[ python ] fastapi使用指南
目录结构, static是html上传的文件 __init__.py 是空文件(前后都是两个杠)
main.py
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles from .api import upload as upload_router from .api import get_user from .api import img app = FastAPI() # 挂载静态资源目录 app.mount("/static", StaticFiles(directory="static"), name="static") app.add_middleware( CORSMiddleware, allow_origins=['*'], allow_credentials=False, allow_methods=["*"], allow_headers=["*"], ) app.include_router(upload_router.router, prefix='/upload', tags=['上传文件']) app.include_router(get_user.router, prefix='/user', tags=['获取用户']) app.include_router(img.router, prefix='/img', tags=['静态资源'])
dependencies.py
import pymysql from pymysql.cursors import DictCursor DB_CONFIG = { 'host': '127.0.0.1', 'user': 'root', 'password': 'yyjeiq', 'database': 'fmg', 'charset': 'utf8mb4', 'cursorclass': DictCursor } # 数据库连接工具函数 def get_db_connection(): return pymysql.connect(**DB_CONFIG)
get_user.py
from fastapi import APIRouter, Depends, Query from ..dependencies import get_db_connection from typing import Annotated router = APIRouter( dependencies=[Depends(get_db_connection)] ) @router.get("/get_list", name="获取用户信息") def get_list(page_id: int | None = None, page_num: int | None = None, username: str | None = None, sex: Annotated[str | None, Query(pattern="^[1|2]$")] = None): with get_db_connection().cursor() as cursor: sql = "select * from tb_student where state = 0" keys = [] vals = [] if username: keys.append(" username like %s ") vals.append(f"%{username}%") if sex: keys.append(" sex = %s ") vals.append(sex) if len(keys): sql += ' and ' sql += ' and '.join(keys) if page_id and page_num: sql += f" limit {(page_id - 1) * page_num} , {page_num}" print(sql) cursor.execute(sql, vals) lis = cursor.fetchall() return lis
img.py
from fastapi import APIRouter, Depends from ..dependencies import get_db_connection router = APIRouter( dependencies=[Depends(get_db_connection)] ) @router.get('/get_imgs') def get_imgs(page_id: int | None = None, page_num: int | None = None): with get_db_connection().cursor() as cursor: sql = "select * from tb_imgs where state = 0" if page_id and page_num: sql += f" limit {(page_id - 1) * page_num} , {page_num}" print(sql) cursor.execute(sql) lis = cursor.fetchall() return lis
upload.py
from fastapi import UploadFile, File, APIRouter, Depends from typing import List import time from ..dependencies import get_db_connection router = APIRouter( dependencies=[Depends(get_db_connection)] ) # 单个文件上传 @router.post('/upload_file', tags=['上传文件'], description="单个文件上传") async def upload_file(file: UploadFile = File(...)): content = await file.read() less = file.filename.rsplit('.')[1] f_name = str(int(time.time())) with open(f'./static/{f_name}.{less}', 'ab') as f: f.write(content) url = f"http://127.0.0.1:8000/static/{f_name}.{less}" db = get_db_connection() cursor = db.cursor() cursor.execute('insert into tb_imgs(url) values(%s)', url) db.commit() return { "url": url } # 多个文件上传 @router.post('/upload_files', tags=['上传文件'], description="文件批量上传") async def upload_files(files: List[UploadFile] = File(...)): urls = [] for file in files: content = await file.read() less = file.filename.rsplit('.')[1] f_name = str(int(time.time())) with open(f'./static/{f_name}.{less}', 'ab') as f: f.write(content) urls.append(f'"http://127.0.0.1:8000/static/{f_name}.{less}') return { "urls": urls }
项目启动命令
fastapi dev main.py # 官网写的uvicorn ... 那个,太难记了...
本想把生活活成一首诗, 时而优雅 , 时而豪放 , 结果活成了一首歌 , 时而不靠谱 , 时而不着调