Alfred Huang
Alfred Huang

Reputation: 18235

Async http request with python3

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

I want a minimal example, I've tried the 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 the async mode works, the print('exit') should display first.

Can anyone help?

Upvotes: 5

Views: 4097

Answers (1)

Cthulhu
Cthulhu

Reputation: 1372

Using threading (based on your own 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)

Upvotes: 4

Related Questions