Python automated Transport Koriyuki 26, Django series-web Framework Essence

Source: Internet
Author: User

First, the nature of web framework

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

#!/usr/bin/env python#coding:utf-8  Import Socket  def handle_request (client):    buf = CLIENT.RECV (1024)    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)      while True:        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.

Second, Wsgi

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. When there are other interface formats:

'CGI': Cgiserver,'Flup': Flupfcgiserver,'Wsgiref': Wsgirefserver,'Waitress': Waitressserver,'CherryPy': Cherrypyserver,'Paste': Pasteserver,'FAPWS3': Fapwsserver,'Tornado': Tornadoserver,'Gae': Appengineserver,'Twisted': Twistedserver,'Diesel': Dieselserver,'Meinheld': Meinheldserver,'Gunicorn': Gunicornserver,'Eventlet': Eventletserver,'gevent': Geventserver,'Geventsocketio': Geventsocketioserver,'Rocket': Rocketserver,'Bjoern': Bjoernserver,'Auto': Autoserver,

Django-Implemented Wsgiref:

#!/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 ' 
III. Customizing the web framework

1. Framework

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_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 (' 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 ()

2. Template engine

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:

<!DOCTYPE HTML><HTML><HeadLang= "en">    <MetaCharSet= "UTF-8">    <title></title></Head><Body>    <H1>Index</H1></Body></HTML>
index.html
<!DOCTYPE HTML><HTML><HeadLang= "en">    <MetaCharSet= "UTF-8">    <title></title></Head><Body>    <form>        <inputtype= "text" />        <inputtype= "text" />        <inputtype= "Submit" />    </form></Body></HTML>
login.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 (' 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 ()

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
<!DOCTYPE HTML><HTML><HeadLang= "en">    <MetaCharSet= "UTF-8">    <title></title></Head><Body>    <H1>{{Name}}</H1>    <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_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 Data def routers (): Urlpatterns = (('/I ndex/', index), ('/login/', login), return urlpatterns def run_server (environ, start_response): Start_ Response (' K OK ', [(' Content-type ', ' text/html ')]) url = environ[' path_info '] urlpatterns = routers () func = Non E for item in urlpatterns:if item[0] = = Url:func = item[1] break if Func:retu RN 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 grammar rules of JINJA2, the interior will replace the specified syntax to achieve dynamic return content, for the nature of the template engine, reference: The vernacular tornado the source of the faded template coat foreplay

Python automated Transport Koriyuki 26, Django series-web Framework Essence

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.