Detailed description of the WSGI interface connecting the Python program to the server

Source: Internet
Author: User
This article mainly introduces the WSGI interface connecting the Python program to the server, which is an important part of Python network programming learning. For more information about HTTP and HTML, see, we understand that the essence of a Web application is:

  • The browser sends an HTTP request;
  • The server receives the request to generate an HTML document;
  • The server sends the HTML document as the HTTP response Body to the browser;
  • The browser receives an HTTP Response and retrieves and displays the HTML document from the HTTP Body.

Therefore, the simplest Web application is to save HTML files and use a ready-made HTTP server software to receive user requests, read HTML from the files, and return the results. Apache, Nginx, Lighttpd, and other common static servers do this.

If you want to dynamically generate HTML, You need to implement the above steps by yourself. However, it is hard to accept HTTP requests, parse HTTP requests, and send HTTP responses. If we write the underlying code ourselves, we haven't started to write dynamic HTML yet, it takes a month to read the HTTP specification.

The correct method is that the underlying code is implemented by specialized server software. We use Python to focus on generating HTML documents. Because we do not want to be exposed to TCP connections, original HTTP requests, and response formats, we need a unified interface that allows us to focus on writing Web Services in Python.

This Interface is WSGI: Web Server Gateway Interface.

The WSGI interface is easy to define. It only requires Web developers to implement a function to respond to HTTP requests. Let's take a look at the simplest Web version of "Hello, web !" :

def application(environ, start_response):  start_response('200 OK', [('Content-Type', 'text/html')])  return 'Hello, web!'

The preceding application () function is an HTTP processing function conforming to the WSGI standard. It receives two parameters:

  1. Environ: A dict object that contains all HTTP request information;
  2. Start_response: a function that sends an HTTP response.

In the application () function, call:

Start_response ('2017 OK ', [('content-type', 'text/html')])

The HTTP response Header is sent. Note that the Header can only be sent once, that is, the start_response () function can only be called once. The start_response () function receives two parameters, one being an HTTP response code and the other being a group of HTTP headers represented by a list. Each Header is represented by a tuple containing two str.

Generally, Content-Type hair should be sent to the browser. Many other common HTTP headers should also be sent.

Then, the return value of the function is 'hello, web! 'Send the HTTP response Body to the browser.

With WSGI, we care about how to get the HTTP request information from the dict object environ, construct HTML, send the Header Through start_response (), and finally return the Body.

The entire application () function does not involve any parsing of HTTP. That is to say, the underlying code does not need to be compiled by ourselves. We only need to consider how to respond to the request at a higher level.

But wait. How can I call this application () function? If we call the two parameters environ and start_response, we cannot provide them, and the returned str cannot be sent to the browser.

Therefore, the application () function must be called by the WSGI server. There are many servers that comply with the WSGI specifications. We can choose one. But now, we just want to test the application () function we have compiled as soon as possible to output HTML to the browser. So we need to find the simplest WSGI server, run our Web application.

The good news is that Python has a built-in WSGI server. This module is called wsgiref. It is a reference implementation of the WSGI server written in pure Python. The "reference implementation" means that the implementation fully complies with the WSGI standard, but does not consider any running efficiency, and is only used for development and testing.
Run WSGI Service

We first compile hello. py to implement the WSGI processing function of the Web application:

# hello.pydef application(environ, start_response):  start_response('200 OK', [('Content-Type', 'text/html')])  return 'Hello, web!'

Then, write a server. py to start the WSGI server and load the application () function:

# Server. py # import from wsgiref module: from wsgiref. simple_server import make_server # import our own application function: from hello import application # create a server. The IP address is blank, the port is 8000, and the processing function is application: httpd = make_server ('', 8000, application) print" Serving HTTP on port 8000... "# Start listening for HTTP requests: httpd. serve_forever () Try

Make sure that the above two files are in the same directory, and then input python server. py in the command line to start the WSGI server:

NOTE: If Port 8000 is already occupied by other programs, startup will fail. Change it to another port.

After the startup is successful, open the browser and enter http: // localhost: 8000/to view the result:

You can view the log information printed by wsgiref on the command line:

Press Ctrl + C to terminate the server.

If you think this Web application is too simple, you can modify it a little and read PATH_INFO from environ to display more dynamic content:

# hello.pydef application(environ, start_response):  start_response('200 OK', [('Content-Type', 'text/html')])  return 'Hello, %s!' % (environ['PATH_INFO'][1:] or 'web')

You can enter the user name in the address bar as part of the URL and return Hello, xxx! :

Is it a bit of a Web App?
Summary

No matter how complicated a Web application is, the entry is a WSGI processing function. All input information of the HTTP request can be obtained through environ. The output of the HTTP response can be indicated by start_response () and the return value of the function as the Body.

Complex Web applications rely solely on a WSGI function for processing. We need to abstract the Web framework above WSGI to further simplify Web development.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.