How do I check if a file on http exists, using Python/Django?
如何使用Python / Django检查http上的文件是否存在?
I try to check if file in http://hostname/directory/file.jpg exist
我尝试检查http://hostname/directory/file.jpg中的文件是否存在
2 个解决方案
#1
12
Try urllib2.urlopen:
试试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.
编辑:用户Geo的另一个答案是更好的,因为HEAD请求可以更高效,因为它不会获取资源内容。
#2
6
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.
您可以使用HEAD请求执行此操作。查看此问题以获取更多信息。如果您获得的状态代码为200,则应该没问题,但您也可以检查内容类型。
#1
12
Try urllib2.urlopen:
试试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.
编辑:用户Geo的另一个答案是更好的,因为HEAD请求可以更高效,因为它不会获取资源内容。
#2
6
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.
您可以使用HEAD请求执行此操作。查看此问题以获取更多信息。如果您获得的状态代码为200,则应该没问题,但您也可以检查内容类型。