Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What makes WSGI is synchronous in nature?

(Correct me if I made a mistake)

WSGI is a standard interface for python based web application. But it's said that WSGI is synchronous in nature. So, even something like Tornado will handle WSGI app synchonously. It means, the wsgi standard makes python web app synchronous.

I don't have a good understanding on how asynchronous program works internally. What I know is, async program doesn't wait I/O task until it's done to do other tasks which doesn't involve I/O task.

If this is correct, a very basic python web server which handle wsgi app will be something like this:

import socket


class Server(object):

    def __init__(self, host, port, app):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((host, port))
        self.socket.listen(5)
        self.app = app

    def serve(self):
        while True:
            client, addr = self.socket.accept()
            request = client.recv()
            response_body = self.handle_app(request)
            client.sendall(response_body)
            client.close()

    def handle_app(self, request):
        # processing request stuff
        environ = self.environ_logic()  # some logics
        start_response = self.start_response_logic()  # some logics
        return self.app(environ, start_response)

So, what makes WSGI is synchronous in nature? With that example, which part make it not async? And, is it possible to create a web server (in python) that capable handling wsgi app asynchronously?

like image 408
Mas Bagol Avatar asked Dec 05 '15 18:12

Mas Bagol


1 Answers

The interface between the webserver and the Python process it calls is synchronous -- as in the WSGI calling process is blocking, waiting for a response from the backend before it proceeds. Whatever happens within your Python code can be synchronous, asynchronous, or do whatever -- but the webserver's worker thread will block until it gets a response.

Webserver thread                      YourCode 
    |                                    |
    |       --callout to WSGI code-->    |
    |                                    |
    |                              [Do stuff ...]
[blocking]                         [     ...    ]
    |                              [Do stuff ...]
    |                                    |
    |                                  Done!
    |   <--Your response to the server-- |
 Proceed!

This does not mean this is the only thread in the webserver, of course.

like image 174
zxq9 Avatar answered Nov 02 '22 14:11

zxq9