I am making a website. I want to check from the server whether the link that the user submitted is actually an image that exists.
This is the best approach working for my application, based also on previous comments:
def is_url_image(image_url):
image_formats = ("image/png", "image/jpeg", "image/jpg")
r = requests.head(image_url)
if r.headers["content-type"] in image_formats:
return True
return False
This is one way that is quick:
It doesn't really verify that is really an image file, it just guesses based on file extention and then checks that the url exists. If you really need to verify that the data returned from the url is actually an image (for security reasons) then this solution would not work.
import mimetypes, urllib2
def is_url_image(url):
mimetype,encoding = mimetypes.guess_type(url)
return (mimetype and mimetype.startswith('image'))
def check_url(url):
"""Returns True if the url returns a response code between 200-300,
otherwise return False.
"""
try:
headers = {
"Range": "bytes=0-10",
"User-Agent": "MyTestAgent",
"Accept": "*/*"
}
req = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(req)
return response.code in range(200, 209)
except Exception:
return False
def is_image_and_ready(url):
return is_url_image(url) and check_url(url)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With