Python Web Program
As we all know, for all Web applications, is essentially a socket server, the user's browser is actually a socket client.
The Python web framework is divided into two categories:
- Write your own socket and handle requests yourself
- Based on WSGI (web Server Gateway Interface Web Services Gateway Interface, implementing socket function), processing requests yourself
Shown
Self-written web framework
#!/usr/bin/Env Python#coding:utf-8Import Socket def handle_request (client): BUF= Client.recv (1024x768) Client.send ("http/1.1 ok\r\n\r\n") Client.send ("Hello, Seven.") def main (): Sock=Socket.socket (socket.af_inet, socket. Sock_stream) Sock.bind (('localhost',8000)) Sock.listen (5) whiletrue:connection, Address=sock.accept () handle_request (connection) connection.close ()if__name__ = ='__main__': Main ()
The above is achieved through the socket, but for the real development of the Python Web program, it is generally divided into two parts: server programs and Applications. The server program is responsible for encapsulating the socket server and collating the various data requested when the request arrives. The application is responsible for the specific logical processing. In order to facilitate the development of the application, there are many web frameworks, such as Django, Flask, web.py and so on. Different frameworks have different ways of developing them, but in any case, the applications you develop will have to work with the server program to provide services to the user. In this way, the server program needs to provide different support for different frameworks. This chaotic situation is bad for both the server and the framework. For the server, you need to support a variety of frameworks, for the framework, only the servers that support it can be used by the development of the application. Standardization becomes particularly important at this time. We can set up a standard that is supported by the framework as long as the server program supports this standard, so they can work with it. Once the criteria are determined, both parties are implemented. In this way, the server can support more frameworks that support standards, and the framework can use more servers that support standards.
WSGI (Web server Gateway Interface) is a specification that defines the interface format between Web apps and Web servers written in Python, enabling decoupling between Web apps and Web servers.
The standalone WSGI server provided by the Python standard library is called Wsgiref.
#!/usr/bin/Env Python#coding:utf-8#以下代码就是django的祖宗 # import wscgi fromwsgiref.simple_server Import make_serverdef runserver (environ, start_response): Start_response ('OK', [('Content-type','text/html')]) return ''if__name__ = ='__main__': #建立socket连接 httpd= Make_server ("',8000, runserver) print"serving HTTP on port 8000 ..."
#while循环, waiting for user request
#只要有请求进来, execute the Runserver function Httpd.serve_forever () #预处理请求 (environ contains the information returned by the client)
Customizing the web Framework
Develop a web framework of your own using the Wsgiref module provided by the Python standard library
#!/usr/bin/Env python#-*-coding:utf-8-*- fromwsgiref.simple_server Import Make_serverdef f1 ():return 'F1'def f2 ():return 'F2'#1define a dictionary that defines the function routers= {'/index/': F1,'/login/':F2,}def runserver (environ, start_response):
#environ封装用户相关的所有信息
#environ ["Path_info"] read the URL of the user request
Start_response ('OK', [('Content-type','text/html')]) #根据url的不同, perform different functions, return different stringsRequest_url= environ['Path_info']#print environ #这里可以通过断点来查看它都封装了什么数据#如果用户请求的url和咱们定义的url匹配ifRequest_url in Routers.keys ():func_name = Routers[request_url]()
ret = Func_name ()
return ret
else:return '404'if__name__ = ='__main__': httpd= Make_server ("',8000, runserver) print"serving HTTP on port 8000 ..."Httpd.serve_forever ()
Template engine
Users using your web framework are not just returning a string, they may need more information, so we typically write the HTML that will be returned to the user in the specified file before returning.
<!DOCTYPE HTML><HTML><HeadLang= "en"> <MetaCharSet= "UTF-8"> <title></title></Head><Body> <H1>Hello</H1> <Divstyle= "style="color:red;font-size:50px; ">World ---((x))</Div></Body></HTML>
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Title</title> <Linkrel= "stylesheet"href= "/static/css/commons.css"></Head><Body> <H1>Home</H1> <H2>{{Name}}</H2> <H2>{{Age}}</H2> <ul>{% for item in user_list%}<Li>{{Item}}</Li>{% endfor%}</ul></Body></HTML>
#!/usr/bin/env python#-*-coding:utf-8-*-from wsgiref.simple_server import make_serverdef F1 (): F = open ("Templates/t1 . html ") data = F.read () f.close () #让返回的信息跟数据库的信息替换 (dynamic) import time Db_str = str (time.time ()) data = Dat A.replace ("((x))", Db_str) #jinja2模板给你提供更复杂的替换 return datadef F2 (): F = open ("templates/t2.html") data = F.read () F.close () from jinja2 import Template template = Template (data) #接受值, make a special replacement ret = Template.render (name= "Koka", user_list=["ASD", "Qwe"]) return Ret.encode ("Utf-8") #1 define a dictionary that defines the function routers = {'/index/': F1, '/login/': F2, }def runserver (environ, start_response): #environ封装用户相关的所有信息 #environ ["Path_info"] read the URL of the user request Start_response (' 200 OK ', [(' Content-type ', ' text/html ')]) #根据url的不同, perform different functions, return different strings Request_url = environ[' path_info '] #print envir On #这里可以通过断点来查看它都封装了什么数据 #如果用户请求的url和咱们定义的url匹配 if Request_url in Routers.keys (): Func_name = Rou Ters[request_url] () ret = Func_name () return ret else:return ' 404 ' if __name__ = = ' __main__ ': httpd = m Ake_server (", 8000, runserver) print" Serving HTTP on port 8000 ... " Httpd.serve_forever ()
MVC & MVT
First we write the web framework for the convenience of others to use, give him a standard (specification)
Put all the rules of the routing operation to: Put the operation of the DD in the model, the operation of the ULR into the Controller directory (function), view to store all the HTML template
All mappings in the URL are user_list list:(' index.html ', index).
This is the MVC framework.
First, we're looking at the process of web framework.
So MTV is:
Models Handling DB Operations
Templates HTML templates
Views Processing function Request
For more information, please refer to:
Http://www.cnblogs.com/wupeiqi/articles/4491246.html
Http://www.cnblogs.com/luotianshuai/p/5258572.html
Python Learning Note 15 web framework