Before learning to customize the Web framework, we have a clear understanding of what a web framework needs to be, essentially, a web framework is a socket Server.
There are Wsgi (Eg:django, Flask ...) in front of the common Dynamic web framework. Or you write the socket (Tornado), then to the URL routing system processing, and then to a function or a class, and then in the template (Common jinja2) to get the template and then the template and the data extracted from the database is mixed together to form a string and then return to the user ( Python3 is sent with a byte encoding).
Here is an example of WSGI:
WSGI is used to receive requests and then encapsulate requests. For example, Django is encapsulated in the request.
Customizing the web Framework
1. Socket implementation of Web frame prototype
1 #!/usr/bin/env python2 #-*-Coding:utf8-*-3 4 ImportSocket5 6 7 defhandle_request (client):8BUF = CLIENT.RECV (1024)9Client.send (b"http/1.1 OK \r\n\r\n")
# with open ('./html/index.html ', ' R ') as F: #执行时这里报错 error details are described below OneWith open ('./html/index.html','RB') as F: A Client.send (F.read ()) - - the defMain (): -Ip_port = ('127.0.0.1', 9999) -Sock =Socket.socket (Socket.af_inet,socket. SOCK_STREAM) - Sock.bind (Ip_port) + Sock.listen () - + whileTrue: Aconn, addr =sock.accept () at handle_request (conn) - conn.close () - - - if __name__=='__main__': - Print("\033[31;1m Server is running ... \033[0m") inMain ()
Encountered a small problem here, Pycharm execution error:
' GBK ' codec can't decode byte 0x80 in position 84:illegal multibyte sequence
Workaround:
(1) Modify open file mode for ' RB '
With open ('./html/index.html'RB') as F: Client.send (F.read ())
(2) Set encoding on open
With open ('./html/index.html'R', encoding= ' Utf-8 ' ) as F: Client.send (F.read ())
2 socket-based web framework
This way of implementation of the Web framework is mainly tornado
3. WSGI-based web framework
The current mainstream part of the web framework, such as Django, Flask ... It's all in this way
Python--Custom web framework