First, the nature of web framework
1. Socket-based processing of requests
#!/usr/bin/env python3#coding:utf8import socketdef handle_request (client): #接收请求 buf = client.recv (1024x768) print (BUF) # Return information Client.send (bytes ('Welcome Liuyao webserver
', ' UTF8 ')) def main (): #创建sock对象 sock = Socket.socket () #监听80端口 sock.bind ((' localhost ', 8000)) #最大连接数 Sock.listen (5) Print (' Welcome nginx ') #循环 while True: #等待用户的连接, the default accept block executes when requested connection,address = Sock.accept () #把连接交给handle_ Request function Handle_request (connection) #关闭连接 connection.close () if __name__ = = ' __main__ ': Main ()
2. Based on WSGI
WSGI, full name Web server gateway Interface, or Python Web server gateway Interface, is a simple and easy-to-pass between a Web server and a Web application or framework defined for the Python language The interface used. Similar interfaces have appeared in many other languages since WSGI was developed.
The official definition of WSGI is the Python Web Server Gateway Interface. From the name it can be seen that this thing is a gateway, that is, gateways. The purpose of a gateway is to convert between protocols.
WSGI is a low-level interface between a Web server and a Web application or application framework to enhance the common denominator of portable web application development. WSGI is designed based on the existing CGI standards.
Many frameworks have their own WSGI servers, such as Flask,webpy,django, CherryPy, and so on. Of course, the performance is not good, the Web server comes with more testing purposes, the release of the use of the production environment of the WSGI server or the joint nginx do UWSGI.
The standalone WSGI server provided by the Python standard library is called Wsgiref.
#!/usr/bin/env python#coding:utf-8# Import WSGI module from wsgiref.simple_server import make_serverdef runserver (environ, start _response): Start_response (' K OK ', [(' Content-type ', ' text/html ')] return [bytes ("Welcome webserver". Encode (' UTF8 ') ))]if __name__ = = ' __main__ ': httpd = Make_server (', 8000, runserver) print ("Serving HTTP on port 8000 ...") httpd.serve_ Forever () #接收请求 #预处理请求 (something that encapsulates a lot of HTTP requests)
After the request comes, execute the Runserver function.
Schematic diagram:
When the user sends the request, the socket gives the request to the function handler and then returns it to the user.
II. Customizing the web framework
The Wsgiref module provided by the Python standard library develops a web framework of its own
Previous use of Wsgiref can only access one URL
The following can be processed according to the different URL requests you visit and returned to the user
#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server Import make_serverdef runserver (environ, start_response ): Start_response (' $ OK ', [(' Content-type ', ' text/html ')]) #根据url的不同, return different strings #1 get the Url[url from where? Execute Runserver when the request comes in. #wsgi给咱们封装了这些请求, these requests are encapsulated, Environ & start_response] request_url = environ[' Path_info '] print (Request_url) #2 Make different corresponding #print according to the URL environ #这里可以通过断点来查看它都封装了什么数据 if request_url = = '/login ': return [bytes ("Welcome login", ' UTF8 ')] elif Request_url = = '/reg ': return [bytes ("Welcome reg", ' UTF8 ')] else: return [Bytes ('404! No found
', ' UTF8 ')]if __name__ = = ' __main__ ': httpd = Make_server (', 8000, runserver) print ("Serving HTTP on port 8000 ...") httpd . Serve_forever ()
Of course, although the above is handled according to different URLs, but if a large number of URLs, then the code is very cumbersome to write.
So use the following method to process
#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server Import make_serverdef index (): return [Bytes ('Index
', ' UTF8 ')]def login (): return [Bytes ('Login
', ' UTF8 ')]def reg (): return [Bytes ('Reg
', ' UTF8 ')]def layout (): return [Bytes ('Layout
', ' UTF8 ')] #定义一个列表 the URL and the function above do a corresponding urllist = [('/index ', Index), ('/login ', login), ('/reg ', Reg), ('/layout ', layout),] def runserver (environ, start_response): Start_response (' OK ', [(' Content-type ', ' text/html ')]) #根据url的不同, return a different string # 1 Get url[url Where do I get it? When the request comes in, execute the RUNSERVER,WSGI to let us encapsulate these requests, which are encapsulated, environ & start_response] Request_url = environ[' Path_info '] Print (request_url) #2 depending on the URL to make a different corresponding #print environ #这里可以通过断点来查看它都封装了什么数据 #循环这个列表 Find the URL you opened to return the URL corresponding function for URL I n urllist:if request_url = = Url[0]: return url[1] () Else: #url_list列表里都没有返回404 return [Bytes ('404 Not Found
', ' UTF8 ')] if __name__ = = ' __main__ ': httpd = Make_server (', 8000, runserver) print ("Serving HTTP on port 8000 ...") HTTP D.serve_forever ()
Third, template engine
The actions above are returned to the user according to the URL visited by the user a string such as return XXX
Case:
First write a index.html page
Content:
IndexWelcome Index
Login.html page
Content:
LoginWelcome Login
Python code:
#!/usr/bin/env python #coding: utf-8from wsgiref.simple_server import make_serverdef index (): #把index页面读进来返回给用户 Indexfile = open (' index.html ', ' r+ '). Read () return [bytes (indexfile, ' UTF8 ')]def login (): loginfile = open (' login.html ', ' r+ '). Read () return [bytes (loginfile, ' utf8 ')]urllist = [('/login ', login), ('/index ', index),]def runserver (environ, Start_response): Start_response (' OK ', [(' Content-type ', ' text/html ')]) #根据url的不同, return a different string #1 get Url[url from where? When the request comes in and executes RUNSERVER,WSGI to encapsulate these requests, these requests are encapsulated, Environ & start_response] request_url = environ[' Path_info ') print ( Request_url) #2 make different #print based on the URL environ #这里可以通过断点来查看它都封装了什么数据 for the URL in urllist: #如果用户请求的url和咱们定义的rul匹配 if Request_url = = Url[0]: #执行 return url[1] () Else: #url_list列表里都没有返回404 return [bytes ('404 Not Found
', ' UTF8 ')]if __name__ = = ' __main__ ': httpd = Make_server (', 8000, runserver) print ("Serving HTTP on port 8000 ...") httpd . Serve_forever ()
However, the above content can only be returned to static content, cannot return dynamic content
So how do we get back to dynamic content?
Customize a special set of syntax to replace
Use the Open Source Tool JINJA2 to follow its specified syntax
Index.html follows Jinja syntax to replace, cycle, and judge
First show the approximate effect, specific jinja2 will be in the next chapter Django notes to explain in detail
Index.html page
Content:
Title
{{Name}}
{{Age}}
{{Time}}
{% for item in user_list%}
- {{Item}}
{% endfor%}
{% if num = = 1}
num = = 1
{% Else%}
num = = 2
{% ENDIF%}
Python code:
#!/usr/bin/env python#-*-coding:utf-8-*-import time #导入wsgi模块from wsgiref.simple_server import make_server# Import Jinja module from JINJA2 Import Templatedef index (): #打开index. HTML data = open (' index.html '). Read () #使用jinja2渲染 template = Tem Plate (data) result = Template.render (name = ' Yaoyao ', age = ' + ', time = str (time.time ()), user_list = [' Linux ', ' Pyth On ', ' Bootstarp '], num = 1) #同样是替换为什么用jinja because he is more than just text he also supports if judgment & for loop operation #这里需要注意因为默认是的unicode的编码所以设置为utf-8 return [b Ytes (result, ' utf8 ')]urllist = [('/index ', index),]def runserver (environ, start_response): Start_response (' K OK ', [(' Content-type ', ' text/html ')]) #根据url的不同, returns a different string #1 gets where Url[url gets it? When the request comes in and executes the Runserver, # WSGI encapsulates the requests, and the requests are encapsulated, Environ & Start_response] request_url = environ[' Path_info '] print (request_url) #2 make different corresponding #循环这个列表 for URLs in Urll IST: #如果用户请求的url和咱们定义的rul匹配 If Request_url = = Url[0]: print (URL) return url[1] () Else: #urllist列表里都没有返回404 return [Bytes ('404 Not Found
', ' UTF8 ')]if __name__ = = ' __main__ ': httpd = Make_server (', 8000, runserver) print ("Serving HTTP on port 8000 ...") httpd . Serve_forever ()
IV. MVC and MTV
1.MVC
The full name is the Model view Controller, which is the abbreviation for the Models-view (Controller), a software design paradigm that organizes the code with a separate approach to business logic, data, and interface, and aggregates business logic into a single component , there is no need to rewrite business logic while improving and customizing the interface and user interaction. MVC is uniquely developed to map the traditional input, processing, and output functions in a logical graphical user interface structure.
Place routing rules into urls.py
The Func function in the controller that operates the URLs
To operate the database in the db.py in the party model.
Place HTML pages into views
Schematic diagram:
2.MTV
Models Handling DB Operations
Templates HTML templates
Views Processing function Request
Schematic diagram:
The above is the whole content of this article, I hope that everyone's study has helped.