I am trying to retrieve 10 images through an API which returns JSON data by first making a request to the API and then storing 10 image URLs from the returned JSON data in a list. In my original iteration I made individual requests to those urls and saved the response content to file. My code is given below with my API key removed for obvious reasons:
def get_image(search_term):
number_images = 10
images = requests.get("https://pixabay.com/api/?key=insertkey&q={}&per_page={}".format(search_term,number_images))
images_json_dict = images.json()
hits = images_json_dict["hits"]
urls = []
for i in range(len(hits)):
urls.append(hits[i]["webformatURL"])
count =0
for url in urls:
picture_request = requests.get(url)
if picture_request.status_code == 200:
try:
with open(dir_path+r'\\images\\{}.jpg'.format(count),'wb') as f:
f.write(picture_request.content)
except:
os.mkdir(dir_path+r'\\images\\')
with open(dir_path+r'\\images\\{}.jpg'.format(count),'wb') as f:
f.write(picture_request.content)
count+=1
This was working fine apart from the fact that it was very slow. It took maybe 7 seconds to pull in those 10 images and save in a folder. I read here that it's possible to use Sessions() in the requests library to improve performance - I'd like to have those images as quickly as possible. I've modified the code as shown below however the problem I'm having is that the get request on the sessions object returns a requests.sessions.Session object rather than a response code and there is also no .content method to retrieve the content (I've added comments to the relevant lines of code below). I'm relatively new to programming so I'm uncertain if this is even the best way to do this. My question is how can I use sessions to retrieve back the image content now that I am using Session() or is there some smarter way to do this?
def get_image(search_term):
number_images = 10
images = requests.get("https://pixabay.com/api/?key=insertkey&q={}&per_page={}".format(search_term,number_images))
images_json_dict = images.json()
hits = images_json_dict["hits"]
urls = []
for i in range(len(hits)):
urls.append(hits[i]["webformatURL"])
count =0
#Now using Session()
picture_request = requests.Session()
for url in urls:
picture_request.get(url)
#This will no longer work as picture_request is an object
if picture_request == 200:
try:
with open(dir_path+r'\\images\\{}.jpg'.format(count),'wb') as f:
#This will no longer work as there is no .content method
f.write(picture_request.content)
except:
os.mkdir(dir_path+r'\\images\\')
with open(dir_path+r'\\images\\{}.jpg'.format(count),'wb') as f:
#This will no longer work as there is no .content method
f.write(picture_request.content)
count+=1