在python中,如何在不等待响应的情况下发出http请求。我不在乎取回任何数据,我只需要通过服务器注册一个页面请求。
现在我使用这个代码:
urllib2.urlopen("COOL WEBSITE")
但很明显,这会暂停脚本,直到返回响应,我只想发出一个请求并继续前进
我该怎么做?
此处所需的内容称为线程或异步。
线程:
- 将对
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标准库中没有实现这一点的标准方法
使用具有此支持的请求库。
示例:
from requests import async
async.get("http://google.com")
还有一个使用restclient库的第三个选项内置(有一段时间)异步支持:
from restclient import GET
res = GET("http://google.com", async=True, resp=True)
使用线程:
import threading
threading.Thread(target=urllib.urlopen, args=('COOL WEBSITE',)).start()
不要忘记args
参数应该是元组。这就是为什么后面有,
。
您可以使用请求库执行以下操作
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
根据上面的代码,您可以发送异步请求而不需要得到响应。根据需要指定超时。否则就不会超时。
gevent可能是一个合适的选择。
第一个接线插座:
import gevent
import gevent.monkey
monkey.patch_socket()
monkey.patch_ssl()
然后使用gevent.spawn()
来封装您的请求以生成greenlet。它不会阻塞主线程,而且速度非常快!
这里有一个简单的教程。