search
HomeBackend DevelopmentPython TutorialPython Web Application: WSGI Basics

Python Web Application: WSGI Basics

Mar 18, 2017 am 11:44 AM
python

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
The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python vs. C  : Pros and Cons for DevelopersPython vs. C : Pros and Cons for DevelopersApr 17, 2025 am 12:04 AM

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

Python: Time Commitment and Learning PacePython: Time Commitment and Learning PaceApr 17, 2025 am 12:03 AM

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft