main.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import os
  2. import sys
  3. import time
  4. from pathlib import Path
  5. import uvicorn
  6. import subprocess
  7. from fastapi import FastAPI, UploadFile, File, Form
  8. from fastapi import Request
  9. from fastapi.middleware.cors import CORSMiddleware
  10. from starlette.middleware.sessions import SessionMiddleware
  11. from starlette.responses import JSONResponse, RedirectResponse, FileResponse
  12. # =============== 基础配置 ===============
  13. app = FastAPI(title="project name ", description="通用系统 ", version="v 0.0.0")
  14. # 添加 session 中间键,使项目中可以使用session
  15. app.add_middleware(SessionMiddleware, secret_key='123456hhh')
  16. app.add_middleware(
  17. CORSMiddleware,
  18. allow_origins=["*", ],
  19. allow_credentials=True,
  20. allow_methods=["*"],
  21. allow_headers=["*"],
  22. )
  23. @app.exception_handler(Exception)
  24. async def validation_exception_handler(request, exc):
  25. """请求校验异常捕获; application/json """
  26. return JSONResponse({'message': "服务器内部错误", 'status_code': 500})
  27. @app.middleware("http")
  28. async def add_process_time_header(request: Request, call_next):
  29. """接口响应中间键; 当前只支持 http 请求"""
  30. start_time = time.time()
  31. response = await call_next(request)
  32. process_time = time.time() - start_time
  33. response.headers["API-Process-Time"] = f"{process_time} seconds"
  34. return response
  35. # =============== 代码 ===============
  36. @app.get("/getDataFromJson")
  37. def get_data_from_json():
  38. # 读取本地data.json,获取一级列表
  39. import json
  40. with open('data.json', 'r') as f:
  41. data = json.load(f)
  42. return data
  43. if __name__ == '__main__':
  44. # uvicorn call_sh:app --reload --port 19999
  45. uvicorn.run(app='main:app', host="0.0.0.0", port=9999, reload=True)