files.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import io
  2. import json
  3. import time
  4. from datetime import datetime, timedelta, timezone
  5. from app.common.decorators import verify_all
  6. import app.crud as crud
  7. from fastapi import APIRouter, File, UploadFile, Form, Depends
  8. from sqlalchemy.orm import Session
  9. from fastapi.responses import StreamingResponse
  10. from utils.sx_time import sxtimeit
  11. from utils.sx_web import web_try
  12. from app.common.minio import minio_client
  13. from configs.globals import g
  14. from app import get_db
  15. router = APIRouter(
  16. prefix="/jpt/files",
  17. tags=["files-文件管理"],
  18. )
  19. @router.delete("/dag", dependencies=[Depends(verify_all)])
  20. @web_try()
  21. @sxtimeit
  22. def delete_dag_file(uri: str,db: Session = Depends(get_db)):
  23. res = crud.get_jm_homework_by_dag_url(db,uri)
  24. if len(res) == 0:
  25. minio_client.del_file(uri)
  26. else:
  27. raise Exception("该算子正在被作业使用,不可删除")
  28. @router.post("/upload_file", dependencies=[Depends(verify_all)])
  29. @web_try()
  30. @sxtimeit
  31. def upload_file(file: UploadFile = File(...), file_type: str=Form(...)):
  32. print("UploadFile-->",file.filename)
  33. file_name = str(int(time.time()))+'_'+file.filename
  34. url = minio_client.put_byte_file(f"{g.project_id}/{file_type}/"+file_name, file.file.read())
  35. return url
  36. @router.get("/directory", dependencies=[Depends(verify_all)])
  37. @web_try()
  38. @sxtimeit
  39. def get_directory(file_type: str):
  40. files = minio_client.ls_file(f'{g.project_id}/{file_type}/')
  41. res = []
  42. td = timedelta(hours=8)
  43. tz = timezone(td)
  44. for file in files:
  45. timestamp = file.object_name.split('_',1)[0].split('/')[-1]
  46. dt = datetime.fromtimestamp(int(timestamp), tz)
  47. time_str = dt.strftime('%Y-%m-%d %H:%M:%S')
  48. dag_name = file.object_name.split('_',1)[1]
  49. res.append({'name':time_str+'-'+dag_name, 'uri':file.object_name,'timestamp':timestamp})
  50. res.sort(key=lambda x: x['timestamp'],reverse=True)
  51. return res
  52. @router.get("/dag_content", dependencies=[Depends(verify_all)])
  53. @sxtimeit
  54. @web_try()
  55. def get_dag_content(uri: str):
  56. file = minio_client.get_file(uri)
  57. if len(file) == 0:
  58. raise Exception('No file found')
  59. res = json.loads(file)
  60. return res
  61. # 此接口置于末尾,勿乱动,乱动者砍死
  62. @router.get("/{uri:path}",name="path-convertor")
  63. @sxtimeit
  64. def get_file(uri: str):
  65. file = minio_client.get_file(uri)
  66. code = 200
  67. if len(file) == 0:
  68. code = 404
  69. response = StreamingResponse(io.BytesIO(file), status_code=code, media_type="application/octet-stream")
  70. # 在请求头进行配置
  71. response.headers["Content-Disposition"] = "attachment; filename="+uri
  72. return response