Python Server Dynamic Resource Request

Server Dynamic Resource Request

1. Browser request dynamic page process

2. WSGI

How do you run a Django application and Flask application on the Web server you just built, and how do you adapt to different web architectures without any changes?

In the past, the choice of Python web architecture was subject to the availability of web servers, and vice versa. If architecture and servers can work together, that's good.
However, it is possible to face (or have faced) the following problems when combining a server with an architecture, and find that they are not designed to work together:
So how can you ensure that you can run web servers under multiple architectures without modifying the server and architecture code? The answer is Python Web Server Gateway Interface.
WSGI allows developers to separate their choice of Web frameworks from web servers. You can mix matching web servers and web frameworks and choose a suitable pairing. For example, you can run Django, Flask, or Pyramid on Gunicorn or Nginx/uWSGI or Waitress. True hybrid matching benefits from WSGI's support for both servers and architectures:
Web servers must have WSGI interfaces, and all modern Python Web frameworks already have WSGI interfaces, which allow you to work with the server and the characteristic web frameworks without modifying the code.

WSGI is supported by web servers, and web frameworks allow you to choose matches that suit you, but they also make it easy for server and framework developers to focus on their preferred areas and expertise without interrupting each other. Other languages have similar interfaces: java has Servlet API s, Ruby has Rack.

3. Define WSGI interface

The WSGI interface definition is very simple. It only requires Web developers to implement a function to respond to HTTP requests. Let's take a look at the simplest version of "Hello World!":

The application() function above is an HTTP handler that meets the WSGI standard. It receives two parameters:

environ: a dict object that contains all HTTP request information;
start_response: A function that sends HTTP responses.
The entire application() function itself does not involve any part of parsing HTTP, that is, the underlying web server parsing part and the application logic part are separated, so that developers can concentrate on a field.

But wait, how does this application() function call? If we call it ourselves, we can't provide the two parameters environ and start_response, and the returned str can't be sent to the browser.

So the application() function must be invoked by the WSGI server. There are many WSGI-compliant servers. The goal of our web server project at this time is to be a server that can parse both static and dynamic web pages.