Skip to content

Commit ae7aa63

Browse files
author
lan-air
committed
完善 aiosqlite 异步数据库驱动
1 parent b999073 commit ae7aa63

File tree

3 files changed

+13
-3
lines changed

3 files changed

+13
-3
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ __pycache__/
88
# Created by .ignore support plugin (hsz.mobi)
99
### Python template
1010
# Byte-compiled / optimized / DLL files
11-
database.db
11+
databasea.db
1212
# C extensions
1313
*.so
1414
*.env

database.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import asyncio
12
import datetime
23

34
from sqlalchemy import Boolean, Column, Integer, String, DateTime
@@ -9,7 +10,10 @@
910

1011
Base = declarative_base()
1112

12-
Base.metadata.create_all(bind=engine)
13+
14+
async def init_models():
15+
async with engine.begin() as conn:
16+
await conn.run_sync(Base.metadata.create_all)
1317

1418

1519
async def get_session():

main.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,19 @@
1111
from sqlalchemy import or_, select, update, delete
1212
from sqlalchemy.ext.asyncio.session import AsyncSession
1313

14-
from database import get_session, Codes
14+
from database import get_session, Codes, init_models
1515

1616
app = FastAPI()
1717
if not os.path.exists('./static'):
1818
os.makedirs('./static')
1919
app.mount("/static", StaticFiles(directory="static"), name="static")
2020

21+
22+
@app.on_event('startup')
23+
async def startup():
24+
await init_models()
25+
26+
2127
############################################
2228
# 需要修改的参数
2329
# 允许错误次数

0 commit comments

Comments
 (0)