Hi, I have a form that enables a user to upload an image from twitter based upon the handle. I trying to automate the download/upload to improve the UX. I then want to use the image for other pages.
I think i have two options, 1 would be to dynamically retrieve the image using http
as the path and the other is would be to download and store the path to the media folder location in the model.
I think from a performance perspective it would be better to reference the image stored in the media folder rather than loading via http each time.
So I am trying to build this into my view.
username = 'someUser'
consumer_key = "######..."
consumer_secret = "######..."
access_token = "######..."
access_token_secret = "######..."
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
user = api.get_user(user_id = username ,screen_name = username)
url = user.profile_image_url
url = url.replace('_normal.jpg','.jpg')
remote_url = url
local_file = 'profile.jpg'
request.urlretrieve(remote_url, local_file)
os.remove(local_file)
This allows me to download the file and store it on a local disk which won’t work once in production.
My Model
profile_image = ResizedImageField(size=[400, 400],crop=['middle', 'center'],quality=100,upload_to='images/profiles/', blank=True)
I could maybe save it to images/profiles/<something>.jpg
and then within my view, I reference this file and delete it after?
if form.is_valid():
username = request.POST['twitter_handle'] # for POST form method
user = api.get_user(user_id = username ,screen_name = username)
url = user.profile_image_url
url = url.replace('_normal.jpg','.jpg')
remote_url = url
local_file = 'images/profile'
urllib.request.urlretrieve(remote_url, local_file)
print(local_file)
form = form.save(commit=False)
form.profile = profile
form.image = local_file
form.save()
Ideally, I need the file to be uploaded to my media_root path, but I feel like I am approaching this the wrong way.
Thanks