2

I am trying to check if a URL to a jpg is real. This code works, returns Trueif the jpg exists:

import httplib

def exists(site, path):

    conn = httplib.HTTPConnection(site)
    conn.request('HEAD', path)
    response = conn.getresponse()
    conn.close()
    return response.status == 200

print exists('uploads1.wikiart.org',
             '/images/vincent-van-gogh/vincent-s-bedroom-in-arles-1889.jpg')

However, if I send it to a url that doesn't exist, like 'uploads1111.wikiart.org',I get a socket error that says:

socket.error: [Errno 10060] A connection attempt failed 
because the connected party did not properly respond after a period of time

I searched for an answer and found something to do with the errno module but wasn't able to apply that code to my own successfully. I'm trying to catch any socket errors and return False if there is one.

ian-campbell
  • 1,605
  • 1
  • 20
  • 42

1 Answers1

3

Answer to my own question:

import httplib
import socket


def exists(site, path):

    try:
        conn = httplib.HTTPConnection(site)
        conn.request('HEAD', path)
        response = conn.getresponse()
        conn.close()
        return response.status == 200

    except socket.error:
        return False
ian-campbell
  • 1,605
  • 1
  • 20
  • 42