【问题标题】:HTTP request overload/timeout using python使用python的HTTP请求过载/超时
【发布时间】:2014-03-07 16:50:43
【问题描述】:

我有一个 python 脚本正在运行,它基本上通过 http 请求 1000 个 url 并记录它们的响应。这是下载url页面的函数。

def downld_url(url, output):
     print "Entered Downld_url and scraping the pdf/doc/docx file now..."
     global error
     try:
        # determine all extensions we should account for
        f = urllib2.urlopen(url)
        data = f.read()
        dlfn = urlsplit(url).path.split('.')[-1]
        print "The extension of the file is: " + str(dlfn)
        dwnladfn = ImageDestinationPath + "/" + output + "." + dlfn
        with open(dwnladfn, "wb") as code:
            code.write(data)
            code.close()
        _Save_image_to_s3(output+"."+dlfn, ImageDestinationPath + "/" +output + 
                          "." + dlfn)
        print dlfn + " file saved to S3"
        os.remove(ImageDestinationPath + "/" +output + "." + dlfn)
        print dlfn + "file removed from local folder"
        update_database(output,output+"."+dlfn, None)
        return
     except Exception as e:
        error = "download error: " + str(e)
        print "Error in downloading file: " + error
        return

现在,管道中的 100-200 个 url 可以顺利运行,但之后响应开始变得非常缓慢,最终响应超时。我是,猜测这是因为请求过载。有没有一些有效的方法可以在不重载请求的情况下做到这一点?

【问题讨论】:

  • 注意:这些网址大多是下载的 .png 和 .pdf 文件。
  • 不相关:使用urlparse解析url和os.pathposixpath操作路径
  • 哪些请求变慢了:是urlopen(),还是_Save_image_to_s3,还是update_database(),还是别的什么?

标签: python http python-2.7 python-3.x https


【解决方案1】:

我不知道问题出在哪里,但如果它与同一进程中的请求过多有关,您可以尝试multiprocessing作为解决方法。

它还可以加快整个过程,因为您可以同时执行多个任务(例如,一个进程正在下载而另一个正在写入磁盘,......)。我这样做是为了类似的事情,确实更好(也提高了总下载速度)

【讨论】:

    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 2011-11-05
    • 2010-12-12
    • 2014-04-25
    • 1970-01-01
    相关资源
    最近更新 更多