Skip to content

Instantly share code, notes, and snippets.

@ratpik
Last active December 18, 2015 10:29

Revisions

  1. ratpik revised this gist Jun 12, 2013. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions s3upload.py
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,3 @@

    #s3_object_key is the file path relative to the your S3 URL where you want to store the file

    Eg.
    @@ -8,8 +7,9 @@
    #file is the file that you have create locally either in ephermal storage (Like the Heroku Dyno) or permanent storage like your local file system

    #Write to local storage
    Eg.

    avatar = urlopen(url).read()
    avatar = urlopen(url).read() #Pick a random file on the internet

    fout = open(os.path.join(filepath, filename), "wb")
    fout.write(avatar)
  2. ratpik created this gist Jun 12, 2013.
    41 changes: 41 additions & 0 deletions s3upload.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@

    #s3_object_key is the file path relative to the your S3 URL where you want to store the file

    Eg.
    s3_object_key = '%s/%s' %(settings.USER_PROFILE_PICTURE_DIR, filename)


    #file is the file that you have create locally either in ephermal storage (Like the Heroku Dyno) or permanent storage like your local file system

    #Write to local storage

    avatar = urlopen(url).read()

    fout = open(os.path.join(filepath, filename), "wb")
    fout.write(avatar)
    fout.close()


    def push_picture_to_s3(s3_upload_key, file):
    try:
    import boto
    from boto.s3.key import Key

    bucket_name = settings.AWS_STORAGE_BUCKET_NAME

    # connect to the bucket
    conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID,
    settings.AWS_SECRET_ACCESS_KEY)
    bucket = conn.get_bucket(bucket_name)

    # create a key to keep track of our file in the storage
    k = Key(bucket)
    k.key = s3_upload_key
    k.set_contents_from_filename(file)
    # we need to make it public so it can be accessed publicly
    # using a URL like http://s3.amazonaws.com/bucket_name/key
    k.make_public()
    # remove the file from the web server
    os.remove(file)
    except Exception:
    raise