init
This commit is contained in:
commit
f660d3b97b
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
venv
|
||||
.idea
|
||||
.vscode
|
6
Dockerfile
Normal file
6
Dockerfile
Normal file
|
@ -0,0 +1,6 @@
|
|||
FROM python:slim
|
||||
WORKDIR /app
|
||||
ADD . /app
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
EXPOSE 80
|
||||
CMD ["python", "main.py"]
|
7
README.md
Normal file
7
README.md
Normal file
|
@ -0,0 +1,7 @@
|
|||
#### ENV setup
|
||||
|
||||
- STORJ_ACCESS_KEY
|
||||
- STORJ_SECRET_KEY
|
||||
- STORJ_END_POINT
|
||||
- STORJ_BUCKET_NAME
|
||||
- CDN_DOMAIN
|
56
main.py
Normal file
56
main.py
Normal file
|
@ -0,0 +1,56 @@
|
|||
import os
|
||||
import tempfile
|
||||
import uuid
|
||||
import boto3
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from aiohttp import web
|
||||
|
||||
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')
|
||||
|
||||
|
||||
async def upload_handler(request):
|
||||
reader = await request.multipart()
|
||||
file = await reader.next()
|
||||
if file is None:
|
||||
return web.json_response({'error': 'No file uploaded'}, status=400)
|
||||
file_name, file_extension = os.path.splitext(file.filename)
|
||||
key = str(uuid.uuid4()) + file_extension
|
||||
s3 = boto3.client('s3',
|
||||
aws_access_key_id=STORJ_ACCESS_KEY,
|
||||
aws_secret_access_key=STORJ_SECRET_KEY,
|
||||
endpoint_url=STORJ_END_POINT)
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile() as tmp_file:
|
||||
while True:
|
||||
chunk = await file.read_chunk() # 8192 bytes by default.
|
||||
if not chunk:
|
||||
break
|
||||
tmp_file.write(chunk)
|
||||
|
||||
s3.upload_file(
|
||||
Filename=tmp_file.name,
|
||||
Bucket=STORJ_BUCKET_NAME,
|
||||
Key=key,
|
||||
ExtraArgs={
|
||||
"ContentType": file.content_type
|
||||
}
|
||||
)
|
||||
|
||||
url = 'http://' + CDN_DOMAIN + '/' + key
|
||||
|
||||
return web.json_response({'url': url, 'originalFilename': file.filename})
|
||||
|
||||
except (BotoCoreError, ClientError) as e:
|
||||
print(e)
|
||||
return web.json_response({'error': 'Failed to upload file'}, status=500)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = web.Application()
|
||||
app.router.add_post('/upload', upload_handler)
|
||||
|
||||
web.run_app(app)
|
3
requirements.txt
Normal file
3
requirements.txt
Normal file
|
@ -0,0 +1,3 @@
|
|||
aiohttp~=3.8.5
|
||||
boto3~=1.28.56
|
||||
botocore~=1.31.56
|
Loading…
Reference in New Issue
Block a user