增加Redis缓存配置
This commit is contained in:
parent
2f7ddd590a
commit
0e63ccc55d
47
api/test.py
47
api/test.py
|
|
@ -1,12 +1,14 @@
|
|||
# Test Router 页面
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from typing import Optional
|
||||
from fastapi_sqlalchemy import db
|
||||
from fastapi import APIRouter, Query, Depends
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
|
||||
import aioredis
|
||||
from fastapi_plugins import depends_redis
|
||||
from fastapi_sqlalchemy import db
|
||||
from models.devices_place import DevicesPlace
|
||||
from pydantic_sqlalchemy import sqlalchemy_to_pydantic
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
router = APIRouter(prefix="/test")
|
||||
|
||||
|
|
@ -16,9 +18,33 @@ def index():
|
|||
return {"msg": "This is Index Page"}
|
||||
|
||||
|
||||
@router.get("/login")
|
||||
def login():
|
||||
return {}
|
||||
# ==================登录验证相关===================================
|
||||
class User(BaseModel):
|
||||
username: str
|
||||
email: Optional[str] = None
|
||||
full_name: Optional[str] = None
|
||||
disabled: Optional[bool] = None
|
||||
|
||||
|
||||
def fake_decode_token(token):
|
||||
return User(
|
||||
username=token + "fakedecoded", email="john@example.com", full_name="John Doe"
|
||||
)
|
||||
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
||||
|
||||
|
||||
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
||||
print("get_current_user...")
|
||||
user = fake_decode_token(token)
|
||||
return user
|
||||
|
||||
|
||||
# 登录验证
|
||||
@router.get("/users/me")
|
||||
async def read_users_me(current_user: User = Depends(get_current_user)):
|
||||
return current_user
|
||||
|
||||
|
||||
# 数据库查询
|
||||
|
|
@ -30,3 +56,10 @@ def query(mid: str = Query(..., description='mid'), region_id: Optional[int] = Q
|
|||
record = db.session.query(DevicesPlace).filter(DevicesPlace.mid == mid)\
|
||||
.filter(DevicesPlace.region_id == region_id).first()
|
||||
return record
|
||||
|
||||
|
||||
# Redis 缓存查询
|
||||
@router.get("/ping")
|
||||
async def ping(cache: aioredis.Redis = Depends(depends_redis)):
|
||||
return dict(ping=await cache.ping())
|
||||
|
||||
|
|
|
|||
51
config.py
51
config.py
|
|
@ -1,7 +1,8 @@
|
|||
import os
|
||||
from configparser import ConfigParser
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseSettings
|
||||
from fastapi_plugins import RedisSettings
|
||||
|
||||
|
||||
class ReConfigParser(ConfigParser):
|
||||
|
|
@ -12,24 +13,33 @@ class ReConfigParser(ConfigParser):
|
|||
def optionxform(self, optionstr):
|
||||
return optionstr
|
||||
|
||||
|
||||
class CommonConfig(BaseModel):
|
||||
SECRET_KEY: str = os.urandom(32)
|
||||
PROJECT_NAME: str
|
||||
API_V1_STR: str
|
||||
# 允许访问的origins
|
||||
BACKEND_CORS_ORIGINS: str
|
||||
# class CommonConfig(BaseSettings):
|
||||
# SECRET_KEY: str = os.urandom(32)
|
||||
# PROJECT_NAME: str
|
||||
# API_V1_STR: str
|
||||
# # 允许访问的origins
|
||||
# BACKEND_CORS_ORIGINS: str
|
||||
|
||||
|
||||
class MySQLConfig(BaseModel):
|
||||
USERNAME: str = None
|
||||
PASSWORD: str = None
|
||||
HOST: Optional[str] = "localhost"
|
||||
PORT: Optional[int] = 3306
|
||||
DATABASE: str = None
|
||||
SQLALCHEMY_DATABASE_URI: str = (
|
||||
f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE}?charset=utf8"
|
||||
)
|
||||
class MySQLConfig(BaseSettings):
|
||||
username: str
|
||||
password: str
|
||||
host: Optional[str] = "localhost"
|
||||
port: Optional[int] = 3306
|
||||
database: str
|
||||
|
||||
@property
|
||||
def sqlalchemy_db_uri(self):
|
||||
return f"mysql+pymysql://{self.username}:{self.password}@{self.host}:{self.port}/{self.database}?charset=utf8"
|
||||
|
||||
|
||||
class RedisConfig(RedisSettings):
|
||||
redis_url: str = None
|
||||
redis_host: Optional[str] = 'localhost'
|
||||
redis_port: Optional[int] = 6379
|
||||
redis_password: str = None
|
||||
redis_db: int = 0
|
||||
redis_connection_timeout: int = 2
|
||||
|
||||
|
||||
def init_config():
|
||||
|
|
@ -41,10 +51,11 @@ def init_config():
|
|||
config.read(os.path.join('.', 'conf', 'conf-prod.ini'), encoding='utf-8')
|
||||
else:
|
||||
config.read(os.path.join('.', 'conf', 'conf-dev.ini'), encoding='utf-8')
|
||||
|
||||
mysql_config = MySQLConfig(**dict(config.items('mysql')))
|
||||
# common_config = CommonConfig(**dict(config.items('common')))
|
||||
return mysql_config
|
||||
mysql_config = MySQLConfig(**dict(config.items('mysql')))
|
||||
print(mysql_config)
|
||||
redis_config = RedisConfig(**dict(config.items('redis')))
|
||||
return mysql_config, redis_config
|
||||
except Exception as e:
|
||||
print(e)
|
||||
raise Exception("Config Error!")
|
||||
|
|
|
|||
19
main.py
19
main.py
|
|
@ -1,6 +1,7 @@
|
|||
import os
|
||||
from fastapi import FastAPI
|
||||
from fastapi_sqlalchemy import DBSessionMiddleware
|
||||
import fastapi_plugins
|
||||
import logging.config as logging_config
|
||||
from config import init_config
|
||||
|
||||
|
|
@ -9,15 +10,21 @@ def create_app():
|
|||
app = FastAPI()
|
||||
|
||||
@app.on_event("startup")
|
||||
def startup_event():
|
||||
async def startup_event():
|
||||
# 日志配置
|
||||
logging_config.fileConfig('conf/log.ini')
|
||||
# logging_config.fileConfig('conf/log.ini')
|
||||
# 初始化配置文件
|
||||
mysql_config = init_config()
|
||||
mysql_config, redis_config = init_config()
|
||||
# 添加sqlalchemy数据库中间件
|
||||
# once the middleware is applied, any route can then access the database session
|
||||
# from the global ``db``
|
||||
app.add_middleware(DBSessionMiddleware, db_url=mysql_config.SQLALCHEMY_DATABASE_URI)
|
||||
# once the middleware is applied, any route can then access the database session from the global ``db``
|
||||
app.add_middleware(DBSessionMiddleware, db_url=mysql_config.sqlalchemy_db_uri)
|
||||
# Redis 缓存初始化
|
||||
await fastapi_plugins.redis_plugin.init_app(app, redis_config)
|
||||
await fastapi_plugins.redis_plugin.init()
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown_event():
|
||||
await fastapi_plugins.redis_plugin.terminate()
|
||||
|
||||
# 在这里添加API route
|
||||
from api import test
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
aiofiles==0.6.0
|
||||
aioredis==1.3.1
|
||||
fastapi==0.63.0
|
||||
fastapi-login==1.5.3
|
||||
FastAPI-SQLAlchemy==0.2.1
|
||||
Jinja2==2.11.2
|
||||
MarkupSafe==1.1.1
|
||||
pydantic==1.8.1
|
||||
pydantic-sqlalchemy==0.0.8.post1
|
||||
|
|
@ -12,5 +11,4 @@ requests==2.24.0
|
|||
sqlacodegen==2.3.0
|
||||
SQLAlchemy==1.3.23
|
||||
starlette==0.13.6
|
||||
uvicorn==0.13.4
|
||||
Werkzeug==1.0.1
|
||||
uvicorn==0.13.4
|
||||
Loading…
Reference in New Issue