Getting started with python socket programming and getting started with python Programming
Flask or other frameworks are well-encapsulated. We don't need to care about how routes and sessions are implemented, now we use socket To implement a To do website with registration and login functions, so that we can have a little deeper understanding of the backend framework (of course, you can also directly look at the Flask source code ).
The main program runserver. py code is as follows:
#! /Usr/bin/env python #-*-coding: UTF-8-*-import socketfrom exts import Requestfrom route import response_for_requestfrom datetime import datetimedef run_server (host = '', port = 1207 ): # create a socket. socket () Class s with socket. socket () as s: # Set s to release the port immediately after the server is closed to avoid the Address already in use error s. setsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1) # bind host and port s. bind (host, port) while 1: # Start listening for incoming connections. The maximum number of connections that can be suspended is 5 s. listen (5) # accept the connection and continuously read the content connection, address = s according to buffer_size. accept () r = ''buffer_size = 1024 while 1: data = connection. recv (1, 1024 ). decode ('utf-8') r + = data if len (data) <buffer_size: break # prevent blank requests from the browser if len (r. split () <2: continue # The final obtained r is an http request header string, which is parsed and then the corresponding content Request = request (r) is returned using sendall) # print time for each request, request method and path print (str (datetime. now () [: 19], request. method, request. path) response = response_for_request (request) connection. sendall (response) connection. close () if _ name _ = '_ main _': run_server ()
For a brief description of the run_server function code, you can see the comments. from exts import Request: imports a Request class from exts, which is compiled by yourself and used to parse the http Request header, this part is very simple. You can search for http request-related content on the Internet and write it by yourself, including the path, method, fields, and body of the returned request header, string-related operations.
From route import response_for_request: import the corresponding function from route. py, that is, pass in the Request class in the previous step, and return the corresponding webpage content. The specific implementation will be explained later.
It can be said that the main program has been compiled, and the entire logic is also very simple. Use socket to listen to the connection, parse the request, and return the corresponding content of the request. In the future, you only need to process the resolution request and response, and the main program does not need to modify it.