Compare commits

...

1 Commits

Author SHA1 Message Date
chenweijia 40d25d2990 fix: 初始化异步数据库操作分支 2024-08-13 15:54:12 +08:00
6 changed files with 34 additions and 29 deletions

View File

@ -30,8 +30,11 @@ class MySQLConfig(BaseSettings):
@property @property
def sqlalchemy_db_uri(self): def sqlalchemy_db_uri(self):
return f"mysql+pymysql://{self.username}:{self.password}@{self.host}:{self.port}/{self.database}?charset=utf8" return f"mysql+pymysql://{self.username}:{self.password}@{self.host}:{self.port}/{self.database}?charset=utf8mb4"
@property
def async_sqlalchemy_db_uri(self):
return f"mysql+aiomysql://{self.username}:{self.password}@{self.host}:{self.port}/{self.database}?charset=utf8mb4"
class RedisConfig(RedisSettings): class RedisConfig(RedisSettings):
redis_host: Optional[str] = 'localhost' redis_host: Optional[str] = 'localhost'

View File

@ -5,7 +5,7 @@ import fastapi_plugins
from fastapi import FastAPI, Request from fastapi import FastAPI, Request
from fastapi.exceptions import HTTPException, RequestValidationError from fastapi.exceptions import HTTPException, RequestValidationError
from fastapi.middleware.wsgi import WSGIMiddleware from fastapi.middleware.wsgi import WSGIMiddleware
from fastapi_sqlalchemy import DBSessionMiddleware from fastapi_async_sqlalchemy import SQLAlchemyMiddleware
from config import init_config from config import init_config
# from src.middleware.flask import flask_app # from src.middleware.flask import flask_app
@ -18,7 +18,7 @@ def create_app():
mysql_config, redis_config = init_config() mysql_config, redis_config = init_config()
# 添加sqlalchemy数据库中间件 # 添加sqlalchemy数据库中间件
# once the middleware is applied, any route can then access the database session from the global ``db`` # 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) app.add_middleware(SQLAlchemyMiddleware, db_url=mysql_config.async_sqlalchemy_db_uri)
@app.on_event("startup") @app.on_event("startup")
async def startup_event(): async def startup_event():

42
poetry.lock generated
View File

@ -397,6 +397,26 @@ type = "legacy"
url = "https://pypi.tuna.tsinghua.edu.cn/simple" url = "https://pypi.tuna.tsinghua.edu.cn/simple"
reference = "mirrors" reference = "mirrors"
[[package]]
name = "fastapi-async-sqlalchemy"
version = "0.6.1"
description = "SQLAlchemy middleware for FastAPI"
optional = false
python-versions = ">=3.7"
files = [
{file = "fastapi-async-sqlalchemy-0.6.1.tar.gz", hash = "sha256:c4e0c9832e5e7ef9d647e7eb134e6d326945dca28323e503a21f3d4ab2dee160"},
{file = "fastapi_async_sqlalchemy-0.6.1-py3-none-any.whl", hash = "sha256:0f4edfbc7b0f5fc2e0017cd903a953f4e0b01870f09e86cd0bc79087f3606bc4"},
]
[package.dependencies]
SQLAlchemy = ">=1.4.19"
starlette = ">=0.13.6"
[package.source]
type = "legacy"
url = "https://pypi.tuna.tsinghua.edu.cn/simple"
reference = "mirrors"
[[package]] [[package]]
name = "fastapi-cli" name = "fastapi-cli"
version = "0.0.4" version = "0.0.4"
@ -450,26 +470,6 @@ type = "legacy"
url = "https://pypi.tuna.tsinghua.edu.cn/simple" url = "https://pypi.tuna.tsinghua.edu.cn/simple"
reference = "mirrors" reference = "mirrors"
[[package]]
name = "fastapi-sqlalchemy"
version = "0.2.1"
description = "Adds simple SQLAlchemy support to FastAPI"
optional = false
python-versions = ">=3.7"
files = [
{file = "FastAPI-SQLAlchemy-0.2.1.tar.gz", hash = "sha256:7a9d44e46cbc73c3f5ee8c444f7e0bcd3d01370a878740abd4cd4d2e900ce9af"},
{file = "FastAPI_SQLAlchemy-0.2.1-py3-none-any.whl", hash = "sha256:d3bfc6d9388a73a2c3726bc6bd7764cd82debfa71c16e3991c544b9701f48d96"},
]
[package.dependencies]
SQLAlchemy = ">=1.2"
starlette = ">=0.12.9"
[package.source]
type = "legacy"
url = "https://pypi.tuna.tsinghua.edu.cn/simple"
reference = "mirrors"
[[package]] [[package]]
name = "greenlet" name = "greenlet"
version = "3.0.3" version = "3.0.3"
@ -2116,4 +2116,4 @@ reference = "mirrors"
[metadata] [metadata]
lock-version = "2.0" lock-version = "2.0"
python-versions = "^3.10" python-versions = "^3.10"
content-hash = "39a4bc6981b275faba68cb572e406a60300d2d868e646fbbf62ad251e2288e37" content-hash = "a2d3f4dd231a21f18cf3bb4faabebaa59ee95ec5597b388c83326036eda1b458"

View File

@ -13,12 +13,12 @@ sqlalchemy = "2.0.0"
aioredis = "2.0.1" aioredis = "2.0.1"
aiomysql = "0.1.1" aiomysql = "0.1.1"
fastapi-plugins = "0.13.0" fastapi-plugins = "0.13.0"
fastapi-sqlalchemy = "^0.2.1"
passlib = "^1.7.4" passlib = "^1.7.4"
pytz = "^2024.1" pytz = "^2024.1"
qiniu = "^7.13.2" qiniu = "^7.13.2"
pillow = "^10.4.0" pillow = "^10.4.0"
captcha = "^0.6.0" captcha = "^0.6.0"
fastapi-async-sqlalchemy = "^0.6.1"
[[tool.poetry.source]] [[tool.poetry.source]]

View File

@ -5,7 +5,7 @@ import aioredis
from fastapi import APIRouter, Depends, Query from fastapi import APIRouter, Depends, Query
from fastapi.security import OAuth2PasswordBearer from fastapi.security import OAuth2PasswordBearer
from fastapi_plugins import depends_redis from fastapi_plugins import depends_redis
from fastapi_sqlalchemy import db from fastapi_async_sqlalchemy import db
from sqlalchemy.sql import text from sqlalchemy.sql import text
from pydantic import BaseModel from pydantic import BaseModel
@ -64,8 +64,10 @@ async def get_user_list_pages(page: int = Query(..., description="当前页码")
# 数据库查询 # 数据库查询
@router.get('/get_db_version') @router.get('/get_db_version')
async def get_db_version(): async def get_db_version():
result = db.session.execute(text("SELECT version()")).first() async with db():
return dict(result=result.tuple()[0]) result = await db.session.execute(text("SELECT version()"))
version = result.first().tuple()[0]
return dict(result=version)
# Redis 缓存查询 # Redis 缓存查询
@router.get("/ping") @router.get("/ping")

View File

@ -4,7 +4,7 @@ from traceback import format_exc
import struct import struct
import sqlalchemy import sqlalchemy
from sqlalchemy import text from sqlalchemy import text
from fastapi_sqlalchemy import db from fastapi_async_sqlalchemy import db
from jinja2 import Template from jinja2 import Template
from pymysql import err from pymysql import err
from pymysql.constants import FIELD_TYPE from pymysql.constants import FIELD_TYPE