Python& URLLIB2 - 请求网页但不等待响应

时间:2013-12-14 07:41:47

标签: python urllib2

在python中,我如何进行http请求而不是等待响应。我不关心获取任何数据,我只需要服务器来注册页面请求。

现在我使用这段代码:

urllib2.urlopen("COOL WEBSITE")

但显然这会暂停脚本直到返回一个响应,我只是想发出一个请求并继续前进。

我该怎么做?

4 个答案:

答案 0 :(得分:12)

您想要的是线程异步

<强>线程

  • urllib2.urlopen()
  • 中结束对threading.Thread()的通话

示例:

from threading import Thread

def open_website(url):
    return urllib2.urlopen(url)

Thread(target=open_website, args=["http://google.com"]).start()

<强>异步:

  • 不幸的是,在Python标准库中没有标准的方法。

使用具有此支持的requests库。

示例:

from requests import async

async.get("http://google.com")

还有使用restclient库的第3个选项 内置(有一段时间异步支持:

from restclient import GET

res = GET("http://google.com", async=True, resp=True)

答案 1 :(得分:3)

使用线程:

import threading

threading.Thread(target=urllib.urlopen, args=('COOL WEBSITE',)).start()

不要忘记args参数应该是元组。这就是尾随,

的原因

答案 2 :(得分:1)

gevent可能是一个合适的选择。

第一个补丁插座:

import gevent
import gevent.monkey
monkey.patch_socket()
monkey.patch_ssl()

然后使用gevent.spawn()来封装您生成greenlet的请求。它不会阻塞主线程并且速度非常快!

这是一个简单的tutorial

答案 3 :(得分:0)

您可以使用请求库执行此操作,如下所示

import requests
try:
    requests.get("http://127.0.0.1:8000/test/",timeout=10)
except requests.exceptions.ReadTimeout: #this confirms you that the request has reached server
    do_something
except:
    print "unable to reach server"
    raise

从上面的代码中,您可以发送异步请求而无需获得响应。根据需要指定超时。如果不是,它不会超时。