1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- import uvicorn as uvicorn
- from fastapi import FastAPI
- from pydantic.main import BaseModel
- from starlette.middleware.cors import CORSMiddleware
- from starlette.middleware.sessions import SessionMiddleware
- from starlette.responses import JSONResponse
- app = FastAPI(title="project name ", description="系统描述 ", version="v 0.0.0")
- app.add_middleware(SessionMiddleware, secret_key='123456hhh')
- app.add_middleware(
- CORSMiddleware,
- allow_origins=["*", ],
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
- )
- @app.exception_handler(Exception)
- def validation_exception_handler(request, exc):
- """请求校验异常捕获; application/json """
- return JSONResponse({'message': "服务器内部错误", 'status_code': 500})
- @app.get("/query")
- def query(uid: str):
- msg = f'uid为{uid}'
- return {'success': True, 'msg': msg}
- @app.get("/query/{uid}")
- def query(uid: str):
- msg = f'uid为{uid}'
- return {'success': True, 'msg': msg}
- class People(BaseModel):
- name: str
- age: int
- address: str
- salary: float
- # json body请求
- @app.post("/insert")
- def insert(people: People):
- msg = f"名字:{people.name},年龄{people.age}"
- return msg
- if __name__ == '__main__':
- uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)
- # 启动命令
- # pip3 install -r /tmp/request.txt -i https://pypi.douban.com/simple/
- # pip3 install uvicorn gunicorn fastapi -i https://pypi.douban.com/simple/
- #
- # gunicorn tmp_app:app -b 0.0.0.0:8000 -w 4 -k uvicorn.workers.UvicornWorker -D # 不支持linux运行 -w 进程数
- # uvicorn tmp_app:app --reload --host 0.0.0.0 --port 8000
|