fastapi创建api和启动命令
""" https://fastapi.tiangolo.com/project-generation/
cors中间件处理跨域 """ from fastapi import FastAPI from pydantic import BaseModel from starlette.middleware.cors import CORSMiddleware from script import Img app = FastAPI() origins = [ "http://localhost.tiangolo.com", "https://localhost.tiangolo.com", "http://localhost", "http://localhost:8080", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) class Picture(BaseModel): img_recv_path: str # 图片路径 img_id: str @app.post('/update_oss') def update_oss(pic: Picture): # 数据详情接口 path_name = pic.img_recv_path print(path_name) img = Img(path_name, pic.img_id) status = img.detail_filename() return {'status': status} @app.get('/') def index(): return {'message': '欢迎来到接口页面'}
第二种创建模式
# main文件 import uvicorn from fastapi import FastAPI from starlette.middleware.cors import CORSMiddleware from moudle.hot import hot_keyword from moudle.login import login app = FastAPI() origins = [ "http://localhost.tiangolo.com", "https://localhost.tiangolo.com", "http://localhost", "http://localhost:8080", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(router=login.loginer) # 路由 @app.get('/api/python') def index(): return {'message': '欢迎来到页面'} if __name__ == '__main__': uvicorn.run(app='main:app', host="0.0.0.0", port=8001)
# 视图文件 from fastapi import APIRouter login= APIRouter() @login.post('/api/Login') def login(d: Login): pass
启动命令
uvicorn main:app --reload --host=0.0.0.0 --port=8008
如何以守护方式启动
使用gunicorn
参考https://www.cnblogs.com/itBlogToYpl/p/13153785.html