Web Frame Foreplay---The nature of web framework

Source: Internet
Author: User

Web Framework Nature

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 (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)     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.

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.

From Wsgiref.simple_server import make_serverdef runserver (environ, start_response):    start_response (' OK ', [(' Content-type ', ' text/html ')]    return [bytes (' 
Customizing the web Framework

First, the 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_serverdef index ():    return ' index ' def Login ():    return ' login ' def routers ():        urlpatterns = (        ('/index/', index),        ('/login/', login),    )        return urlpatternsdef 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_serverdef index (): # return ' index ' F = open (' index.html ') data = F.read () return datadef login (): # R Eturn ' login ' F = open (' login.html ') data = F.read () return datadef routers (): Urlpatterns = (('/index /', index), ('/login/', login),) return urlpatternsdef run_server (environ, start_response): start_respons E (' K OK ', [(' Content-type ', ' text/html ')]) url = environ[' path_info '] urlpatterns = routers () func = None fo R 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>
index.html
#!/usr/bin/env python#-*-coding:utf-8-*-from wsgiref.simple_server import make_serverfrom jinja2 import Templatedef in    Dex (): # 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 (): # RET Urn ' login ' f = open (' login.html ') data = F.read () return datadef routers (): Urlpatterns = (('/index/' , index), ('/login/', login), return urlpatternsdef 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 ()

Following the syntax rules of JINJA2, the syntax is replaced internally to achieve dynamic return content, and for the nature of the template engine, refer to another blog: http://www.cnblogs.com/wupeiqi/p/4592637.html

Web Frame Foreplay---The nature of web framework

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.