upload.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import os
  2. import base64
  3. import hmac, sha
  4. from google.appengine.ext import webapp
  5. from google.appengine.ext.webapp import template
  6. from google.appengine.ext.webapp.util import run_wsgi_app
  7. """ A simple file to generate a policy and signature to upload to S3 from appengine """
  8. #DEFINE AWS CREDENTIALS
  9. AWS_KEY = 'YOUR_AWS_KEY'
  10. AWS_SECRET_KEY = 'YOUR_AWS_SECRET_KEY'
  11. class MainPage(webapp.RequestHandler):
  12. def get(self):
  13. """ Take the request and create encoded values to allow file upload """
  14. file_name = 'file_name'
  15. return_url = 'http://localhost:8080'
  16. if not return_url:
  17. return self.response.out.write('Error: no return defined')
  18. #POLICY DOCUMENT - MUST BE STRING
  19. policy_document = '''{
  20. "expiration": "2015-06-15T12:00:00.000Z",
  21. "conditions": [
  22. {"bucket": "bucket-name" },
  23. ["starts-with", "$key", ""],
  24. ["starts-with", "$Content-Type", ""],
  25. {"acl": "public-read"},
  26. {"success_action_redirect": "%s"}
  27. ]
  28. }
  29. ''' % return_url
  30. #policy must be a base64 encoded version of the policy document
  31. policy = base64.b64encode(policy_document)
  32. #the signature is the policy + the AWS secret key
  33. signature = base64.b64encode(
  34. hmac.new(AWS_SECRET_KEY, policy, sha).digest())
  35. #template values to be passed through to upload.html
  36. template_values = {
  37. 'policy': policy,
  38. 'signature': signature,
  39. 'filename': file_name,
  40. 'return_url': return_url
  41. }
  42. #define the template
  43. path = os.path.join(os.path.dirname(__file__), 'upload.html')
  44. #write out
  45. self.response.out.write(template.render(path, template_values))
  46. #only one URL route necessary
  47. application = webapp.WSGIApplication(
  48. [('/', MainPage)],
  49. debug=True)
  50. def main():
  51. run_wsgi_app(application)
  52. if __name__ == "__main__":
  53. main()