fastapi使用sqlalchemy任意接口位置获取db上下文,非常安全并可靠。
Project description
FastAPI DB
用于 fastapi 应用,可随时获取上下文,使用sqlalchemy,封装Base让模型类直接查询。
import random
import uvicorn
from fastapi import FastAPI
from fastapi_db import FastAPIDBMiddleware, DeclarativeModel, ctx
from sqlalchemy import Column, String, create_engine, Integer
app = FastAPI()
engine = create_engine('sqlite:///test.db')
app.add_middleware(FastAPIDBMiddleware, engine=engine)
class Base(DeclarativeModel):
__abstract__ = True
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(32), nullable=False, unique=True)
Base.metadata.create_all(engine)
@app.get('/user')
def get_list():
users = User.query().all()
return users
@app.get('/create')
def create_user(username: str = None):
if username is None:
username = str(random.randint(1, 99999))
user = User(username=username)
"""你可以在接口的任意位置获取session并使用"""
ctx.session.add(user)
"""如果你需要返回自增id,注意请不要在业务层随意添加commit,这会导致你的程序不可控,添加flush可以解决很多问题"""
ctx.session.flush()
return user
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=9001)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
fastapi_db-0.1.3.tar.gz
(5.2 kB
view hashes)
Built Distribution
Close
Hashes for fastapi_db-0.1.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | fab831f1c515ace9df6d2cca80b31fafdf5bc138c806d3bd1b94b75de1f6cdac |
|
MD5 | e67f03c0c6cac27d316d924e1032a312 |
|
BLAKE2b-256 | 0b30ddc9d7cbd756c825ffffffafaf779a74b9346a1d7cf43bf7cd36c68d9853 |