Python----web Framework

Source: Internet
Author: User

Web Framework Nature

1, 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-*-#-author-lian import Socket def handle_request (client):    buf = client.recv (1024x768)    Client.send ("http/1.1 ok\r\n\r\n". Encode ("Utf-8"))    client.send ("Hello, Seven". Encode ("Utf-8") 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 ()

Execute the above program, directly with the browser access to Http://127.0.0.1:8000/can display the information sent

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 web apps and Web applications written in Python interface format between servers, enabling decoupling between Web apps and Web servers

2. The standalone WSGI server provided by the Python standard library is called Wsgiref

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

Less code for web interaction

Convert string to byte form:

1.b ' FFFF ' 2.bytes (' ffff ', encoding= ' UTF8 ') 3. ' FFFF '. Encoding (' Utf-8 ')
Customizing the web Framework

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

From wsgiref.simple_server import Make_server def handel_index ():    return [' 

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>    <form>        <inputtype= "text" />        <inputtype= "text" />        <inputtype= "Submit" />    </form></Body></HTML>data.html
data.html
<!DOCTYPE HTML><HTML><HeadLang= "en">    <MetaCharSet= "UTF-8">    <title></title></Head><Body>    <H1>Index</H1></Body></HTML>index.html
index.html
from wsgiref.simple_server import make_server def handel_index (): F = open (' Ind Ex.html ', ' RB ') data = F.read () return [data,] # return [' 

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?

3. Return dynamic page data

    • Customize a special set of syntax to replace
    • Use the Open Source Tool JINJA2 to follow its specified syntax
#!/usr/bin/env python#-*-coding:utf-8-*-#-author-lian from wsgiref.simple_server import make_server def handel_index ( ): F = open (' index.html ', ' RB ') data = F.read () data = Data.replace (b ' index ', "Cheng Ronghua eats Bones". Encode ("Utf-8") return [ Data,] # return [' 

4. Web Framework

The actual structure of the folder is differentiated.

MVC    Model View Controller    Database template file Business processing MTV    Model template view    database template file Business processing

After the example is modified to the MVC framework,

#!/usr/bin/env python#-*-coding:utf-8-*-#__author__ = "Life"#Email: [Email protected]#DATE:2017/5/28defHandle_index ():ImportTime v=Str (time.time ()) F= Open ('view/index.html', mode='RB') Data=F.read () f.close () data= Data.replace (b'@uuuuu', V.encode ('Utf-8'))    return[Data,]defhandle_date ():return[''. Encode ('Utf-8'),]dict={'a'}
account.py
#!/usr/bin/env python#-*-coding:utf-8-*-#__author__ = "Life"#Email: [Email protected]#DATE:2017/5/28 fromWsgiref.simple_serverImportMake_server fromControllerImportaccounturl_dict={"/index": Account.handle_index,"/date": Account.handle_date}defrunserver (environ, start_response):#environ all data sent by the customer    #Start_response Package The data to be returned to the user, response header status codeStart_response ('OK', [('Content-type','text/html')]) Current_url= environ['Path_info'] Func=NoneifCurrent_urlinchUrl_dict:func=Url_dict[current_url]iffunc:returnfunc ()Else:        return[''. Encode ('Utf-8'), ]    #What's returned    #return [' if __name__=='__main__': httpd= Make_server ("', 8000, Runserver)Print('Server HTTP on port 8000 ...') Httpd.serve_forever ()
s3.py
<! DOCTYPE html>"en">" UTF-8 ">    <title>Title</title>
index.html

Django for MTV type Web framework

 

  

 

 

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.