blob-upload-1.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import os
  2. from flask import Flask, request, redirect, url_for
  3. from werkzeug import secure_filename
  4. from azure.storage.blob import BlockBlobService
  5. import string, random, requests
  6. app = Flask(__name__, instance_relative_config=True)
  7. app.config.from_pyfile('config.py')
  8. account = app.config['ACCOUNT'] # Azure account name
  9. key = app.config['STORAGE_KEY'] # Azure Storage account access key
  10. container = app.config['CONTAINER'] # Container name
  11. blob_service = BlockBlobService(account_name=account, account_key=key)
  12. @app.route('/', methods=['GET', 'POST'])
  13. def upload_file():
  14. if request.method == 'POST':
  15. file = request.files['file']
  16. filename = secure_filename(file.filename)
  17. fileextension = filename.rsplit('.',1)[1]
  18. Randomfilename = id_generator()
  19. filename = Randomfilename + '.' + fileextension
  20. try:
  21. blob_service.create_blob_from_stream(container, filename, file)
  22. except Exception:
  23. print ('Exception=' + Exception)
  24. pass
  25. ref = 'http://'+ account + '.blob.core.windows.net/' + container + '/' + filename
  26. return '''
  27. <!doctype html>
  28. <title>File Link</title>
  29. <h1>Uploaded File Link</h1>
  30. <p>''' + ref + '''</p>
  31. <img src="'''+ ref +'''">
  32. '''
  33. return '''
  34. <!doctype html>
  35. <title>Upload new File</title>
  36. <h1>Upload new File</h1>
  37. <form action="" method=post enctype=multipart/form-data>
  38. <p><input type=file name=file>
  39. <input type=submit value=Upload>
  40. </form>
  41. '''
  42. def id_generator(size=32, chars=string.ascii_uppercase + string.digits):
  43. return ''.join(random.choice(chars) for _ in range(size))
  44. if __name__ == '__main__':
  45. app.run(debug=True)