Created
October 6, 2014 17:55
-
-
Save rianvdm/fc159696ee92bf43ef4a to your computer and use it in GitHub Desktop.
An automated image upload workflow for Amazon S3
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
# For more info, see http://www.elezea.com/2014/07/automatic-upload-amazon-s3/ | |
import boto | |
from boto.s3.connection import S3Connection | |
import os | |
import sys | |
import urllib | |
from datetime import date, datetime | |
import subprocess | |
# This is how Hazel passes in the file path | |
hazelFilePath = sys.argv[1] | |
# Obviously, you'll need your own keys | |
aws_key = 'YOUR_KEY' | |
aws_secret = 'YOUR_SECRET' | |
# This is where I store my log file for these links. It's a Dropbox file in my NVAlt notes folder | |
logFilePath = "/Users/~YOUR_COMPUTER_NAME/Dropbox/Notational/Link_Log.txt" | |
nowTime = str(datetime.now()) | |
# Method to add to clipboard | |
def setClipboardData(data): | |
p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE) | |
p.stdin.write(data) | |
p.stdin.close() | |
retcode = p.wait() | |
# This is the method that does all of the uploading and writing to the log file. | |
# The method is generic enough to work with any S3 bucket that is passed. | |
def uploadToS3(localFilePath, S3Bucket): | |
fileName = os.path.basename(localFilePath) | |
# Determine the current month and year to create the upload path | |
today = date.today() | |
datePath = today.strftime("/%Y/%m/") | |
# Create the URL for the image (Add your own path here) | |
imageLink = 'http://cdn.elezea.com/images/'+urllib.quote(fileName) | |
# Connect to S3 | |
s3 = S3Connection(aws_key, aws_secret) | |
bucket = s3.get_bucket(S3Bucket) | |
key = bucket.new_key('images/'+fileName) | |
key.set_contents_from_filename(localFilePath) | |
key.set_acl('public-read') | |
logfile = open(logFilePath, "a") | |
try: | |
# %% encode the file name and append the URL to the log file | |
logfile.write(nowTime+' '+imageLink+'\n') | |
setClipboardData(imageLink) | |
finally: | |
logfile.close() | |
# Add your bucket name here. | |
uploadToS3(hazelFilePath, 'YOUR_BUCKET_NAME') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment