More and more people are using Python for Web development because python code is elegant, beautiful and easy to maintain. Python Web frameworks are flourishing. Currently, popular frameworks include Django, small and flexible Flask and Bottle, and Asynchronous frameworks Tornado and SANic with high performance. As long as you choose one of these frameworks and read its documentation, you can easily build a Web app without having to worry about the principle of its implementation.
This article is intended to take a look at web development.
Front end page three musketeers
We open the browser and enter a url yukunweb.com, and then we see the page shown by the browser. At this time, open the browser developer tool, click Network, refresh the page, and we will see the url of the request below, click Response, You can see the HTML file information returned by the server to the browser. If you copy the content of the Response, save it as index.html and open it in the browser, you can still see the content of the home page, but it seems to lack some of the style and function of the page.
This is because when the browser received the home page HTML source code, it will according to the RULES of HTML to display the page, and then according to the HTML link, automatically send HTTP request to the server, get the corresponding picture, and JavaScript, CSS and other resources, and finally show a complete page. So we’ll see a lot of extra requests under Network with.js,.css, etc.
The page we see is what the browser is showing us, according to the rules of HTML. HTML tells the browser that there’s navigation, there’s the main bar, there’s the sidebar. How this information is displayed, or how it is displayed, is the result of CSS files. For example, the navigation pull down hide and pull up display is what JavaScript does.
If you want to do Web development, you must be familiar with HTML, CSS, JavaScript knowledge of the three swordmen, here recommended W3school front-end tutorial, is also where I learn front-end: W3school
The client communicates with the server
Understand the three musketeers, you know how to write a web page. So what happens from when we type the URL into the browser’s address bar to when the Web page is rendered.
As shown in the figure, this kind of Web browser that obtains server resources by sending a request can be called a client. First, send a request to the server, most of which is accessed in the form of GET request. The server receives your request, and then takes the requested resource and returns it to the client.
How does the server communicate with the client, how does the server understand the request from the client. Here, a Protocol specification is needed, namely HTTP(HyperText Transfer Protocol). It can be said that the Web is built on the HTTP protocol for communication.
As shown in the previous example, open the browser to yukunweb.com, open the browser developer tool, click the TAB marked in the picture (remember to click View Parsed), you can see the first two lines of the request sent by the client to the server.
GET/HTTP/1.1 Host: www.yukunweb.comCopy the code
The GET at the beginning of the first line indicates the type of server requested, called method. The subsequent character/identifies the resource object requested, the request URI. The final HTTP/1.1, or HTTP version number, is used to indicate the HTTP protocol functionality used by clients.
To sum up, the first line of the request reads: request access to a /(home) page resource on an HTTP server. So the Host in the second line indicates the requested domain name, which is the address of the server.
In the case of a POST request, there is not only the request header information, but also a Form Data request entity content.
What about the server that receives the request? It will return the result of processing the request content in the form of a response. Look at the first line in the diagram:
HTTP / 1.1 200 OKCopy the code
The opening part is still the server’s HTTP version, followed by the 200 OK indicating the status code and reason phrase for the result of the request. The 200 status code indicates a successful response, the common 404 indicates an access error, and the 500 indicates a server response error. There are no fixed rules for OK, you can also tell it to return GOOD or something.
The next line shows the server information. This site uses an Nginx server. The next line shows the date and time when the response was created. The content-type on the next line indicates the Type of Content that the client depends on to determine whether the Content in the response is a web page, audio, image, etc.
The HTTP protocol is the communication protocol between the client and server. The Definitive GUIDE to HTTP is recommended for more in-depth reading.
WSGI
If you visit a music address http://www.yukunweb.com/search-result/?keywords=, you can access to the music on this site keywords in the search results. We know that the client sends a request to the server, so how does the server get the resource? In fact, this is handed back to the back-end running application, such as when you grab a page to get information, these logical processing must be our program to run again.
However, the low-level operations of receiving and parsing HTTP requests from clients and sending HTTP responses are definitely not handled by back-end applications. So, to focus only on Web business logic, you need a grafting layer between the server and the Web application ————WSGI.
What is WSGI(Web Server Gateway Interface)?
WSGI translates to Web Server Gateway Interface. It is simply a specification that defines how Web servers interact with Python applications so that Web applications written in Python can interconnect with Web servers (Nginx/Apache).
The address of the specification: PEP 333
WSGI is the cornerstone of Python Web development, and with it you have it all. It exists for two purposes:
- Describes how the Web server interacts with the Web application (passing client requests to the application),
- Describes how a Web application handles requests and returns data to the server.
Since there is a WSGI library in Python’s built-in standard library, WSGIref, we will write an example of WSGI’s purpose based on it:
from wsgiref.simple_server import make_server def application(environ, start_response): status = '200 OK' response_headers = [('Content-type', 'text/html')] start_response(status, response_headers) body = '<h1>Hello, {name} !!! </h1>'.format(name=environ['PATH_INFO'][1:] or 'WSGI') return [body.encode('utf-8')] app = make_server('', 8000, application) app.serve_forever()Copy the code
Run the program. If no error is reported, open your browser and enter 127.0.0.1:8000 and 127.0.0.1:8000/GuTianle to see the page returned by the program. As shown in figure:
We can see a request whose entry requires only a WSGI handler. Because all request information is contained in environ, we can return different data based on this information.
Parameters:
- Environ: a dictionary type that stores all client-specific information. If you want to know what parameters are in it, you can change the code above and add one above the return line
for k, v in environ.items()
To print out all the parameters in the dictionary. - Start_response: a callable object that accepts two mandatory and one optional arguments:
- Status: A string representing the HTTP response status string, such as 200,404
- Response_headers: a list of tuples of the form (header_name, header_value) representing headers for an HTTP response, e.g. (‘ content-type ‘, ‘text/ HTML’).
- Exc_info (Optional) : Used for information that the server needs to return to the browser in case of an error
Returns: an iterable that the server iterates through to get the entire body content, which can be HTML or JSON.
Here’s a quick overview of what WSGI is and what it does. If you understand WSGI, writing a Web framework for Python is easy. This is why Python has hundreds of web frameworks.
Implement a WSGi-based framework
Now that we understand what WSGI does, it’s a breeze to implement a simple Web framework based on it.
from wsgiref.simple_server import make_server class Application(object): def __init__(self, environ, start_response): self.start_response = start_response self.path = environ['PATH_INFO'] def __iter__(self): if self.path == '/': status = '200 OK' response_headers = [('Content-type', 'text/html')] self.start_response(status, esponse_headers) yield '<h1>Hello,World! </h1>'.encode('utf-8') elif self.path == '/wsgi': status = '200 OK' response_headers = [('Content-type', 'text/html')] self.start_response(status, response_headers) yield '<h1>Hello,WSGI! </h1>'.encode('utf-8') else: status = '404 NOT FOUND' response_headers = [('Content-type', 'text/html')] self.start_response(status, response_headers) yield '<h1>404 NOT FOUND</h1>'.encode('utf-8') if __name__ == "__main__": App = make_server('127.0.0.1', 8000, Application) print('Serving HTTP on port 8000... ') app.serve_forever()Copy the code
This Application class is just another layer of encapsulation for WSGI. Since WSGI functions return an iterable object, we need to implement an __iter__ method that controls the client’s request routing and returns different outputs.
There are a lot of things to consider if you want to scale into a decent framework, such as a handy routing system like Flask, and handling of user requests. Flask version 0.1 had 200 lines removed from the comments, but now the latest version…