Table of Contents
![
Application
Server
Home Backend Development Python Tutorial You must understand what WSGI is

You must understand what WSGI is

Nov 10, 2020 pm 05:01 PM

python video tutorial column introduces WSGI.

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]复制代码
Copy after login

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&#39;.format(line=line)            for line in request_data.splitlines()
        ))
        self.parse_request(request_data)        # Construct environment dictionary using request data
        env = self.get_environ()        # It&#39;s time to call our application callable and get
        # back a result that will become HTTP response body
        result = self.application(env, self.start_response)        # Construct a response and send it back to the client
        self.finish_response(result)    def parse_request(self, text):
        request_line = text.splitlines()[0]
        request_line = request_line.rstrip(&#39;\r\n&#39;)        # Break down the request line into components
        (self.request_method,  # GET
         self.path,  # /hello
         self.request_version  # HTTP/1.1
         ) = request_line.split()    def get_environ(self):
        env = {}        # The following code snippet does not follow PEP8 conventions
        # but it&#39;s formatted the way it is for demonstration purposes
        # to emphasize the required variables and their values
        #
        # Required WSGI variables
        env[&#39;wsgi.version&#39;] = (1, 0)
        env[&#39;wsgi.url_scheme&#39;] = &#39;http&#39;
        env[&#39;wsgi.input&#39;] = StringIO.StringIO(self.request_data)
        env[&#39;wsgi.errors&#39;] = sys.stderr
        env[&#39;wsgi.multithread&#39;] = False
        env[&#39;wsgi.multiprocess&#39;] = False
        env[&#39;wsgi.run_once&#39;] = False
        # Required CGI variables
        env[&#39;REQUEST_METHOD&#39;] = self.request_method  # GET
        env[&#39;PATH_INFO&#39;] = self.path  # /hello
        env[&#39;SERVER_NAME&#39;] = self.server_name  # localhost
        env[&#39;SERVER_PORT&#39;] = str(self.server_port)  # 8888
        return env    def start_response(self, status, response_headers, exc_info=None):
        # Add necessary server headers
        server_headers = [
            (&#39;Date&#39;, &#39;Tue, 31 Mar 2015 12:54:48 GMT&#39;),
            (&#39;Server&#39;, &#39;WSGIServer 0.2&#39;),
        ]
        self.headers_set = [status, response_headers + server_headers]        # To adhere to WSGI specification the start_response must return
        # a &#39;write&#39; callable. We simplicity&#39;s sake we&#39;ll ignore that detail
        # for now.
        # return self.finish_response

    def finish_response(self, result):
        try:
            status, response_headers = self.headers_set
            response = &#39;HTTP/1.1 {status}\r\n&#39;.format(status=status)            for header in response_headers:
                response += &#39;{0}: {1}\r\n&#39;.format(*header)
            response += &#39;\r\n&#39;
            for data in result:
                response += data            # Print formatted response data a la &#39;curl -v&#39;
            print(&#39;&#39;.join(                &#39;> {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()复制代码
Copy after login

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()复制代码
Copy after login

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 You must understand what WSGI is. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 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.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 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 vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 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: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 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 for Web Development: Key Applications Python for Web Development: Key Applications Apr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

See all articles