main.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from typing import Optional
  2. from fastapi import FastAPI, UploadFile, Depends, Request
  3. from fastapi.staticfiles import StaticFiles
  4. from sqlalchemy.orm import Session
  5. import hashlib
  6. import time
  7. import schema
  8. from database import SessionLocal, engine
  9. import model
  10. base_host = '/data/'
  11. model.Base.metadata.create_all(bind=engine)
  12. app = FastAPI()
  13. app.mount("/data", StaticFiles(directory="data"), name="data")
  14. def get_database_session():
  15. try:
  16. db = SessionLocal()
  17. yield db
  18. finally:
  19. db.close()
  20. # @app.get("/")
  21. # def read_root():
  22. # return {"Hello": "World"}
  23. #
  24. #
  25. # @app.get("/items/{item_id}")
  26. # def read_item(item_id: int, q: Optional[str] = None):
  27. # return {"item_id": item_id, "q": q}
  28. @app.post("/uploadfile/")
  29. def create_upload_file(file: Optional[UploadFile] = None, db: Session = Depends(get_database_session)):
  30. if not file:
  31. return {"code": "0", "msg": "no file"}
  32. else:
  33. file_location = f"./data/{file.filename}"
  34. with open(file_location, "wb+") as file_object:
  35. data = file.file.read()
  36. md5 = hashlib.md5(data).hexdigest()
  37. try:
  38. audio = model.CryptoAudio(md5=md5, name=file.filename, tm=time.time())
  39. db.add(audio)
  40. db.commit()
  41. db.refresh(audio)
  42. except Exception as e:
  43. return {"code": "-1", "msg": str(e)}
  44. file_object.write(file.file.read())
  45. return {"code": "0", "msg": "ok", 'data': {'md5': md5}}
  46. @app.get("/get_audio_file/{md5}")
  47. def get_audio_file(md5: str, db: Session = Depends(get_database_session)):
  48. try:
  49. item = db.query(model.CryptoAudio).filter(md5 == md5).first()
  50. except Exception as e:
  51. return {"code": "-1", "msg": str(e)}
  52. if item:
  53. return {"code": "0", "msg": "ok", 'data': {'url': f"{base_host}{item.name}"}}
  54. else:
  55. return {"code": "-1", "msg": "no exist"}