I am trying to make an async HTTP request in Python. I use requests - which is very nice - which does not provide async possibilities.
我试图在Python中创建异步HTTP请求。我使用请求 - 这是非常好的 - 它不提供异步的可能性。
Everytime I want to send an HTTP request, I start a new thread. It executes properly and should returns the response within the main thread so I could execute a callback method.
每次我想发送HTTP请求时,我都会启动一个新线程。它正确执行并应在主线程内返回响应,以便我可以执行回调方法。
I am currently using the threading module like this:
我目前正在使用这样的线程模块:
class MyConnection
# ...
def make_request(self):
# Use requests lib here
response = requests.request(...)
self.receive_response(response)
def receive_response(self):
# process response here because it is my callback method
def start(self):
thread = threading.Thread(target=self.make_resquest)
thread.start()
Everything is working fine but methods receive_response should be called within the main thread instead of the thread I launched in start method. How could I go back to the main thread to execute the receive_response method ?
一切正常,但方法receive_response应该在主线程中调用,而不是我在start方法中启动的线程。我怎么能回到主线程来执行receive_response方法?
Many thanks for your help !
非常感谢您的帮助 !
1 个解决方案
#1
0
You could make 'thread' and 'response' member variables of the class and join the thread in 'receive_response'. After you have joined the thread you know that the thread has finished receiving 'response' so it is ready for processing.
你可以创建类的'thread'和'response'成员变量,并在'receive_response'中加入线程。加入线程后,您知道线程已完成接收“响应”,因此可以进行处理。
#1
0
You could make 'thread' and 'response' member variables of the class and join the thread in 'receive_response'. After you have joined the thread you know that the thread has finished receiving 'response' so it is ready for processing.
你可以创建类的'thread'和'response'成员变量,并在'receive_response'中加入线程。加入线程后,您知道线程已完成接收“响应”,因此可以进行处理。