Python Web framework

Source: Internet
Author: User

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

A simple socket code that can be accessed by a browser:

#!/usr/bin/env python#coding:utf-8  import socket   def handle_request (client):     buf = client.recv (1024x768)      client.send ("http/1.1 200 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)        while true:        connection,  address = sock.accept ()         handle_request ( Connection)         connection.close ()   if __name__  ==  ' __main__ ':     main () 

Demo Effect:

650) this.width=650; "Src=" Http://s4.51cto.com/wyfs02/M01/85/29/wKiom1ebJcDxoQKlAABuPb54ve4673.png-wh_500x0-wm_3 -wmp_4-s_1691883077.png "title=" qq picture 20160729174502.png "alt=" Wkiom1ebjcdxoqklaabupb54ve4673.png-wh_50 "/>

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.

Case code:

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


Develop your own web framework case code with the Wsgiref module provided by the Python standard library:

#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server import make_server def  index ():    return  ' index '  def login ():     return   ' login '  def routers ():          urlpatterns =   (         ('/index/', index),          ('/login/', login),               Return urlpatterns def runserver (environ, start_response):     start_ Response (' 200 ok ',  [(' Content-type ',  ' text/html ')])     url =  environ[' Path_info ']    urlpatterns = routers ()     func  = None    for item in urlpatterns:         if  item[0] == url:            func =  item[1]            break     if func:        return func ()      else:        return  ' 404 not found '       if __name__ ==  ' __main__ ':     httpd = make_server (',  8000, runserver)     print  "serving http on port  8000 ... "    httpd.serve_forever ()

Demo Effect:

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M02/85/29/wKioL1ebJr-RFb6iAABsWBLk4aM907.png-wh_500x0-wm_3 -wmp_4-s_1934111975.png "title=" qq picture 20160729174904.png "alt=" Wkiol1ebjr-rfb6iaabswblk4am907.png-wh_50 "/>

650) this.width=650; "Src=" Http://s4.51cto.com/wyfs02/M00/85/29/wKiom1ebJuLwVt0SAAB6cRglm7o525.png-wh_500x0-wm_3 -wmp_4-s_1611184318.png "title=" qq picture 20160729175003.png "alt=" Wkiom1ebjulwvt0saab6crglm7o525.png-wh_50 "/>

650) this.width=650; "Src=" Http://s2.51cto.com/wyfs02/M00/85/29/wKioL1ebJweAkhSJAABxz_zJgpw576.png-wh_500x0-wm_3 -wmp_4-s_2718809240.png "title=" qq picture 20160729175037.png "alt=" Wkiol1ebjweakhsjaabxz_zjgpw576.png-wh_50 "/>


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

Case code:

Index.html

<! DOCTYPE html>

Logun.html

<! Doctype html>
#!/usr/bin/env python# -*- coding:utf-8 -*- from wsgiref.simple_server  Import make_server  def index ():    # return  ' index '      f = open (' index.html ')     data = f.read ()      return data  def login ():    # return  ' Login '     f = open (' login.html ')     data = f.read ( )     return data  def routers ():      urlpatterns =  (         ('/index/',  index),          ('/login/',  login),    )       return urlpatterns  def run_server (Environ, start_response):     start_response (' 200 ok ', [(' Content-type ',  ' text/html ')]     url = environ[' PATH_INFO ']     urlpatterns = routers ()     func = None     for item in urlpatterns:        if  item[0] == url:            func =  item[1]            break     if func:        return func ()      else:        return  ' 404 not found '   if  __name__ ==  ' __main__ ':     httpd = make_server (',  8000, run _server)     print  "serving http on port 8000 ..."     httpd.serve_foRever () 

Demo Effect:

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M02/85/29/wKioL1ebJ_yB43BsAAByBXy6gQY622.png-wh_500x0-wm_3 -wmp_4-s_3252504646.png "style=" Float:none; "title=" QQ picture 20160729175432.png "alt=" wkiol1ebj_ Yb43bsaabybxy6gqy622.png-wh_50 "/>

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M00/85/29/wKiom1ebJ_zikaIgAAB1DZgqm64244.png-wh_500x0-wm_3 -wmp_4-s_4256527656.png "style=" Float:none; "title=" QQ picture 20160729175418.png "alt=" wkiom1ebj_ Zikaigaab1dzgqm64244.png-wh_50 "/>


The above code, although can be returned to the user HTML content to a realistic complex page, but there are still problems: How do I return dynamic content to a user?

    • Customize a special set of syntax to replace

    • Use the Open Source Tool JINJA2 to follow its specified syntax

Index.html

<! Doctype html>
#!/usr/bin/env python# -*- coding:utf-8 -*- from wsgiref.simple_server  Import make_serverfrom jinja2 import template  def index ():     # return  ' index '      # template = template (' hello {{ name }}! ')     # result = template.render (name= ' John doe ')       f = open (' index.html ')     result = f.read ()      template = template (Result)     data = template.render (name = ' John doe ',  user_list=[' Alex ',  ' Eric ')     return data.encode (' Utf-8 ') )   def login ():    # return  ' login '     f  = open (' login.html ')     data = f.read ()     return &Nbsp;data  def routers ():     urlpatterns =  (          ('/index/',  index),         (' /login/',  login),    )      return urlpatterns   def run_server (Environ, start_response):     start_response (' 200 OK ',  [(' Content-type ',  ' text/html ')]     url = environ[' PATH_INFO ']     urlpatterns = routers ()     func = None     for item in urlpatterns:        if  item[0] == url:            func =  item[1]            break     if func: &nbSp;      return func ()     else:         return  ' 404 not found '   if __name__ ==  ' __main __ ':     httpd = make_server (',  8000, run_server)      print  "serving http on port 8000 ..."     httpd.serve_forever ()

Following the syntax rules of JINJA2, the syntax is replaced internally to achieve dynamic return content, for the nature of the template engine

Demo Effect:

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M00/85/29/wKioL1ebKO-CIkLBAACCOE3GGB4878.png-wh_500x0-wm_3 -wmp_4-s_3583551852.png "title=" qq picture 20160729175846.png "alt=" Wkiol1ebko-ciklbaaccoe3ggb4878.png-wh_50 "/>

Python 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.