tmp_app.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import uvicorn as uvicorn
  2. from fastapi import FastAPI
  3. from pydantic.main import BaseModel
  4. from starlette.middleware.cors import CORSMiddleware
  5. from starlette.middleware.sessions import SessionMiddleware
  6. from starlette.responses import JSONResponse
  7. app = FastAPI(title="project name ", description="系统描述 ", version="v 0.0.0")
  8. app.add_middleware(SessionMiddleware, secret_key='123456hhh')
  9. app.add_middleware(
  10. CORSMiddleware,
  11. allow_origins=["*", ],
  12. allow_credentials=True,
  13. allow_methods=["*"],
  14. allow_headers=["*"],
  15. )
  16. @app.exception_handler(Exception)
  17. def validation_exception_handler(request, exc):
  18. """请求校验异常捕获; application/json """
  19. return JSONResponse({'message': "服务器内部错误", 'status_code': 500})
  20. @app.get("/query")
  21. def query(uid: str):
  22. msg = f'uid为{uid}'
  23. return {'success': True, 'msg': msg}
  24. @app.get("/query/{uid}")
  25. def query(uid: str):
  26. msg = f'uid为{uid}'
  27. return {'success': True, 'msg': msg}
  28. class People(BaseModel):
  29. name: str
  30. age: int
  31. address: str
  32. salary: float
  33. # json body请求
  34. @app.post("/insert")
  35. def insert(people: People):
  36. msg = f"名字:{people.name},年龄{people.age}"
  37. return msg
  38. if __name__ == '__main__':
  39. uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)
  40. # 启动命令
  41. # pip3 install -r /tmp/request.txt -i https://pypi.douban.com/simple/
  42. # pip3 install uvicorn gunicorn fastapi -i https://pypi.douban.com/simple/
  43. #
  44. # gunicorn tmp_app:app -b 0.0.0.0:8000 -w 4 -k uvicorn.workers.UvicornWorker -D # 不支持linux运行 -w 进程数
  45. # uvicorn tmp_app:app --reload --host 0.0.0.0 --port 8000