-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
78 lines (60 loc) · 2.36 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import time
from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks
import os
import logging
import tempfile
from fastapi.responses import JSONResponse
from dotenv import load_dotenv
from uploader import BlobUploader
import traceback
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.StreamHandler(),
logging.FileHandler("app.log")
]
)
logger = logging.getLogger(__name__)
app = FastAPI(timeout=3000) # 50minutes
connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING")
container_name = os.getenv("AZURE_STORAGE_CONTAINER_NAME")
blob_uploader = BlobUploader(connection_string, container_name)
@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
logger.error(f"An error occurred: {exc}")
return JSONResponse(
status_code=500,
content={"message": "An internal server error occurred."}
)
@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
try:
start_time=time.time()
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file_path = temp_file.name
chunk_size = 1024 * 1024
while True:
chunk = await file.read(chunk_size)
if not chunk:
break
temp_file.write(chunk)
try:
blob_uploader.upload_stream(temp_file_path, file.filename)
except Exception as e:
logger.error(f"Error uploading file: {str(e)}")
logger.error(traceback.format_exc())
raise HTTPException(status_code=500, detail="Failed to upload file.")
#os.remove(temp_file_path)
end_time=time.time()
duration=end_time-start_time
logger.info(f"Process completed in {duration} seconds ++++ {float(duration /60)}")
return {"message": "Upload completed successfully."}
except Exception as e:
logger.error(f"Failed to upload file due to: {str(e)}")
logger.error(traceback.format_exc())
raise HTTPException(status_code=500, detail="Failed to upload file.")
@app.get("/upload/progress")
async def get_upload_progress():
return {"progress": f"{blob_uploader.get_progress():.2f}%"}