fastapi_sqlalchemy
"""
SQLAlchemy
"""
# SQlAlchemy
from sqlalchemy import Column, Integer, String, DateTime, func, select
from sqlalchemy.orm import declarative_base
Base = declarative_base()
# 创建生成表的类
class SqlAlchemyTable(Base):
__tablename__ = "a" # table name就是表的名字
# 属性,就是表中的字段
id = Column(Integer, primary_key=True)
data = Column(String)
create_date = Column(DateTime, server_default=func.now())
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
# 创建engine 和session
engine = create_async_engine("sqlite+aiosqlite:///basic.sqlite3")
async_session = sessionmaker(
engine, expire_on_commit=True, class_=AsyncSession
)
from fastapi import FastAPI, Depends
from pydantic import BaseModel
class Response(BaseModel):
id: int
data: str
app = FastAPI(title="SQLAlchemy & TortoiseORM")
@app.get("/", response_model=Response)
async def index():
# 方式一:with 形式
async with async_session() as session:
result = await session.execute(select(SqlAlchemyTable).order_by(SqlAlchemyTable.id))
return result.scalars().first().__dict__ # 第一条
# 注入的函数
def get_db():
session = async_session()
try:
yield session
finally:
session.close()
@app.get("/index")
async def index1(db: AsyncSession = Depends(get_db)):
# 方式二: 依赖注入的形式
result = await db.execute(select(SqlAlchemyTable).order_by(SqlAlchemyTable.id))
return result.scalars().all() # 所有
if __name__ == '__main__':
import uvicorn
uvicorn.run("__main__:app", reload=True)
标签:__,engine,sqlalchemy,fastapi,session,demo,async,import
From: https://www.cnblogs.com/zhuoss/p/17110699.html