Home  >  Article  >  Backend Development  >  Python Web Application: WSGI Basics

Python Web Application: WSGI Basics

巴扎黑
巴扎黑Original
2017-03-18 11:44:111163browse

This article was originally translated by MaNong.com - Xiao Hao. Please read the reprint requirements at the end of the article for reprinting. Welcome to participate in our paid contribution plan!

Underlying Django, Flask, Bottle and all other Python web frameworks is the Web Server Gateway Interface, or WSGI for short. WSGI is to Python what Servlets are to Java - a common specification for web servers that allows different web servers and application frameworks to interact based on a common API. However, for most things, the Python version is fairly simple to implement.

WSGI is defined in the PEP 3333 protocol. If you want to learn more after reading this article, the author recommends that readers read the introduction first.

This article will introduce you to WSGI instructions from an application developer's perspective, and show you how to develop applications directly through WSGI (if you can't wait).

Your first WSGI application

Here is the most basic Python web application:

def app(environ, start_fn):
    start_fn('200 OK', [('Content-Type', 'text/plain')])
    return ["Hello World!\n"]

That’s it! the entire file. Name it app.py and run it on any WSGI compilable server, and you will get a Hello World accompanied by a 200 response status code. You can use gunicorn to complete it, install it through pip (pip install gunicorn) and execute gunicorn app:app. This command tells gunicorn to get the WSGI callable from the application variables in the application module.

Just now, I was very excited. Can you run an application with just three lines of code? That must be logging in some sense (excluding PHP, since mod_php is in play). I bet you want to know more about it now.

So what is the most important part of a WSGI application?

  • A WSGI application is a Python callable, like a function, a class, or a class instance with a __call__ method

  • A callable application must accept two arguments: environ, a Python dictionary containing the necessary data, and start_fn, which itself is callable.

  • The application must be able to call start_fn with two parameters: the status code (string), and a list represented by a header of two tuples.

  • The application returns a convenient iterable object containing bytes in the return body, the streaming part - for example, each containing only the "Hello, World!" string list. (If app is a class, it can be done in the __iter__ method)

For example, the following two examples are equivalent to the first one:

class app(object):

    def __init__(self, environ, start_fn):
        self.environ = environ
        self.start_fn = start_fn

    def __iter__(self):
        self.start_fn('200 OK', [('Content-Type', 'text/plain')])
        yield "Hello World!\n"
class Application(object):
    def __call__(self, environ, start_fn):
        start_fn('200 OK', [('Content-Type', 'text/plain')])
        yield "Hello World!\n"

app = Application()

You may have started to think about what you can use these things for, but the most relevant one is to write middleware.

Make it active

Middleware is a convenient way to extend the functionality of WSGI applications. Since you only need to provide a callable object, you can wrap it in any other function.

For example, suppose we want to detect the contents of environ. We can easily create a middleware to accomplish this as follows:

import pprint

def handler(environ, start_fn):
    start_fn('200 OK', [('Content-Type', 'text/plain')])
    return ["Hello World!\n"]

def log_environ(handler):
    def _inner(environ, start_fn):
        pprint.pprint(environ)
        return handler(environ, start_fn)
    return _inner

app = log_environ(handler)

Here, log_environ is a function that returns a function that delays the original in the environ argument Decorate this parameter before the callback.

The advantage of writing middleware in this way is that the middleware and the processor do not need to know or care about each other. You can easily bind log_environ to a Flask application, for example, because the Flask application is a WSGI application.

Some other useful middleware designs:

import pprint

def handle_error(handler):
    def _inner(environ, start_fn):
        try:
            return handler(environ, start_fn)
        except Exception as e:
            print e  # Log error
            start_fn('500 Server Error', [('Content-Type', 'text/plain')])
            return ['500 Server Error']
    return _inner

def wrap_query_params(handler):
    def _inner(environ, start_fn):
        qs = environ.get('QUERY_STRING')
        environ['QUERY_PARAMS'] = urlparse.parse_qs(qs)
        return handler(environ, start_fn)
    return _inner

If you don’t want your file to have a big pyramid base, you can use reduceApply to on multiple middlewares.

# Applied from bottom to top on the way in, then top to bottom on the way out
MIDDLEWARES = [wrap_query_params,
               log_environ,
               handle_error]

app = reduce(lambda h, m: m(h), MIDDLEWARES, handler)

Taking advantage of the start_fn parameter, you can also write middleware that decorates the response body. Below is a middleware whose content type header is text/plain and inverts the output result.

def reverser(handler):

    # A reverse function
    rev = lambda it: it[::-1]

    def _inner(environ, start_fn):
        do_reverse = []  # Must be a reference type such as a list

        # Override start_fn to check the content type and set a flag
        def start_reverser(status, headers):
            for name, value in headers:
                if (name.lower() == 'content-type'
                        and value.lower() == 'text/plain'):
                    do_reverse.append(True)
                    break

            # Remember to call `start_fn`
            start_fn(status, headers)

        response = handler(environ, start_reverser)

        try:
            if do_reverse:
                return list(rev(map(rev, response)))

            return response
        finally:
            if hasattr(response, 'close'):
                response.close()
    return _inner

It's a little confusing due to the separation of start_fn and the response body, but it still works perfectly.

Also note that in order to strictly follow the WSGI specification, we must check the close method in the response body and call it if it exists. It is possible for a WSGI application to return a write function instead of an iterable object calling the handler, and you may need to deal with this if you want your middleware to support older applications.

Once you start playing with native WSGI a little bit, you start to understand why Python has a bunch of web frameworks. WSGI makes it very easy to build something from the ground up. For example, you may be considering the following routing problem:

routes = {
    '/': home_handler,
    '/about': about_handler,
}

class Application(object):
    def __init__(self, routes):
        self.routes = routes

    def not_found(self, environ, start_fn):
        start_fn('404 Not Found', [('Content-Type', 'text/plain')])
        return ['404 Not Found']

    def __call__(self, environ, start_fn):
        handler = self.routes.get(environ.get('PATH_INFO')) or self.not_found
        return handler(environ, start_fn)

If you like the flexibility of the following resource collection, it is very convenient to directly use WSGI to create wheels.

  • Template Library: Throw in any template you like (e.g. Jinja2, Pystashe) and return the rendered template from your processor!

  • Use a library to help you with routing, such as Routes or Werkzeug’s routing. In fact, if you want to use WSGI easily, take a look at Werkzeug.

  • Use any Flask or similar database migration library.

Of course, for non-professional applications, you may also want to use a framework, so that some special examples such as this can also be reasonably solved.

What about the server?

There are many ways to serve WSGI applications. We've already discussed Gunicorn, a pretty good choice. uWSGI is another good choice. But make sure you set up things like nginx before serving these static things, and you should have a fixed starting node.

The above is the detailed content of Python Web Application: WSGI Basics. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn