I've written a really simple function with requests, which with a giver URL checks if it gets a response and if this response is an image. It actually works, but is crazy slow at times. I'm too inexperienced to understand why is that. How can I improve it or achieve the same thing in a better and faster way?
def is_image_url(url):
try:
response = requests.get(url)
status = response.status_code
print(status)
if response.status_code == 200:
content_type = response.headers.get('content-type')
print(content_type)
if content_type.startswith('image'):
return True
return False
except Exception as e:
print(e)
return False
I'm using that function to exclude images who are not accessible, like images from Instagram, Facebook etc. I thought it could work fine because I actually need to check only 10 images that I get from Google custom search API.
for now I've excluded the function from the application, and tried do a similar thing with checking the image height or width to assure that it existed and was accessible without much success.
loop i use to call the function
for image in img['items']:
height = image['image']['height']
width = image['image']['width']
imgTitle = image['title']
imgHtmlTitle = image['htmlTitle']
imgContext = image['image']['contextLink']
imgLink = image['link']
workingImg = is_image_url(imgLink)
print(f'alt {height}.... larg {width}')
image_info = {'imgTitle' : imgTitle, 'imgHtmlTitle' : imgHtmlTitle, "imgContext" : imgContext, "imgLink" : imgLink}
if workingImg:
image_results.append(image_info)