Created
June 13, 2019 08:21
-
-
Save michimani/32d7f309a3a349c5da226d2adbeb8621 to your computer and use it in GitHub Desktop.
Save image file from image url to S3 backet.
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
import boto3 | |
from urllib import request | |
from urllib.request import Request, urlopen | |
def save_image(img_url): | |
""" | |
Save images from image url to S3 backet. | |
@param string img_url | |
""" | |
try: | |
backet = 'backet-name' | |
save_key_base = 'images' | |
save_key = '{}/{}'.format( | |
save_key_base, | |
re.sub(r'^https?:.+\/(.+\.(jpg|png))$', r'\1', img_url) | |
) | |
image = urlopen(img_url).read() | |
s3 = boto3.resource('s3') | |
s3obj = s3.Object(backet, save_key) | |
s3obj.put(Body=image) | |
except Exception: | |
print('Failed to save image. {}'.format(img_url)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment