Python Learning Path Web framework

Source: Internet
Author: User

The nature of web frameworks

Python's web framework is divided into two main categories:

1. Write your own socket and handle the request yourself

2, based on WSGI (web Server Gateway Interface Web Services Gateway Interface), processing the request yourself

As we all know, for all Web applications, is essentially a socket server, the user's browser is actually a socket client.

Look at the following code is the most essential web framework of the Web (write your own socket, request your own processing)

#!/usr/bin/env python#coding:utf-8import socketdef handle_request (client): #接收请求 buf = client.recv (1024x768) #返回信息 client.send ("http/1.1 ok\r\n\r\n") client.send ("Hello, Lili") def Main ( ): #创建sock对象 sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM) #监听80端口 sock.bind ((' localhost ', 8010)) #最大允许排队的客户端 Sock.listen (5) #循环 while True: #等待 The user's connection, the default accept block, executes connection when requested, address = sock.accept () #把连接交给handle_request函数 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 Python standard library provides a standalone WSGI server called Wsgiref

#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server Import make_serverdef runserver (environ, start_response ):    start_response (' K OK ', [(' Content-type ', ' text/html ')])    return ' 

The Runserver function is executed when the request comes in.

OK look at the Web Frame diagram (Socket & process request function)

The difference between these two types of web frameworks is that one is writing the socket itself, and one is based on WSGI.

    • Write your own socket, the representative frame of your own processing request is tornado (and Tronado has two modes, you can modify the configuration so that it can use its own written socket may also be based on WSGI)
    • WSGI-based web framework representation is Django
Custom Frames

1. Develop a web framework of your own using the Wsgiref module provided by the Python standard library

#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server Import make_serverdef runserver (environ, start_response ):    start_response (' K OK ', [(' Content-type ', ' text/html ')])    return ' 

When we visit, the access to any URL will be displayed, Hello,django, other sites are based on the user input URL different return to the user different HTML.

Since we are going to return different content based on the different URLs that the user has entered, we need to get the user's content.

#!/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 Url[url from where? When the request comes in and executes the RUNSERVER,WSGI to encapsulate these requests, these requests are encapsulated, Environ & Start_response]    request_url = environ[' Path_info ']    print Request_url    #2 according to the URL to make a different corresponding    #print environ #这里可以通过断点来查看它都封装了什么数据    if request_url = = '/home/index ':        return ' Hello Home '    elif request_url = = '/login ':        return ' Welcome to login our site. '    else:        return ' 

The user's request is less good, if the more use if this way is not possible, we can use the following methods to achieve:

#!/usr/bin/env python#-*-coding:utf-8-*-from wsgiref.simple_server import make_server ' can be split---this part can be given to the framework user,    Operation "Def index () by defined format: Return ' index ' def login (): Return ' login ' #1 define a list of functions url_list = [#这里吧URL和函数做一个对应 ('/index/', Index), ('/login/', login),]######################################################################## ' "This part can be taken out separately, as framework developer, framework using ' Def runserver (environ, start_response): Start_response (' OK ', [' Content-type ', ' Text/html ')]) #根据url的不同, returns a different string #1 gets the Url[url from? When the request comes in and executes the RUNSERVER,WSGI we encapsulate these requests, these requests are encapsulated, Environ & Start_ Response] Request_url = environ[' path_info '] #2 different corresponding #print environ #这里可以通过断点来查看它都封装了什么数据 based on the URL #循环这个列表 fo R URL in url_list: #如果用户请求的url和咱们定义的rul匹配 if Request_url = = url[0]: Print URL return  URL[1] () #执行里面的方法 else: #url_list列表里都没有返回404 return ' 404 ' if __name__ = = ' __main__ ': httpd = Make_server (", 8000, runserver) print" SerVing Tsun HTTP on port 8000 ... " Httpd.serve_forever ()

2. Template engine

In the previous step, for all login, index returns to the user browser a simple string, and the actual Web request will generally return a complex HTML-compliant string, so we will return to the user's HTML written in the specified file, and then return.

#index. html<! DOCTYPE html>
#login <! DOCTYPE html>
#!/usr/bin/env python#-*-coding:utf-8-*-from wsgiref.simple_server Import make_serverdef index (): #读取html并返回 data = Open (' html/index.html '). Read () return datadef login (): #读取html并返回 data = open (' html/login.html '). Read () Retu RN Data#1 defines a list of functions defined above url_list = [#这里吧URL和函数做一个对应 ('/index/', Index), ('/login/', login),]def runserver (environ, Start_response): Start_response (' OK ', [(' Content-type ', ' text/html ')]) #根据url的不同, return different strings #1 get Url[url from where? The request comes in and executes RUNSERVER,WSGI to let us encapsulate these requests, which are encapsulated, environ & start_response] request_url = environ[' Path_info '] #2 based on the URL Make a different corresponding #print environ #这里可以通过断点来查看它都封装了什么数据 #循环这个列表 for the URL in url_list: #如果用户请求的url和咱们定义的rul匹配 if Request_url = = url[0]: Print URL return url[1] () #执行里面的方法 Else: #url_list列表里都没有 return 404 return ' 404 ' if __name__ = = ' __main__ ': httpd = Make_server (', 8000, runserver) print "Serving HTTP on    Port 8000 ... " Httpd.sErve_forever () 

For the above code, although can be returned to the user HTML content to a realistic complex page, but there is still a problem: How to return dynamic content to the user?

    • 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

<! DOCTYPE html>
#web. py#!/usr/bin/env python#-*-coding:utf-8-*-import timefrom wsgiref.simple_server import Make_serverfrom jinja2 Import Templatedef Index (): data = open (' html/index.html '). Read () template = template (data) result = Template.ren Der (name = ' Luotianshuai ', age = ' + ', time = str (time.time ()), user_list = [' Tianshuai ', ' Tim ', ' shuaige '], num = 1) #同样是替换为什么用jinja because he is more than just text He also supports the If Judgment & for loop Operation #这里需要注意因为默认是的unicode的编码所以设置为utf- 8 return Result.encode (' utf-8 ') def login (): #读取html并返回 data = open (' html/login.html '). Read () return data#1 define a A list of functions defined above url_list = [#这里吧URL和函数做一个对应 ('/index/', Index), ('/login/', login),]def runserver (environ, start_respons E): Start_response (' OK ', [(' Content-type ', ' text/html ')]) #根据url的不同, return different strings #1 get the Url[url from where? Execute Runse when the request comes in Rver,wsgi gave us the encapsulation of these requests, which are encapsulated, environ & start_response] request_url = environ[' path_info '] #2 different corresponding #pr according to the URL int environ #这里可以通过断点来查看它都封装了What data #循环这个列表 for the URL in url_list: #如果用户请求的url和咱们定义的rul匹配 if Request_url = = url[0]: print ur L return url[1] () #执行里面的方法 else: #url_list列表里都没有返回404 return ' 404 ' if __name__ = = ' _    _main__ ': httpd = Make_server (', 8000, runserver) print "Serving HTTP on port 8000 ..." Httpd.serve_forever ()

Following the grammar rules of JINJA2, it will replace the specified syntax, so as to achieve the dynamic return content, for the nature of the template engine, refer to Mr. Wu Sir a blog: The vernacular tornado the source of the faded template coat of the foreplay

Reference article:

Http://www.cnblogs.com/luotianshuai/p/5258572.html

Http://www.cnblogs.com/wupeiqi/articles/5237672.html

Python Learning Path Web framework

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.