Asynchronous HTTP request with python3

Is there a way to make async python3 look like node.js do?

I want a minimal example, I tried below but still works with sync mode.

import urllib.request

class MyHandler(urllib.request.HTTPHandler):

    @staticmethod
    def http_response(request, response):
        print(response.code)
        return response

opener = urllib.request.build_opener(MyHandler())
try:
    opener.open('http://www.google.com/')
    print('exit')
except Exception as e:
    print(e)

      

If async mode works, it should be displayed first print('exit')

.

Can anyone please help?

+3


source to share


1 answer


Using streaming (based on native code):



import urllib.request
import threading

class MyHandler(urllib.request.HTTPHandler):
    @staticmethod
    def http_response(request, response):
        print(response.code)
        return response

opener = urllib.request.build_opener(MyHandler())
try:
    thread = threading.Thread(target=opener.open, args=('http://www.google.com',))
    thread.start()      #begin thread execution
    print('exit')

    # other program actions

    thread.join()       #ensure thread in finished before program terminates
except Exception as e:
    print(e)

      

+2


source







All Articles