core/resolvers/upload.py

57 lines
1.7 KiB
Python
Raw Normal View History

2023-07-13 13:01:58 +00:00
import os
import shutil
import tempfile
import uuid
2023-10-26 21:07:35 +00:00
import boto3
from botocore.exceptions import BotoCoreError, ClientError
from starlette.responses import JSONResponse
2023-10-26 17:56:42 +00:00
2023-10-26 21:07:35 +00:00
STORJ_ACCESS_KEY = os.environ.get('STORJ_ACCESS_KEY')
STORJ_SECRET_KEY = os.environ.get('STORJ_SECRET_KEY')
STORJ_END_POINT = os.environ.get('STORJ_END_POINT')
STORJ_BUCKET_NAME = os.environ.get('STORJ_BUCKET_NAME')
CDN_DOMAIN = os.environ.get('CDN_DOMAIN')
2023-07-13 13:01:58 +00:00
async def upload_handler(request):
form = await request.form()
2023-10-26 21:07:35 +00:00
file = form.get('file')
2023-07-13 13:01:58 +00:00
if file is None:
2023-10-26 21:07:35 +00:00
return JSONResponse({'error': 'No file uploaded'}, status_code=400)
2023-07-13 13:01:58 +00:00
file_name, file_extension = os.path.splitext(file.filename)
2023-10-26 21:07:35 +00:00
key = 'files/' + str(uuid.uuid4()) + file_extension
2023-07-13 13:01:58 +00:00
# Create an S3 client with Storj configuration
2023-10-26 21:07:35 +00:00
s3 = boto3.client('s3',
aws_access_key_id=STORJ_ACCESS_KEY,
aws_secret_access_key=STORJ_SECRET_KEY,
endpoint_url=STORJ_END_POINT)
2023-07-13 13:01:58 +00:00
try:
# Save the uploaded file to a temporary file
with tempfile.NamedTemporaryFile() as tmp_file:
shutil.copyfileobj(file.file, tmp_file)
s3.upload_file(
Filename=tmp_file.name,
Bucket=STORJ_BUCKET_NAME,
Key=key,
2023-10-26 21:07:35 +00:00
ExtraArgs={
"ContentType": file.content_type
}
2023-07-13 13:01:58 +00:00
)
2023-10-26 21:07:35 +00:00
url = 'https://' + CDN_DOMAIN + '/' + key
2023-07-13 13:01:58 +00:00
2023-10-26 21:07:35 +00:00
return JSONResponse({'url': url, 'originalFilename': file.filename})
2023-07-13 13:01:58 +00:00
except (BotoCoreError, ClientError) as e:
print(e)
2023-10-26 21:07:35 +00:00
return JSONResponse({'error': 'Failed to upload file'}, status_code=500)