call_sh.py 2.8 KB

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