Analysis on the operation of WSGI interface and WSGI service in Python

  • 2021-08-21 20:51:44
  • OfStack

HTTP format
HTTP GET request format:


GET /path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3

1 line per Header1, and the newline character is \r\n .

HTTP POST request format:


POST /path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3

body data goes here...

When two consecutive\ r\ n are encountered, the Header part ends, and the following data is all Body.

Format of HTTP response:


200 OK
Header1: Value1
Header2: Value2
Header3: Value3

body data goes here...

The HTTP response, if it contains body, is also passed through the \r\n\r\n To separate. Note that the data type of Body is defined by the Content-Type Header, if it is a web page, Body is text, if it is a picture, Body is binary data of the picture.

When there is Content-Encoding Body data is compressed, and the most common compression method is gzip.

WSGI interface
WSGI: Web Server Gateway Interface.

WSGI interface definition is very simple, only need to implement a function, can respond to HTTP request.


# hello.py

def application(environ, start_response):
  start_response('200 OK', [('Content-Type', 'text/html')])
  body = '<h1>Hello, %s!</h1>' % (environ['PATH_INFO'][1:] or 'web')
  return [body.encode('utf-8')]

Function takes two arguments:

environ: A that contains all HTTP request information dict Object; start_response: A function that sends an HTTP response.

Running the WSGI service
Python built-in 1 WSGI server, this module is called wsgiref, it is written with pure Python WSGI server reference implementation.


# server.py

from wsgiref.simple_server import make_server
from hello import application

#  Create 1 Servers, IP The address is empty and the port is 8000 The handler function is application:
httpd = make_server('', 8000, application)
print('Serving HTTP on port 8000...')
#  Start listening HTTP Request :
httpd.serve_forever()

Enter on the command line python server.py You can start the WSGI server.

After starting successfully, open the browser and enter http://localhost:8000/ You can see the result.

Press Ctrl+C You can terminate the server.

The above is the detailed analysis of WSGI interface and WSGI service operation in Python. For more information about Python WSGI interface and WSGI service, please pay attention to other related articles on this site!


Related articles: