我想实现一个类似于这个http://www.tineye.com/parse?url=yahoo.com的功能-允许用户从任何网页上传图片。
对我来说,主要的问题是,对于拥有大量图像的网页来说,这需要花费太多的时间。
根据下一个方案,我在Django (使用curl或urllib)中这样做:
file.read()
def get_image_size(uri):
file = urllib.urlopen(uri)
p = ImageFile.Parser()
data = file.read(1024)
if not data:
return None
p.feed(data)
if p.image:
return p.image.size
file.close()
#not an image
return None正如你所看到的,我不是为了得到它的大小而加载完整的图像,只有1kb的大小。但是,当有很多图像时,仍然要花费太多的时间(对于找到的每个图像,我都会调用这个函数一次)。
那我怎么才能让它工作得更快呢?
有没有办法不对每一张图片提出要求?
任何帮助都将不胜感激。
谢谢!
发布于 2011-04-09 20:23:12
我能想到很少的优化:
头请求的例子:
$ telnet m.onet.pl 80
Trying 213.180.150.45...
Connected to m.onet.pl.
Escape character is '^]'.
HEAD /_m/33fb7563935e11c0cba62f504d91675f,59,29,134-68-525-303-0.jpg HTTP/1.1
host: m.onet.pl
HTTP/1.0 200 OK
Server: nginx/0.8.53
Date: Sat, 09 Apr 2011 18:32:44 GMT
Content-Type: image/jpeg
Content-Length: 37545
Last-Modified: Sat, 09 Apr 2011 18:29:22 GMT
Expires: Sat, 16 Apr 2011 18:32:44 GMT
Cache-Control: max-age=604800
Accept-Ranges: bytes
Age: 6575
X-Cache: HIT from emka1.m10r2.onet
Via: 1.1 emka1.m10r2.onet:80 (squid)
Connection: close
Connection closed by foreign host.发布于 2011-04-09 20:21:33
您可以使用文件的headers属性,比如urllib2.urlopen返回的对象(我不知道urllib)。
这是我为它写的一个测试。正如你所看到的,它是相当快的,虽然我认为一些网站会阻止太多的重复请求。
|milo|laurie|¥ cat test.py
import urllib2
uri = "http://download.thinkbroadband.com/1GB.zip"
def get_file_size(uri):
file = urllib2.urlopen(uri)
content_header, = [header for header in file.headers.headers if header.startswith("Content-Length")]
_, str_length = content_header.split(':')
length = int(str_length.strip())
return length
if __name__ == "__main__":
get_file_size(uri)
|milo|laurie|¥ time python2 test.py
python2 test.py 0.06s user 0.01s system 35% cpu 0.196 totalhttps://stackoverflow.com/questions/5607101
复制相似问题