如何使用fastapi 快速搭建API 及设置同源

from fastapi import FastAPI
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
import response_code
import requests
from pydantic import BaseModel



app = FastAPI()

// 同源策略, 如果在本机python跑API 同时本机vue调用localhost的API,因为端口号不同不能直接调用, 需要加 中间件,添加origins

origins = [
    "http://localhost:1901",
    "http://localhost",
    "http://localhost:8081"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

// 这样就是一个API
@app.get('/test')
def test(text:str):
    return response_code.resp_200(data={"type": "text", "text": text, "disableInput": False})


if __name__ == '__main__':
    # 命令行启动
    uvicorn.run(app='main:app', host="0.0.0.0", port=8000, reload=True, debug=True)

你可能感兴趣的:(python,python)