search
HomeBackend DevelopmentPython TutorialAfter reading this, you must understand what WSGI is

python video tutorial column introduces what WSGI is.

After reading this, you must understand what WSGI is

I have been writing python web for several years, but I still don’t know what WSGI is and whether there are many people there. This is normal, because as a developer, you rarely need to understand what wsgi is to build a website.

But if you want to write a web framework yourself, you have to understand wsgi.

To review, when we use python for web development, we usually develop it based on a certain web framework, such as django or flask and other frameworks. After the business development is completed, it must be deployed to a server to provide external access.

If you search online at this time, they will tell you that you need to use gunicorn or uwsgi to deploy. So what are gunicorn and uwsgi?

You will understand after looking at this picture. I found the picture from the Internet.

The role played by uwsgi or gunicorn here is the role of the web server. The server here is a software-level server, used to process HTTP requests sent by the browser and return the response results to the front end. The main task of the Web framework is to process business logic and generate results to the web server, and then the web server returns them to the browser.

The communication between the web framework and the web server needs to follow a set of specifications, and this specification is WSGI.

Why should we come up with such a set of regulations? Standards are to unify standards and facilitate everyone's use

Imagine that our mobile phone charging interfaces are now Type-c. Type-c is a standard. Mobile phone manufacturers produce mobile phones and chargers according to this standard. Manufacturers produce chargers according to Type-c specifications, and mobile phones from different manufacturers can be used with chargers from different manufacturers. However, Apple has its own set of regulations, which ultimately results in the Android charger being unable to charge Apple.

![

](p9-juejin.byteimg.com/tos-cn-i-k3…)

How to write an application that complies with the WSGI specification ( What about frameworks) programs and servers?

As shown in the picture above, the left side is the web server, and the right side is the web framework, or application.

Application

WSGI stipulates that the application must be a callable object (the callable object can be a function, a class, or one that implements __call__ instance object), and must accept two parameters, and the return value of the object must be an iterable object.

We can write the simplest example of an application

HELLO_WORLD = b"Hello world!\n"def application(environ, start_response):
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)    return [HELLO_WORLD]复制代码

application is a function, which must be a callable object, and then receives two parameters, the two parameters are: environ and start_response

  • environ is a dictionary that stores all content related to the HTTP request, such as headers, request parameters, etc.
  • start_response is a function passed by the WSGI server, used to response header, status code is passed to the server.

Calling the start_response function is responsible for passing the response header and status code to the server. The response body is returned to the server by the application function. A complete http response is provided by these two functions.

Any web framework that implements wsgi will have such a callable object

Server

WSGI What the server does is to receive an HTTP request each time and build an environ object , then call the application object, and finally return the HTTP Response to the browser.

The following is the code of a complete wsgi server

import socketimport sysfrom io import StringIOclass WSGIServer(object):
    address_family = socket.AF_INET
    socket_type = socket.SOCK_STREAM
    request_queue_size = 1

    def __init__(self, server_address):
        # Create a listening socket
        self.listen_socket = listen_socket = socket.socket(
            self.address_family,
            self.socket_type
        )        # Allow to reuse the same address
        listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)        # Bind
        listen_socket.bind(server_address)        # Activate
        listen_socket.listen(self.request_queue_size)        # Get server host name and port
        host, port = self.listen_socket.getsockname()[:2]
        self.server_name = socket.getfqdn(host)
        self.server_port = port        # Return headers set by Web framework/Web application
        self.headers_set = []    def set_app(self, application):
        self.application = application    def serve_forever(self):
        listen_socket = self.listen_socket        while True:            # New client connection
            self.client_connection, client_address = listen_socket.accept()            # Handle one request and close the client connection. Then
            # loop over to wait for another client connection
            self.handle_one_request()    def handle_one_request(self):
        self.request_data = request_data = self.client_connection.recv(1024)        # Print formatted request data a la 'curl -v'
        print(''.join(            ' {line}\n'.format(line=line)                for line in response.splitlines()
            ))
            self.client_connection.sendall(response)        finally:
            self.client_connection.close()


SERVER_ADDRESS = (HOST, PORT) = 'localhost', 8080def make_server(server_address, application):
    server = WSGIServer(server_address)
    server.set_app(application)    return serverif __name__ == '__main__':
    httpd = make_server(SERVER_ADDRESS, application)
    print('WSGIServer: Serving HTTP on port {port} ...\n'.format(port=PORT))
    httpd.serve_forever()复制代码

Of course, if you just write a server for development environment, you don’t have to go to so much trouble to reinvent the wheel yourself, because there are built-in modules in Python. Provides wsgi server functionality.

from wsgiref.simple_server import make_server
srv = make_server('localhost', 8080, application)
srv.serve_forever()复制代码

Only 3 lines of code can provide a wsgi server. Isn’t it super convenient? Finally, let’s visit and test the effect of the browser initiating a request

Above This is an introduction to wsgi. If you have a deep understanding of wsgi, you can familiarize yourself with PEP333

Related free learning recommendations: python video tutorial

The above is the detailed content of After reading this, you must understand what WSGI is. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.