Python Web Application: WSGI Basics
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

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.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
