简体   繁体   中英

How do I check if a file on http exists, using Python/django?

How do I check if a file on http exists, using Python/Django?

I try to check if file in http://hostname/directory/file.jpg exist

Try urllib2.urlopen :

import urllib2
ret = urllib2.urlopen('http://hostname/directory/file.jpg')
if ret.code == 200:
    print "Exists!"

Note that you don't check if file exists - you check if resource exists

EDIT: The other answer by user Geo is better in that HEAD request can be much more efficient as it doesn't fetch resource content.

You could do it with a HEAD request. Check this question for more info. If you get a status code of 200, it should be ok, but you could check for content type as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM