I have a python 2.7 project and need to simply make an https POST request without blocking the main thread. The examples I have seen have mostly been sending multiple requests at the same time and then blocking while waiting for them all to complete. Others have problems with https. And others are 3.0 or above. Can anyone post an example that works with 2.7 for a single https post request that does not block the main thread?
1 Answer
What about dispatching the request using a new thread?
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()
The above script prints (may vary due to async):
Main thread: Creating child thread
Main thread: Child thread started
Child thread: response is 81.218.42.131
Child thread: Request finished
Note: code was tested on Python 2.7.13