This commit is contained in:
parent
acb6f291d3
commit
fc7bca08f8
31
main.py
31
main.py
|
@ -3,6 +3,7 @@ import os
|
|||
import tempfile
|
||||
import uuid
|
||||
import aiobotocore.session
|
||||
import asyncio
|
||||
from starlette.applications import Starlette
|
||||
from starlette.responses import JSONResponse
|
||||
from starlette.routing import Route
|
||||
|
@ -35,43 +36,39 @@ async def create_s3_client():
|
|||
|
||||
@login_required
|
||||
async def upload_handler(request: Request):
|
||||
logging.debug("Received upload request")
|
||||
logger.debug("Received upload request")
|
||||
form = await request.form()
|
||||
file = form.get("file")
|
||||
|
||||
if file is None:
|
||||
logging.error("No file uploaded")
|
||||
logger.error("No file uploaded")
|
||||
return JSONResponse({"error": "No file uploaded"}, status_code=400)
|
||||
|
||||
file_name, file_extension = os.path.splitext(file.filename)
|
||||
key = str(uuid.uuid4()) + file_extension
|
||||
logging.debug(f"Generated file key: {key}")
|
||||
logger.debug(f"Generated file key: {key}")
|
||||
|
||||
s3 = await create_s3_client()
|
||||
with tempfile.NamedTemporaryFile() as tmp_file:
|
||||
while True:
|
||||
chunk = await file.read(8192)
|
||||
if not chunk:
|
||||
break
|
||||
tmp_file.write(chunk)
|
||||
tmp_file.flush()
|
||||
|
||||
logging.debug("Starting file upload to S3")
|
||||
await s3.upload_file(
|
||||
Filename=tmp_file.name,
|
||||
logger.debug("Starting file upload to S3")
|
||||
async with file.open("rb") as f:
|
||||
content = await f.read()
|
||||
await s3.put_object(
|
||||
Bucket=STORJ_BUCKET_NAME,
|
||||
Key=key,
|
||||
ExtraArgs={"ContentType": file.content_type},
|
||||
Body=content,
|
||||
ContentType=file.content_type,
|
||||
)
|
||||
logging.debug("File upload completed")
|
||||
logger.debug("File upload completed")
|
||||
|
||||
url = f"http://{CDN_DOMAIN}/{key}"
|
||||
logging.info(f"File uploaded successfully: {url}")
|
||||
logger.info(f"File uploaded successfully: {url}")
|
||||
return JSONResponse({"url": url, "originalFilename": file.filename})
|
||||
|
||||
|
||||
|
||||
async def home(request: Request):
|
||||
logging.debug("Home route called")
|
||||
logger.debug("Home route called")
|
||||
return JSONResponse({"message": "Hello World!"})
|
||||
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user