fastapi 目录结构
fastapi 解决跨域
"""apt app 后端服务启动"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from apt_app_service.apps.antifraud.app_views.files_views import antifraud_files_router
from apt_app_service.apps.antifraud.app_views.urls_views import antifraud_urls_router
from apt_app_service.apps.antifraud.app_views.result_views import antifraud_results_router
from apt_app_service.apps.antifraud.app_views.feedback_views import antifraud_feedback_router
app = FastAPI(title='apt 接口文档')
app.add_middleware(
CORSMiddleware,
# 允许跨域的源列表,例如 ["http://www.example.org"] 等等,["*"] 表示允许任何源
allow_origins=["*"],
# 跨域请求是否支持 cookie,默认是 False,如果为 True,allow_origins 必须为具体的源,不可以是 ["*"]
allow_credentials=True,
# 允许跨域请求的 HTTP 方法列表,默认是 ["GET"]
allow_methods=["*"],
# 允许跨域请求的 HTTP 请求头列表,默认是 [],可以使用 ["*"] 表示允许所有的请求头
# 当然 Accept、Accept-Language、Content-Language 以及 Content-Type 总之被允许的
allow_headers=["*"],
# 可以被浏览器访问的响应头, 默认是 [],一般很少指定
expose_headers=["*"]
# 设定浏览器缓存 CORS 响应的最长时间,单位是秒。默认为 600,一般也很少指定
# max_age=1000
)
app.include_router(antifraud_files_router)
app.include_router(antifraud_urls_router)
app.include_router(antifraud_results_router)
app.include_router(antifraud_feedback_router)
# uvicorn main:app --host 0.0.0.0 --port 8000 --reload
fastapi 后台任务
# 视图函数
antifraud_urls_router = APIRouter(
prefix="/antifraud/api/v1/urls",
tags=["antifraud_urls"],
responses={404: {"description": "Not found"}},
)
@antifraud_urls_router.post("/")
async def upload_urls(background_tasks: BackgroundTasks, urls: List[str]):
background_tasks.add_task(check_files, [uid, 'url', url])
# 后台任务执行函数
async def check_files(files_list:list):
print('开始执行检测异步任务')
fastapi 路由分发
# 入口文件:main.py
"""apt app 后端服务启动"""
from fastapi import FastAPI
from apt_app_service.apps.antifraud.app_views.files_views import antifraud_files_router
from apt_app_service.apps.antifraud.app_views.urls_views import antifraud_urls_router
from apt_app_service.apps.antifraud.app_views.result_views import antifraud_results_router
from apt_app_service.apps.antifraud.app_views.feedback_views import antifraud_feedback_router
app = FastAPI(title='apt 接口文档')
# 注册路由
app.include_router(antifraud_files_router)
app.include_router(antifraud_urls_router)
app.include_router(antifraud_results_router)
app.include_router(antifraud_feedback_router)
# uvicorn main:app --host 0.0.0.0 --port 8000 --reload
# 视图函数:files_views.py
from fastapi import APIRouter
from typing import List
from fastapi import File, UploadFile
# 实例化视图函数中的子路由,
# 注意:不要想着把路由放到别的文件,就和视图函数放到一起,试了没成功。这样也挺好。
antifraud_files_router = APIRouter(
prefix="/antifraud/api/v1/files",
tags=["antifraud_files"],
responses={404: {"description": "Not found"}},
)
@antifraud_files_router.post("/")
async def upload_files(files: List[UploadFile] = File(...)):
"""上传多个文件"""