WSGI in the end is what?

WSGI often encounter when developing a Python Web, so WSGI what in the end is it? In this paper we WSGI together to uncover the mysterious veil!

First look at the WSGI introduction :

The full name Python Web Server Gateway Interface, specifies a standard interface between web servers and Python web applications or web framework to improve web application portability across a range of web servers. Specific to view the official documentation

From the above description we can see:

  1. WSGI interface standard is a protocol / specification;
  2. Communication (action) is the interval between the Web server and the Python Web applications;
  3. The purpose is to develop standards to ensure mutual communication between different Web servers can be different Python program

You may ask, why WSGI?

First, we identify some of the specific process web application to process the request:

  1. User operates the browser sends a request;
  2. Forwarding the request to the corresponding web server
  3. the web server forwards the request to the web application, web application processing request
  4. The web application request to the web server returns the result returned by the web server in response to the user results
  5. The browser receives the response, show users

It can be seen that, Web servers need to communicate with the web application request, but there are many web servers ah, the Python web application development framework also corresponds more ah, so WSGI emerged, defines a set of communication standards. Imagine, if not a unified standard, it would Framework Web presence and Web server data can not be matched, then developers will be limited, which is obviously unreasonable.

Since the definition of the standard, then the WSGI standards or norms?

web server before the request to the web application, you need to first http message into a format specified WSGI.

WSGI provisions, Web program must have a callable and callable that accepts two parameters, returns an iterable:

  1. environ: dictionary, containing all the information requested
  2. start_response: callable function call in the object, to initiate the response, including the status parameter code, headers, etc.

Through the above study, along with the realization of a simple WSGI service bar

First, we write a http handler in line with a WSGI standard:

def hello(environ, start_response):
    status = "200 OK"
    response_headers = [('Content-Type', 'text/html')]
    start_response(status, response_headers)
    path = environ['PATH_INFO'][1:] or 'hello'
    return [b'<h1> %s </h1>' % path.encode()]

This method is responsible for getting environ dictionary path_info, is acquiring request path, then the front end of the show.

Next, we need to start a WSGI server used to process server authentication, use the built-in Python WSGI server module wsgiref, write server.py:

# coding:utf-8
"""
desc: WSGI服务器实现
"""
from wsgiref.simple_server import make_server
from learn_wsgi.client import hello


def main():
    server = make_server('localhost', 8001, hello)
    print('Serving HTTP on port 8001...')
    server.serve_forever()


if __name__ == '__main__':
    main()

Execute python server.py, open the browser " HTTP: // localhost: 8001 / A ", can be verified.

By implementing a simple WSGI services, we can see: http can get all the information requested by environ, http response data are available through the return value of a function as start_response plus body.

Of course, more than just a simple case, then the internal Web framework python WSGI specification is how to follow it? In Flask example,

Flask and WSGI

Examples of the program in Flask app is a callable, we created the class Flask app instance when invoked achieved __call__ method, __ call__ method calls wsgi_app () method, which completes the process of requests and responses, the WSGI this method is called by the server incoming requests data, access to data is returned:

def wsgi_app(self, environ, start_response):
    ctx = self.request_context(environ)
    error = None
    try:
        try:
            ctx.push()
            response = self.full_dispatch_request()
        except Exception as e:
            error = e
            response = self.handle_exception(e)
        except:  # noqa: B001
            error = sys.exc_info()[1]
            raise
        return response(environ, start_response)
    finally:
        if self.should_ignore_error(error):
            error = None
        ctx.auto_pop(error)

def __call__(self, environ, start_response):
    return self.wsgi_app(environ, start_response)

Flask of werkzeug library is a very good WSGI tool library, and then after a specific implementation of our detailed study.

the above.

Guess you like

Origin www.cnblogs.com/ybjourney/p/12004002.html