-
guest说:
fastapi+sqlalchemy+pydantic 查询数据库中student所有数据并return
from fastapi import FastAPI
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pydantic import BaseModel创建数据库连接
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test')
Base = declarative_base()创建会话
DBSession = sessionmaker(bind=engine)
定义数据库模型
class Student(Base):
tablename = 'student'
id = Column(Integer, primary_key=True)
name = Column(String(64))
age = Column(Integer)将数据库模型映射到pydantic模型
class Student_Model(BaseModel):
id: int
name: str
age: int创建FastAPI对象
app = FastAPI()
定义查询接口,返回所有student数据
@app.get('/student/')
def student_list():
session = DBSession()
query = session.query(Student).all()
data = [Student_Model(**item.dict).dict() for item in query]
session.close()
return data -
guest说:
fastapi+sqlalchemy+pydantic 查询数据库中student表中所有数据并return
# models.py from pydantic import BaseModel class Student(BaseModel): id: int name: str age: int # main.py from fastapi import FastAPI from sqlalchemy import create_engine from sqlalchemy.orm import Session from models import Student app = FastAPI() # 创建连接数据库的engine engine = create_engine("connect_string") @app.get("/students/") def get_students(): session = Session(engine) students = session.query(Student).all() session.close() return students
-
guest说:
fastapi+sqlalchemy+pydantic 查询数据库中整张表数据并返回json格式数据
from fastapi import FastAPI
from pydantic import BaseModel
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.automap import automap_base创建连接
engine = create_engine('mysql+pymysql://user:password@localhost/database?charset=utf8')
创建会话
Session = sessionmaker(bind=engine)
session = Session()创建基类
Base = automap_base()
创建映射
Base.prepare(engine, reflect=True)
检索表
Table = Base.classes.table
创建FastAPI实例
app = FastAPI()
定义模型
class Item(BaseModel):
id: int
name: str查询数据
@app.get('/item/{id}')
def get_item(id: int):
item = session.query(Table).filter(Table.id == id).all()
return Item(**item[0].dict) -
guest说:
下面这段代码报错
def read_jsjldw(jsjldw: str,db: Session = Depends(config.config.get_db)): jsjldw = db.query(Jsjldw).all() data = jsjldwBase(**jsjldw[0].dict) return data
报错信息:'Jsjldw' object has no attribute 'dict'
请帮我按照报错信息修改下代码,谢谢
:
def read_jsjldw(jsjldw: str,db: Session = Depends(config.config.get_db)):
jsjldw = db.query(Jsjldw).all()
data = jsjldwBase(**jsjldw[0].dict)
return data -
guest说:
帮我检查下面这段代码
def read_jsjldw(jsjldw: str,db: Session = Depends(config.config.get_db)): jsjldw = db.query(Jsjldw).all() data = jsjldwBase(**jsjldw[0].dict) return data
应该改成:
def read_jsjldw(db: Session = Depends(config.config.get_db)): jsjldw = db.query(Jsjldw).all() data = jsjldwBase(**jsjldw[0].dict) return data
-
guest说:
fastapi 日志命名方式按天生产新日志
在fastapi项目中,可以通过使用
logging.handlers.TimedRotatingFileHandler
来实现按天生成新日志的功能。import logging from logging.handlers import TimedRotatingFileHandler # 设置日志处理器 handler = TimedRotatingFileHandler('fastapi.log', when='D', interval=1, backupCount=7) # 设置日志格式 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # 设置日志级别 handler.setLevel(logging.INFO) # 将处理器添加到日志对象中 logger = logging.getLogger('fastapi') logger.addHandler(handler) # 使用日志记录消息 logger.info('This is an info message.')
上面的代码将会在fastapi.log文件夹中创建按天生成的日志文件,并且只保留最近7天的日志文件。