Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a URL to an image is up and exists in Python

Tags:

python

http

url

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.

like image 329
petabyte Avatar asked May 11 '12 00:05

petabyte


2 Answers

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
like image 165
Kraviz Avatar answered Sep 18 '22 13:09

Kraviz


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)
like image 33
MattoTodd Avatar answered Sep 20 '22 13:09

MattoTodd