使用python 2.7的简单异步HTTP请求
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用python 2.7的简单异步HTTP请求相关的知识,希望对你有一定的参考价值。
我有一个python 2.7项目,需要简单地发出一个https POST请求而不阻塞主线程。我看到的例子主要是同时发送多个请求,然后在等待所有请求完成时阻塞。其他人有https问题。其他人是3.0或以上。任何人都可以发布一个与2.7一起使用的示例,用于不阻止主线程的单个https发布请求吗?
答案
如何使用新线程调度请求?
from threading import Thread
from urllib2 import Request, urlopen, HTTPError, URLError
def post(url, message):
request = Request(url, message)
try:
response = urlopen(request)
print "Child thread: response is " + response.read()
print "Child thread: Request finished"
except HTTPError as e:
print "Request failed: %d %s", e.code, e.reason
except URLError as e:
print "Server connection failed: %s", e.reason
print "Main thread: Creating child thread"
thread = Thread(target=post, args=("http://icanhazip.com", "test_message"))
thread.start()
# Do more work here while request is being dispatched
print "Main thread: Child thread started"
# Will block until child thread is finished
thread.join()
上面的脚本打印(可能因异步而有所不同):
Main thread: Creating child thread
Main thread: Child thread started
Child thread: response is 81.218.42.131
Child thread: Request finished
注意:代码在Python 2.7.13上进行了测试
以上是关于使用python 2.7的简单异步HTTP请求的主要内容,如果未能解决你的问题,请参考以下文章
无法在 MACOS mojave 上运行来自 python 2.7 的 postgres 请求