What is a Web Server What is WSGI and specific implementation examples

Take Flask as an example: Source code analysis (1): WSGI From: https://www.csdn.net/tags/MtTaEgzsNTYyNzcyLWJsb2cO0O0O.html
2022-03-26 18:35:03

To understand the source code of Flask, you must have a certain Python foundation and be familiar with the concepts and usage of decorator s, magic method s, iterator s, and generator s. Another point is that you must understand WSGI. Here are some concepts related to WSGI and some code to help understand WSGI.

What is a Web server

A Web server generally refers to a website server, which refers to a program that resides on a certain type of computer on the Internet. It can process requests from Web clients such as browsers and return corresponding responses. It can also place website files for the world to browse. It can place data files. , let the world download. At present, the three most mainstream Web servers are Apache, Nginx, and IIS.

What is WSGI (Protocol Specification)

The Web Server Gateway Interface (Web Server Gateway Interface) is an interface specification defined to allow a Web server and a Python program or framework to communicate data. That is to say, as long as both the Web server and the Web application comply with the WSGI protocol, the Web server and the Web application can be combined arbitrarily.

WSGI application (an instance that implements the wsgi protocol)

According to the provisions of WSGI, a Web application (or referred to as a WSGI application) must be a callable object and must meet the following three conditions:

  1. Accepts two parameters environ and start_response
  2. Internally calls the start_response function to generate status codes and response headers
  3. Returns an iterable of response bodies

Implement a WSGI application with functions

def application(environ, start_response):
    """
        environ: A dictionary containing all the information requested.
        start_response: The function used to initiate the response. The parameters are the status code and the response header.
	"""
    start_response('200 OK', [('Content-Type', 'text/plain')])
    yield b'Hello, World!\n'

Implementing a WSGI application with classes

class AppClass:
    def __init__(self, environ, start_response):
        self.environ = environ
        self.start_response= start_response

    def __iter__(self):
        self.start_response('200 OK', [('Content-Type', 'text/plain')])
        yield b'Hello, World!\n'

Flask's WSGI implementation

class Flask(_PackageBoundObject):
	def wsgi_app(self, environ, start_response):
        ...
         
	def __call__(self, environ, start_response):
        """Shortcut for :attr:`wsgi_app`."""
        return self.wsgi_app(environ, start_response)

WSGI server

Simple implementation of a WSGI server (just for understanding)

from io import BytesIO

def call_application(app, environ):
    status = None
    headers = None
    body = BytesIO()
    
    def start_response(rstatus, rheaders):
        nonlocal status, headers
        status, headers = rstatus, rheaders
        
    app_iter = app(environ, start_response)
    try:
        for data in app_iter:
            assert status is not None and headers is not None, \
                "start_response() was not called"
            body.write(data)
    finally:
        if hasattr(app_iter, 'close'):
            app_iter.close()
    return status, headers, body.getvalue()

environ = {...}
status, headers, body = call_application(app, environ)

WSGI server using Python built-in module wsgiref

from wsgiref.simple_server import make_server

def wsgi_app(environ, start_response):
    ...

server = make_server('0.0.0.0', 5000, wsgi_app)
server.serve_forever()

WSGI server using WerkZeug module

When running with the flask run command, it is actually running the WSGI server implemented by Werkzeug

from werkzeug.serving import run_simple

def wsgi_app(environ, start_response):
    ...
    
run_simple('0.0.0.0', 5000, wsgi_app)

refer to

WEB Server_Baidu Encyclopedia (baidu.com)
Web Server Gateway Interface - Wikipedia

Tags: Python Web Development Django

Posted by reaper7861 on Mon, 16 May 2022 13:42:56 +0300