作者:fadsfwebb | 来源:互联网 | 2023-07-05 17:15
创建对应得API文件,比如xxx1做了什么呢,实例化一个fastapi蓝图对象,testplat APIRouter()然后使用该属性装饰器定义路由fromfastapiimpo
创建对应得API文件,比如xxx1
做了什么呢,实例化一个fastapi蓝图对象,
testplat = APIRouter()
然后使用该属性装饰器定义路由
from fastapi import APIRouter
testplat = APIRouter()
res = {
"code": 200,
"status": 1,
"result": "1"
}
@testplat.post("/project/addproject")
def addproject():
return res
run.py 运行文件
导入对应API文件,添加蓝图到fastapi实例内。
app.include_router(testplat, prefix='/testplat', tags=['路由A'])
为了确保支持跨域, 导入CORSMiddleware,添加跨域支持,对应允许请求头和方法,地址等
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
from apis.testplat import testplat
from apis.xx.xx import xxx2
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI
from config.initial_config import Service_port
import uvicorn
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(testplat, prefix='/testplat', tags=['路由A'])
app.include_router(xxx2, prefix='/xxx2', tags=['路由B'])
if __name__ == "__main__":
uvicorn.run(app='run:app', host='0.0.0.0', port=6000, reload=True, debug=True)
然后运行起来,即可实现蓝图和api得挂钩关联