使用 fastapi 重构

This commit is contained in:
shikong 2023-05-31 11:52:34 +08:00
parent 808f1f6100
commit dfd34a6237
17 changed files with 113 additions and 104 deletions

20
README.MD Normal file
View File

@ -0,0 +1,20 @@
### 生成 requirements.txt
```shell
pip freeze > requirements.txt
```
### fastapi
```shell
pip install fastapi
pip install "uvicorn[standard]"
```
### 运行
```shell
# uvicorn [文件]:[fastapi 对象] --reload --port [端口号]
# uvicorn main:app --reload --port 5000
python main.py
```
### swagger 地址
> http://127.0.0.1:5000/docs

View File

@ -1,72 +0,0 @@
import distutils
import logging
from flask import Flask, current_app, request
from flask_sqlalchemy import SQLAlchemy
from utils.model import model_list
from utils.common import strtobool
from orm.jiakaobaodian import JiaKaoBaoDian
from response.response import response
app = Flask(__name__)
formatter = logging.Formatter("[%(asctime)s][%(filename)s:%(lineno)d][%(levelname)s][%(thread)d] - %(message)s")
# 输出到文件
# handler = TimedRotatingFileHandler("logs.log",
# when="D",
# interval=1,
# backupCount=0,
# encoding="UTF-8",
# delay=False,
# utc=True,)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
app.logger.handlers[0].setFormatter(formatter)
app.logger.setLevel(logging.DEBUG)
# 设置数据库连接地址
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:12341234@10.10.10.200:3306/car'
# 是否追踪数据库修改(开启后会触发一些钩子函数) 一般不开启, 会影响性能
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 是否显示底层执行的SQL语句
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
@app.get("/health")
def health():
current_app.logger.info("666")
return response("OK")
@app.get("/car/list")
def car_all():
args = request.args
page = int(args.get("page", 1))
size = int(args.get("size", 10))
keyword = str(args.get("keyword", ""))
order_by_wrong_rate = strtobool(args.get("sortByWrongRate", 'True'))
current_app.logger.info("page => %d, size => %d, keyword => %s", page, size, keyword)
query = db.session.query(JiaKaoBaoDian)
if len(keyword) > 0:
query = query.filter(JiaKaoBaoDian.question.like("%%%s%%" % keyword))
if order_by_wrong_rate:
query = query.order_by(JiaKaoBaoDian.wrong_rate.desc())
total = query.count()
offset = (page - 1) * size
data = query.offset(offset).limit(size).all()
current_app.logger.info("data num %d", len(data))
return response({
"data": model_list(data),
"page": page,
"size": size,
"total": total
})
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=True)

View File

@ -1 +0,0 @@

View File

@ -1,22 +0,0 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from jiakaobaodian import JiaKaoBaoDian
db = create_engine('mysql+pymysql://', connect_args={
'user': "root",
'password': "12341234",
'host': '10.10.10.200',
'port': 3306,
'database': 'car',
'charset': 'utf8mb4'
})
if __name__ == '__main__':
_session = sessionmaker(db)
session = _session()
data = session.query(JiaKaoBaoDian).filter(JiaKaoBaoDian.question.like("%驾驶%")).all()
for item in data:
print(item.to_json())
session.close()

View File

@ -1,9 +0,0 @@
from flask import jsonify
def response(data: any, code=200, msg="OK"):
return jsonify({
"code": code,
"data": data,
"msg": msg,
})

21
db/mysql.py Normal file
View File

@ -0,0 +1,21 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql+pymysql://', connect_args={
'user': "root",
'password': "12341234",
'host': '10.10.10.200',
'port': 3306,
'database': 'car',
'charset': 'utf8mb4'
})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def database():
_db = SessionLocal()
try:
yield _db
finally:
_db.close()

38
handler/car.py Normal file
View File

@ -0,0 +1,38 @@
from sqlalchemy.orm import Session
import logger
from fastapi import APIRouter, Depends, Query
from db.mysql import database
from orm.jiakaobaodian import JiaKaoBaoDian
from utils.common import response, strtobool
from utils.model import model_list
router = APIRouter(tags=["Car"], prefix="/car")
@router.get("/list")
def get_list(db: Session = Depends(database),
page: int = Query(default=1),
size: int = Query(default=10),
keyword: str = Query(default=""),
order_by_wrong_rate: bool = Query(default=True)):
logger.logger.info("page => %d, size => %d, keyword => %s", page, size, keyword)
query = db.query(JiaKaoBaoDian)
if len(keyword) > 0:
query = query.filter(JiaKaoBaoDian.question.like("%%%s%%" % keyword))
if order_by_wrong_rate:
query = query.order_by(JiaKaoBaoDian.wrong_rate.desc())
total = query.count()
offset = (page - 1) * size
data = query.offset(offset).limit(size).all()
logger.logger.info("data num %d", len(data))
return response({
"data": model_list(data),
"page": page,
"size": size,
"total": total
})

11
handler/health.py Normal file
View File

@ -0,0 +1,11 @@
import logger
from fastapi import APIRouter
from utils.common import response
router = APIRouter(tags=["Health"])
@router.get("/health")
def health():
logger.logger.info("health")
return response("OK")

2
logger/__init__.py Normal file
View File

@ -0,0 +1,2 @@
from loguru import logger

13
main.py Normal file
View File

@ -0,0 +1,13 @@
import uvicorn
from fastapi import FastAPI
from handler import car, health
# 禁用 redoc
app = FastAPI(docs_url="/docs", redoc_url=None)
app.include_router(health.router)
app.include_router(car.router)
if __name__ == '__main__':
uvicorn.run("main:app", host="0.0.0.0", port=5000, reload=True)

0
utils/__init__.py Normal file
View File

View File

@ -11,3 +11,11 @@ def strtobool(val):
return 0 return 0
else: else:
raise ValueError("invalid truth value %r" % (val,)) raise ValueError("invalid truth value %r" % (val,))
def response(data: any, code=200, msg="OK"):
return {
"code": code,
"data": data,
"msg": msg,
}