使用python 2.7的简单异步HTTP请求

问题描述 投票:0回答:1

我有一个python 2.7项目,需要简单地发出一个https POST请求而不阻塞主线程。我看到的例子主要是同时发送多个请求,然后在等待所有请求完成时阻塞。其他人有https问题。其他人是3.0或以上。任何人都可以发布一个与2.7一起使用的示例,用于不阻止主线程的单个https发布请求吗?

python-2.7 asynchronous post https
1个回答
0
投票

如何使用新线程调度请求?

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上进行了测试

© www.soinside.com 2019 - 2024. All rights reserved.