From dfd34a6237bb32dc83c11946cb89eaa169d4e1d4 Mon Sep 17 00:00:00 2001 From: shikong <919411476@qq.com> Date: Wed, 31 May 2023 11:52:34 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BD=BF=E7=94=A8=20fastapi=20=E9=87=8D?= =?UTF-8?q?=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.MD | 20 ++++++ backend/main.py | 72 ------------------- backend/orm/__init__.py | 1 - backend/orm/main.py | 22 ------ backend/response/response.py | 9 --- {backend/response => db}/__init__.py | 0 db/mysql.py | 21 ++++++ handler/car.py | 38 ++++++++++ handler/health.py | 11 +++ logger/__init__.py | 2 + main.py | 13 ++++ {backend/utils => orm}/__init__.py | 0 {backend/orm => orm}/jiakaobaodian.py | 0 backend/requirements.txt => requirements.txt | Bin 6726 -> 6922 bytes utils/__init__.py | 0 {backend/utils => utils}/common.py | 8 +++ {backend/utils => utils}/model.py | 0 17 files changed, 113 insertions(+), 104 deletions(-) create mode 100644 README.MD delete mode 100644 backend/main.py delete mode 100644 backend/orm/__init__.py delete mode 100644 backend/orm/main.py delete mode 100644 backend/response/response.py rename {backend/response => db}/__init__.py (100%) create mode 100644 db/mysql.py create mode 100644 handler/car.py create mode 100644 handler/health.py create mode 100644 logger/__init__.py create mode 100644 main.py rename {backend/utils => orm}/__init__.py (100%) rename {backend/orm => orm}/jiakaobaodian.py (100%) rename backend/requirements.txt => requirements.txt (97%) create mode 100644 utils/__init__.py rename {backend/utils => utils}/common.py (79%) rename {backend/utils => utils}/model.py (100%) diff --git a/README.MD b/README.MD new file mode 100644 index 0000000..d4b9454 --- /dev/null +++ b/README.MD @@ -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 diff --git a/backend/main.py b/backend/main.py deleted file mode 100644 index 70595ab..0000000 --- a/backend/main.py +++ /dev/null @@ -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) diff --git a/backend/orm/__init__.py b/backend/orm/__init__.py deleted file mode 100644 index 8b13789..0000000 --- a/backend/orm/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/backend/orm/main.py b/backend/orm/main.py deleted file mode 100644 index bf84260..0000000 --- a/backend/orm/main.py +++ /dev/null @@ -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() diff --git a/backend/response/response.py b/backend/response/response.py deleted file mode 100644 index 21f84a9..0000000 --- a/backend/response/response.py +++ /dev/null @@ -1,9 +0,0 @@ -from flask import jsonify - - -def response(data: any, code=200, msg="OK"): - return jsonify({ - "code": code, - "data": data, - "msg": msg, - }) diff --git a/backend/response/__init__.py b/db/__init__.py similarity index 100% rename from backend/response/__init__.py rename to db/__init__.py diff --git a/db/mysql.py b/db/mysql.py new file mode 100644 index 0000000..dff0a09 --- /dev/null +++ b/db/mysql.py @@ -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() diff --git a/handler/car.py b/handler/car.py new file mode 100644 index 0000000..0378bba --- /dev/null +++ b/handler/car.py @@ -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 + }) diff --git a/handler/health.py b/handler/health.py new file mode 100644 index 0000000..4c9a23e --- /dev/null +++ b/handler/health.py @@ -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") diff --git a/logger/__init__.py b/logger/__init__.py new file mode 100644 index 0000000..7212bbd --- /dev/null +++ b/logger/__init__.py @@ -0,0 +1,2 @@ +from loguru import logger + diff --git a/main.py b/main.py new file mode 100644 index 0000000..c4d2114 --- /dev/null +++ b/main.py @@ -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) diff --git a/backend/utils/__init__.py b/orm/__init__.py similarity index 100% rename from backend/utils/__init__.py rename to orm/__init__.py diff --git a/backend/orm/jiakaobaodian.py b/orm/jiakaobaodian.py similarity index 100% rename from backend/orm/jiakaobaodian.py rename to orm/jiakaobaodian.py diff --git a/backend/requirements.txt b/requirements.txt similarity index 97% rename from backend/requirements.txt rename to requirements.txt index 817013fd26211e4fb641cff015199af56979ff17..27b4ed3b2dcd61f12f18985807548830c7cc53f9 100644 GIT binary patch delta 168 zcmX?R(q*>6fJ3l^As+~H7>XHefzW_KZ?i1NQzp?IpkO*fDMJwuLnRo@H~-`kW|vF> zN|i9AGUPFofu#%?^g#L;3^xB1EM=EX1WG0|WH6*LWCD#%MHtLr$Y41+Su$U<94M2= fV9a2|pbL~u1*Yf(@N~R