Python-wsgi interface

Source: Internet
Author: User
Tags response code

Wsgi interface read: 98477

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

    1. The browser sends an HTTP request;

    2. The server receives the request and generates an HTML document;

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

    4. The browser receives an HTTP response, removing the HTML document from the HTTP body and displaying it.

Therefore, the simplest Web application is to first save the HTML file, with a ready-made HTTP Server software, receive user requests, read HTML from the file, return. Apache, Nginx, lighttpd, and so on these common static server is doing this thing.

If you want to generate HTML dynamically, you need to implement the above steps yourself. However, accepting HTTP requests, parsing HTTP requests, and sending HTTP responses are all menial jobs, and if we're writing these underlying code ourselves, it's going to take months to read the HTTP specification before we start writing Dynamic HTML.

The correct approach 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 lets us 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 the web developer to implement a function, you can respond to HTTP requests. Let's look at one of the simplest web versions of "Hello, web!" :

def application(environ, start_response):    start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)]) return [b‘

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

    • Environ: An object that contains all HTTP request Information dict ;

    • Start_response: A function that sends an HTTP response.

In the application() function, call:

start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)])

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

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

The return value of the function is then sent to the b‘ browser as the body of the HTTP response.

With WSGI, all we care about is getting the environ dict HTTP request information from this object, then constructing the HTML, start_response() sending the header, and finally returning 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 us, we are only responsible for considering how to respond to the request at a higher level.

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

So application() the function must be called by the WSGI server. There are many servers that conform to the WSGI specification, and we can pick one to use. But for now, we just want to test as soon as possible that the functions we write application() can actually output HTML to the browser, so find the simplest WSGI server and run our Web application.

The good news is that Python has a built-in Wsgi server called Wsgiref, which is a reference implementation of a WSGI server written in pure python. The so-called "reference implementation" means that the implementation is fully compliant with the WSGI standard, but does not consider any operational efficiency and is intended for development and testing purposes only.

Running the WSGI service

Let's write hello.py the WSGI handler function for the Web application first:

# hello.pydef application(environ, start_response): start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)]) return [b‘

Then, write another server.py , responsible for starting the WSGI server, loading the application() function:

# server.py# 从wsgiref模块导入:from wsgiref.simple_server import make_server# 导入我们自己编写的application函数:from hello import application# 创建一个服务器,IP地址为空,端口是8000,处理函数是application:httpd = make_server(‘‘, 8000, application)print(‘Serving HTTP on port 8000...‘)# 开始监听HTTP请求:httpd.serve_forever()

Make sure that the above two files are in the same directory and then enter at the command line python server.py 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 wsgiref print log information:

Press to Ctrl+C terminate the server.

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

# hello.pydef application(environ, start_response): start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)]) body = ‘‘PATH_INFO‘][1:] or ‘web‘) return [body.encode(‘utf-8‘)]

You can enter a user name in the Address bar as part of the URL, which will return Hello, xxx! :

Does it feel like a little web app?

Summary

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

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

Python-wsgi interface

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.