Created
June 18, 2015 18:49
-
-
Save arthuralvim/d7792876258800cd2ea1 to your computer and use it in GitHub Desktop.
Conseguindo assinatura do S3 para enviar arquivos via PUT direto do cliente.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django.conf import settings | |
from django.http import JsonResponse | |
from hashlib import sha1 | |
import base64 | |
import hmac | |
import time | |
import urllib | |
__all__ = ['sign_s3', ] | |
def sign_s3(request): | |
""" | |
https://devcenter.heroku.com/articles/s3-upload-python | |
""" | |
AWS_ACCESS_KEY = settings.AWS_ACCESS_KEY_ID | |
AWS_SECRET_KEY = settings.AWS_SECRET_ACCESS_KEY | |
S3_BUCKET = settings.AWS_STORAGE_BUCKET_NAME | |
S3_URL = settings.S3_URL | |
mime_type = request.GET.get('file_type', None) | |
file_name = request.GET.get('file_name', None) | |
object_name = urllib.quote_plus(file_name) | |
expires = int(time.time()+60*60*24) | |
amz_headers = "x-amz-acl:public-read" | |
string_to_sign = 'PUT\n\n{0}\n{1}\n{2}\n/{3}/{4}'.format( | |
mime_type, expires, amz_headers, S3_BUCKET, object_name) | |
signature = base64.encodestring( | |
hmac.new( | |
AWS_SECRET_KEY.encode(), string_to_sign.encode('utf8'), sha1 | |
).digest() | |
) | |
signature = urllib.quote_plus(signature.strip()) | |
url = '{0}tmp-upload/{1}'.format(S3_URL, object_name) | |
return JsonResponse({ | |
'signed_request': | |
'{0}?AWSAccessKeyId={1}&Expires={2}&Signature={3}'.format( | |
url, AWS_ACCESS_KEY, expires, signature), | |
'url': url, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment