python video tutorial column introduces WSGI.
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.

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

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.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...


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

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft