The Wsgi interface between Python program and server connection

Source: Internet
Author: User
Tags command line header http request response code web services in python

This article mainly introduced the Python program and the server Connection Wsgi interface, is the Python network programming study important content, needs the friend may refer to under

Understanding the HTTP protocol and HTML documents, we actually understand that the essence of a Web application is:

The browser sends an HTTP request;

The server receives the request and generates an HTML document;

The server sends the HTML document as the body of the HTTP response to the browser;

The browser receives an HTTP response and extracts the HTML document from the HTTP body and displays it.

Therefore, the simplest Web application is to save the HTML file first, with a ready-made HTTP Server software, receive user requests, read HTML from the file, return. These common static servers, such as Apache, Nginx, and lighttpd, are the only thing to do.

If you want to generate HTML dynamically, you need to implement these steps yourself. However, accepting HTTP requests, parsing HTTP requests, sending HTTP responses is hard work, and if we write the underlying code ourselves and haven't started writing Dynamic HTML, it will take months to read the HTTP specification.

The right thing to do is that the underlying code is implemented by specialized server software, and we use Python to focus on generating HTML documents. Because we don't want to be exposed to TCP connections, HTTP RAW requests, and response formats, we need a unified interface that allows us to focus on writing Web services in Python.

This interface is the Wsgi:web Server Gateway Interface.

Wsgi interface definition is very simple, it only requires web developers to implement a function, you can respond to HTTP requests. Let's look at one of the simplest web versions of "Hello, web!" :

?

1 2 3 def application (environ, start_response): Start_response (' OK ', [(' Content-type ', ' text/html ']]) return '

The application () function above is an HTTP handler that conforms to the WSGI standard and receives two parameters:

Environ: A Dict object that contains all HTTP request information;

Start_response: A function that sends an HTTP response.

In the application () function, call:

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

Sends the header of the HTTP response, note that the header can only be sent once, that is, the start_response () function can be invoked only once. The Start_response () function receives two parameters, one is the HTTP response code, the other is a list of HTTP headers, each header is represented by a tuple containing two str.

Usually, you should send Content-type hair to the browser. Many other commonly used HTTP headers should also be sent.

Then the return value of the function '

' Sends the body as an HTTP response to the browser.

With Wsgi, our concern is how to get the HTTP request information from the Environ Dict object, then construct the HTML, send the header through Start_response (), and return to the body.

The entire application () function itself does not involve any part of parsing HTTP, that is, the underlying code does not need to be written by ourselves, and we are only responsible for considering how to respond to the request at a higher level.

But wait, what does this application () function call? If we call it ourselves, two parameters environ and start_response we cannot provide, and the returned STR cannot be sent to the browser.

So the application () function must be invoked by the WSGI server. There are many servers that meet the WSGI specification and we can pick one to use. But for now, we just want to test that our application () function really can output HTML to the browser, so we need to quickly find the simplest WSGI server to run our Web application.

The good news is that Python has a built-in WSGI server, the module called Wsgiref, which is a reference implementation of a WSGI server written in pure python. The so-called "reference implementation" means that the implementation conforms fully to the WSGI standard, but does not take into account any operational efficiencies and is intended for development and testing purposes only.

Running the WSGI service

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

?

1 2 3 4 5 # hello.py def application (environ, start_response): Start_response (' OK ', [(' Content-type ', ' text/html ')] return ' & Lt;h1>hello, Web!

Then, write a server.py that is responsible for starting the WSGI server and loading the application () function:

?

1 2 3 4 5 6 7 8 9 10 11-12 # server.py # import from Wsgiref module: from wsgiref.simple_server import Make_server # Imports our own written application function: from Hello import appl Ication # Create a server with an IP address that is empty, a port is 8000, and the handler function is APPLICATION:HTTPD = Make_server (', 8000, application) print ' Serving HTTP on por T 8000 ... "# Start listening for HTTP requests: Httpd.serve_forever () Try

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

Note: If the 8000 port is already occupied by another program, startup will fail, please modify it to another port.

After successful startup, open the browser, enter Http://localhost:8000/, you can see the results:

At the command line, you can see the log information that Wsgiref prints:

Press CTRL + C to terminate the server.

If you think this Web application is too simple, you can change it a little bit and read the path_info from the Environ, which can show more dynamic content:

?

1 2 3 4 5 # hello.py def application (environ, start_response): Start_response (' OK ', [(' Content-type ', ' text/html ')] return ' & Lt;h1>hello,%s!

You can enter the username as part of the URL in the Address bar and will return Hello, xxx!:

Is it a bit of a web app?

Summary

No matter how complex the Web application is, the portal is a WSGI handler function. All input information for HTTP requests can be obtained through environ, and the output of the HTTP response can be start_response () plus function return value as body.

Complex Web applications, which rely on a single WSGI function to handle or are too low-level, we need to abstract the web framework on top of WSGI to further simplify web development.

Related Article

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.