call_sh_app.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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("/call_sh")
  37. def call_sh(path: str):
  38. """
  39. echo "$(curl 127.0.0.1:9999/call_sh?path=/Users/mlamp/IdeaProjects/python-base/tmp.sh)"
  40. :param path:
  41. :return:
  42. """
  43. # return os.popen(f"sh {path}").read()
  44. os.system(f"sh {path} &")
  45. return "请等待结果"
  46. def run_shell(shell):
  47. cmd = subprocess.Popen(shell, stdin=subprocess.PIPE, stderr=sys.stderr, close_fds=True,
  48. stdout=sys.stdout, universal_newlines=True, shell=True, bufsize=1)
  49. cmd.communicate()
  50. return cmd.returncode
  51. @app.post("/upload")
  52. def upload(file: UploadFile = File(...), path: str = Form(...)):
  53. """
  54. curl 127.0.0.1:9999/upload -F "file=@稻香.flac" -F 'path=/Users/mlamp/tmp'
  55. :param file:
  56. :param path:
  57. :return:
  58. """
  59. upload_dir = "/tmp/upload"
  60. if not Path(upload_dir).exists():
  61. Path(upload_dir).mkdir()
  62. with open("/tmp/upload/" + file.filename, 'wb') as f:
  63. f.write(file.file.read())
  64. return "OK"
  65. @app.get("/download")
  66. def download(path: str):
  67. """
  68. wget 127.0.0.1:9999/download?path=/Users/mlamp/tmp/稻香.flac
  69. :param path:
  70. :return:
  71. """
  72. return FileResponse(
  73. path,
  74. filename=path.split("/")[-1]
  75. )
  76. if __name__ == '__main__':
  77. # uvicorn call_sh:app --reload --port 19999
  78. uvicorn.run(app='call_sh_app:app', host="0.0.0.0", port=9999, reload=True)