【问题标题】:Django: check if an image exists at some particular urlDjango:检查图像是否存在于某个特定的 url
【发布时间】:2012-06-30 22:49:39
【问题描述】:

只是想知道有什么方法可以在 Django 中检查 url 是否链接到有效图像。

【问题讨论】:

  • 如果图像和 Django 在同一台机器上,那么你可以简单地读取文件并验证它。如果没有,那么您必须进行 REST 调用并解析结果。
  • 图像与 Django 在同一台机器上不存在。实际上我有一个表单,用户需要提交一些图像的 url。我只想检查该 url 是否链接到任何实际图像或不是。
  • 阅读:stackoverflow.com/questions/7699796/…(可能重复)。

标签: python django image file


【解决方案1】:

使用urllib2 进行检查的简单方法。

>>> import urllib2
>>> url = 'https://www.google.com.pk/images/srpr/logo3w.png'
>>> try:
...   f = urllib2.urlopen(urllib2.Request(url))
...   imageFound = True
... except:
...   imageFound = False
...
>>> imageFound
True

【讨论】:

    【解决方案2】:

    这是一种故障保护方法。 首先,解析 url 以获取域和其余部分。

    >>> from urllib.parse import urlparse
    >>> url = 'http://example.com/random/folder/path.html'
    >>> parse_object = urlparse(url)
    >>> parse_object.netloc
    'example.com'
    >>> parse_object.path
    '/random/folder/path.html'
    >>> parse_object.scheme
    'http'
    

    现在,使用以上信息获取内容类型。使用parse_object.netloc 代替 sstatic.net,使用parse_object.path 代替硬编码路径。

    >>> import httplib
    >>> conn = httplib.HTTPConnection("sstatic.net")
    >>> conn.request("HEAD", "/stackoverflow/img/favicon.ico")
    >>> res = conn.getresponse()
    >>> print res.getheaders()
    [('content-length', '1150'), ('x-powered-by', 'ASP.NET'), ('accept-ranges', 'bytes'),         ('last-modified', 'Mon, 02 Aug 2010 06:04:04 GMT'), ('etag', '"2187d82832cb1:0"'), ('cache-control', 'max-age=604800'), ('date', 'Sun, 12 Sep 2010 13:39:26 GMT'), ('content-type', 'image/x-icon')]
    

    这告诉您这是一个 1150 字节的图像(图像/* mime-type)。足以让您决定是否要获取完整资源的信息。

    编辑

    对于缩短的网址,例如指向http://ubuntu.icafebusiness.com/images/ubuntugui2.jpghttp://goo.gl/IwruD,在您收到的响应中,还有一个名为'location' 的附加参数。

    这就是我要说的:

    >>> import httplib
    >>> conn = httplib.HTTPConnection("goo.gl")
    >>> conn.request("HEAD", "/IwruD")
    >>> res = conn.getresponse()
    >>> print res.getheaders()
    [('x-xss-protection', '1; mode=block'),
     ('x-content-type-options', 'nosniff'),
     ('transfer-encoding', 'chunked'),
     ('age', '64'),
     ('expires', 'Mon, 01 Jan 1990 00:00:00 GMT'),
     ('server', 'GSE'),
     ('location', 'http://ubuntu.icafebusiness.com/images/ubuntugui2.jpg'),
     ('pragma', 'no-cache'),
     ('cache-control', 'no-cache, no-store, max-age=0, must-revalidate'),
     ('date', 'Sat, 30 Jun 2012 08:52:15 GMT'),
     ('x-frame-options', 'SAMEORIGIN'),
     ('content-type', 'text/html; charset=UTF-8')]
    

    在直接网址中,您不会找到它。

    >>> import httplib
    >>> conn = httplib.HTTPConnection("ubuntu.icafebusiness.com")
    >>> conn.request("HEAD", "/images/ubuntugui2.jpg")
    >>> res = conn.getresponse()
    >>> print res.getheaders()
    [('content-length', '78603'), ('accept-ranges', 'bytes'), ('server', 'Apache'), ('last-modified', 'Sat, 16 Aug 2008 01:36:17 GMT'), ('etag', '"1fb8277-1330b-45489c3ad2640"'), ('date', 'Sat, 30 Jun 2012 08:55:46 GMT'), ('content-type', 'image/jpeg')]
    

    您可以使用简单的代码来查找:

    >>> r = res.getheaders()
    >>> redirected = False
    >>> for e in r:
    >>>     if(e[0] == 'location'):
    >>>         redirected = e
    >>>
    >>> if(redirected != False):
    >>>     print redirected[1]
    'http://ubuntu.icafebusiness.com/images/ubuntugui2.jpg'
    

    【讨论】:

    • 我的 python 解释器说“ImportError: No module named parse”。您的方法在第 1 步失败。有什么想法吗?
    • 找到了,你用的是python 3,我还在用python 2.7 :)
    • 还有一个疑问,假设 'ubuntu.icafebusiness.com/images/ubuntugui2.jpg' 是 url,我使用 google url shortner 缩短了它,所以它现在在这个缩短的 url 上变成 'goo.gl/IwruD'.Now 你的方法不起作用,它说“ ResponseNotReady”。怎么说?
    【解决方案3】:

    使用requestsPIL 来验证它实际上是一个有效的图像:

    >>> import requests
    >>> from PIL import Image
    >>> from StringIO import StringIO
    >>> r = requests.get('http://cdn.sstatic.net/stackoverflow/img/sprites.png')
    >>> im = Image.open(StringIO(r.content))
    >>> im
    <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=238x1073 at 0x2845EA8>
    

    【讨论】:

    • 如果图像不存在会怎样?您的代码会崩溃还是必须检查 im 的某些属性?您可以将代码更新为返回布尔值的函数吗?
    • 是的,除了 HTTP 状态码,Image.open 应该抛出某种错误,我在想吗? PIL 在这方面不是很有帮助...我也在查看 effbot.org/imagingbook/image.htm#tag-Image.Image.verify 但不知道该使用什么。
    猜你喜欢
    • 1970-01-01
    • 2015-04-06
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 2010-11-24
    • 1970-01-01
    相关资源
    最近更新 更多