I. Essence of Web Framework
All Web applications are essentially a socket server, and the user's browser is a socket client.
Return different contents according to different paths
You can write several simple pages and then access the corresponding page test by http://127.0.0.1:8080/page name
import socket server = socket.socket() # The default is TCP Agreement server.bind(('127.0.0.1',8080)) # binding IP port server.listen(5) # Monitoring Semi-Link Pool: Protecting Computer Security while True: conn, addr = server.accept() # Waiting for connection data = conn.recv(1024) # Receiving client information # follow HTTP Protocol, which adds a response status line to the response message conn.send(b'HTTP/1.1 200 OK\r\n\r\n') res = data.decode('utf-8') current_path = res.split('\r\n')[0].split(' ')[1] # String Cutting, Getting Path # print(current_path) # Return different contents according to different paths if current_path == '/index': # conn.send(b'index') with open('templates/111.html','rb') as f: conn.send(f.read()) elif current_path == '/login': conn.send(b'login') else: conn.send(b'404') conn.close()
Browser access page request information:
HTTP protocol mainly specifies the communication format between client and server
Response-related information can be seen in the network tab of the browser debug window. You can cut pages to get the required requests based on view information
First line of request b'GET / HTTP/1.1\r\n Request header Host: 127.0.0.1:8080\r\n Connection: keep-alive\r\n Cache-Control: max-age=0\r\n Upgrade-Insecure-Requests: 1\r\n User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36\r\n Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\r\n Accept-Encoding: gzip, deflate, br\r\n Accept-Language: zh-CN,zh;q=0.9,en;q=0.8\r\n Cookie: csrftoken=3vPenhmlRQb8Tvl4okwYM0OZpDCl3P7rbxvfpRDOHJy1zUApw89ugxM6OZSxhIBM\r\n \r\n //Requestor '
http://127.0.0.1:8080/index
view Open:
Return different page requests according to different paths - Functional Edition
import socket sk = socket.socket() sk.bind(('127.0.0.1',8001)) sk.listen() # Encapsulating different parts of content into functions def index(url): # read index.html Page content with open("index.html",'rb',encoding="utf-8") as f: s = f.read() # Returns byte data return bytes(s,encoding="utf-8") def login(url): with open("login.html",'rb',encoding="utf-8") as f: s = f.read() return bytes(s, encoding="utf-8") list1= [ ("templates/111.html","/index"), ("templates/login.html",'/login'), ] while True: # Waiting for connection conn,add = sk.accept() data = conn.recv(1024) # Receive messages from clients # from data Get the path in data = str(data,encoding='utf-8') # Converting received byte-type data into strings print("data>>>",data) # Press\r\n cutting,url Access paths separated from messages sent from browsers url = data.split("\r\n")[0].split(' ')[1] print("url>>>>",url) conn.send(b'HTTP/1.1 200 OK\r\n\r\n') #follow http Protocol, so the message to reply also needs to add status line # Return different contents according to different paths. reponse Is the specific responder func = None for i in list1: if i[0].split("/")[1] == url: func = i[1] break # print("func>>>",func) if func: reponse = func(url) else: reponse = b"404 not found!" conn.send(reponse) conn.close() # There are still some problems.//TODO
Server applications and Applications
For python web programs in real development, they are generally divided into two parts: server programs and applications.
The server program is responsible for encapsulating the socket server and sorting out all kinds of data requested when the request arrives.
The application is responsible for specific logical processing. In order to facilitate the development of applications, there are many Web frameworks, such as Django, Flask, web.py and so on. Different frameworks have different ways of development, but in any case, the developed applications must cooperate with server programs in order to provide services for users.
WSGI (Web Server Gateway Interface) is a specification that defines the interface format between web applications written in Python and web server programs, and realizes the decoupling between web applications and web server programs.
uwsgi and Gunicorn are commonly used WSGI servers. The independent WSGI server provided by Python standard library is called wsgiref, and the Django development environment uses this module as the server.
1.wsgiref module
Using wsgiref module to replace the socket server part of our own web Framework
# Pre-splitting code # http://127.0.0.1/index accesses the corresponding name to the corresponding page from wsgiref.simple_server import make_server def index(): return 'index' def reg(): return 'res' def login(): return 'login' def error(): return '404' urls = [ ('/index',index), ('/reg',reg), ('/login',login), ] def run(env,reponse): reponse('200 OK', []) # Fixed format print(env) # Processing http format data, forming a field for you to call current_path = env.get('PATH_INFO') # if current_path == '/index': # return [b'index'] func = None for url_tuple in urls: if current_path == url_tuple[0]: func = url_tuple[1] # If the routing matches, go back to the corresponding function break if func: res = func() else: res = error() return [res.encode('utf-8')] if __name__ == '__main__': server = make_server('127.0.0.1',8080,run) # Always listen for addresses, and whenever there is a request, it calls the last function or object: run() to execute server.serve_forever()
Split the descendant code# urls.py Store pages with access links from views import * urls = [ ('/index',index), ('/reg',reg), ('/login',login), ] # views.py Store access page functions def index(): return 'index' def reg(): return 'res' def login(): return 'login' def error(): return '404' # wsgiref.py Storage startup from wsgiref.simple_server import make_server from urls import urls from views import * def run(env,response): response('200 OK', []) # Fixed format does not need to be mastered print(env) # take http Format data is processed to form a field for you to call current_path = env.get('PATH_INFO') func = None for url_tuple in urls: if current_path == url_tuple[0]: func = url_tuple[1] # If the routing matches, go back to the corresponding function. break if func: res = func(env) else: res = error(env) return [res.encode('utf-8')] if __name__ == '__main__': server = make_server('127.0.0.1',8080,run) server.serve_forever()