First, the nature of web framework
We can understand this: all Web applications are essentially a socket server, and the user's browser is a socket client. This allows us to implement the web framework ourselves.
1. Custom Web framework for semi-finished products
Import= socket.socket () sk.bind (("127.0.0.1",)Sk.listen () while True: = sk.accept () = Conn.recv (8096) Conn.send (b "OK") conn.close ()
It can be said that Web services are essentially expanded on the basis of these more than 10 lines of code. This piece of code is their ancestor.
User's browser input URL, will send data to the server, what data will the browser send? How to send? Who's going to fix this? You this website is this stipulation, his that website according to his that stipulation, this internet still can play?
Therefore, there must be a unified rule, let everyone send messages, receive messages when there is a format basis, can not be written casually.
This rule is the HTTP protocol, after the browser sends the request information, the server replies to the response information, should follow this rule.
The HTTP protocol mainly specifies the communication format between the client and the server, how does the HTTP protocol specify the message format?
Let's first print what the message we received on the server is.
Import= socket.socket () sk.bind (("127.0.0.1",)Sk.listen () while True: = sk.accept () = Conn.recv (8096) print (data) # Prints the message from the browser conn.send (b"OK") ) conn.close ()
Output:
b'get/http/1.1\r\nhost:127.0.0.1:8080\r\nconnection:keep-alive\r\nupgrade-insecure-requests:1\r\ nuser-agent:mozilla/5.0 (Windows NT 10.0; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/64.0.3282.186 safari/537.36\r\naccept:text/html,application/xhtml +xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\ndnt:1\r\naccept-encoding:gzip, deflate, br\r\ naccept-language:zh-cn,zh;q=0.9\r\ncookie:csrftoken= rkbxh1d3m97iz03rpbojx1br6mhhudhyx5pszuxxg3boewh1lxfpgogwn93zh3zv\r\n\r\n'
Web framework Nature and the first Django instance