call_sh.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import os
  2. import time
  3. import uvicorn
  4. import subprocess
  5. from fastapi import FastAPI, UploadFile, File, Form
  6. from fastapi import Request
  7. from fastapi.middleware.cors import CORSMiddleware
  8. from starlette.middleware.sessions import SessionMiddleware
  9. from starlette.responses import JSONResponse, RedirectResponse, FileResponse
  10. def save_upload_file(file: UploadFile, dir_path=None, file_name=None):
  11. if not dir_path:
  12. dir_path = "./"
  13. if not dir_path.endswith("/"):
  14. dir_path += "/"
  15. if not file_name:
  16. file_name = file.filename
  17. with open(dir_path + file_name, 'wb') as f:
  18. f.write(file.file.read())
  19. app = FastAPI(title="project name ", description="通用系统 ", version="v 0.0.0")
  20. # 添加 session 中间键,使项目中可以使用session
  21. app.add_middleware(SessionMiddleware, secret_key='123456hhh')
  22. app.add_middleware(
  23. CORSMiddleware,
  24. allow_origins=["*", ],
  25. allow_credentials=True,
  26. allow_methods=["*"],
  27. allow_headers=["*"],
  28. )
  29. @app.exception_handler(Exception)
  30. async def validation_exception_handler(request, exc):
  31. """请求校验异常捕获; application/json """
  32. return JSONResponse({'message': "服务器内部错误", 'status_code': 500})
  33. @app.middleware("http")
  34. async def add_process_time_header(request: Request, call_next):
  35. """接口响应中间键; 当前只支持 http 请求"""
  36. start_time = time.time()
  37. response = await call_next(request)
  38. process_time = time.time() - start_time
  39. response.headers["API-Process-Time"] = f"{process_time} seconds"
  40. return response
  41. @app.get("/call_sh")
  42. def call_sh(path: str):
  43. """
  44. echo "$(curl 127.0.0.1:9999/call_sh?path=/Users/mlamp/IdeaProjects/python-base/tmp.sh)"
  45. :param path:
  46. :return:
  47. """
  48. read = os.popen(f"sh {path}").read()
  49. print(read)
  50. return os.popen(f"sh {path}").read()
  51. # return subprocess.call(f"sh {path}")
  52. @app.post("/upload")
  53. def upload(file: UploadFile = File(...), path: str = Form(...)):
  54. """
  55. curl 127.0.0.1:9999/upload -F "file=@稻香.flac" -F 'path=/Users/mlamp/tmp'
  56. :param file:
  57. :param path:
  58. :return:
  59. """
  60. save_upload_file(file, path)
  61. return "OK"
  62. @app.get("/download")
  63. def download(path: str):
  64. """
  65. wget 127.0.0.1:9999/download?path=/Users/mlamp/tmp/稻香.flac
  66. :param path:
  67. :return:
  68. """
  69. return FileResponse(
  70. path,
  71. filename=path.split("/")[-1]
  72. )
  73. if __name__ == '__main__':
  74. # uvicorn call_sh:app --reload --port 19999
  75. uvicorn.run(app='call_sh:app', host="0.0.0.0", port=9999, reload=True, debug=True)