Python 3 Script to Upload File & Images to Microsoft Azure API Storage Full Project For Beginners

 

 

app.py

 

 

# Upload a file to azure blob store using python
#
# Usage: python2.7 azure_upload.py <account_details_file.txt> <container_name> <file_name>
#
# The blob name is the same as the file name
# Running:
#   python2.7 azure_info.txt js test_file.js
# Creates a blob at address:
#   http://<account_name>.blob.core.windows.net/js/test_file.js
#
# Store your azure account name and account key in a seperate file as newline
# delimited values.
# example_details.txt:
#   alexv
#   lkasjdkfj39u4192iojfklajsklfjak10u9u1iupqowurijwkfakskflhrhi3hurhui==
#

from azure.storage import *
import sys

def content_type(file_path):
    split = file_path.split('.')
    if len(split) < 2:
        print 'You did not provide an extention with the file name'
        print 'Exiting...'
        sys.exit(1)

    extention = split[1]

    mime_type = None
    if extention == 'jpg':
        mime_type = 'image/jpeg'
    elif extention == 'pdf':
        mime_type = 'text/pdf'
    elif extention == 'css':
        mime_type = 'text/css'
    elif extention == 'js':
        mime_type = 'text/javascript'
    elif extention == 'docx':
        mime_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'

    return mime_type

def main():
    # Be sure the required command line arguments were supplied
    if len(sys.argv) < 3:
        print
        print 'Proper usage:'
        print 'python2.7 azure_upload.py <account_details_file.txt> <container_name> <file_name>'
        sys.exit(0)

    container_name  = sys.argv[2]
    file_path       = sys.argv[3]

    # Determine the file name from the path
    file_name = file_path.split('/')
    file_name = file_name[len(file_name) - 1]

    account_details = open(sys.argv[1], 'r')
    account_name    = account_details.readline()
    account_name    = account_name.strip()
    account_key     = account_details.readline()
    account_key     = account_key.strip()

    mime_type = content_type(file_name)

    blob_service = BlobService(account_name, account_key)

    # Upload the file and set content type
    blob_service.put_block_blob_from_path(container_name, file_name, file_path)

    # Show a blob listing which now includes the blobs just uploaded
    # Format for blobs is: <account>.blob.core.windows.net/<container>/<file>
    print 'All blobs in container ' + container_name
    blobs = blob_service.list_blobs(container_name)
    for blob in blobs:
        print(blob.name)
        print(blob.url)

main()

Leave a Reply