Skip to content

Instantly share code, notes, and snippets.

@ergusto
Created July 12, 2017 23:36
Show Gist options
  • Save ergusto/e7f9318439565e78de388984aea4c066 to your computer and use it in GitHub Desktop.
Save ergusto/e7f9318439565e78de388984aea4c066 to your computer and use it in GitHub Desktop.
For signing direct to S3 file uploads with Django Rest Framework
import os, boto3
from botocore.client import Config
from django.conf import settings
from rest_framework import parsers
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer
AWS_BUCKET_NAME = settings.AWS_BUCKET_NAME
class SignS3RequestView(APIView):
permission_classes = (IsAuthenticated,)
parser_classes = (
parsers.FormParser,
parsers.MultiPartParser,
parsers.JSONParser,
)
renderer_classes = (JSONRenderer,)
def get(self, request):
file_name = request.query_params.get('file-name')
file_type = request.query_params.get('file-type')
s3 = boto3.client('s3', config=Config(signature_version='s3v4'))
presigned_post = s3.generate_presigned_post(
Bucket = AWS_BUCKET_NAME,
Key = file_name,
Fields = {"acl": "public-read", "Content-Type": file_type},
Conditions = [
{"acl": "public-read"},
{"Content-Type": file_type}
],
ExpiresIn = 3600
)
return Response({
'data': presigned_post,
'url': 'https://s3.amazonaws.com/%s/%s' % (AWS_BUCKET_NAME, file_name)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment