Skip to main content

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


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.0.tar.gz (4.3 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page