Python ==> Django Framework

Source: Internet
Author: User
Tags response code

Python's Django framework

The content of this section

1.web Frame

2.MVC and MTV Mode

3.

1.web Frame

Framework, which is specifically designed to solve an open problem with a certain binding support structure, the use of the framework can help you to quickly develop a specific system, in short, you use other people set up the stage to do the performance.

The flow of Web apps:

The browser sends an HTTP request,//the server receives the request, generates an HTML document,//The server sends the HTML document as the body of the HTTP response to the browser;//The browser receives an HTTP response and takes the HTML document out of the HTTP body and displays it.

For all Web applications, essentially a socket server, the user's browser is actually a socket client.

Import socketdef handle_request (client):    buf = Client.recv (1024x768)    client.send ("http/1.1-ok\r\n\r\n". Encode ("UTF8"))    client.send ("

The simplest Web application is to first save the HTML file, with a ready-made HTTP Server software, to receive user requests, from the file to read HTML, return.
If you want to generate HTML dynamically, you need to implement the above steps yourself. However, accepting HTTP requests, parsing HTTP requests, and sending HTTP responses are all menial jobs, and if we're writing these underlying code ourselves, it's going to take months to read the HTTP specification before we start writing Dynamic HTML.

The correct approach is that the underlying code is implemented by specialized server software, and we use Python to focus on generating HTML documents. Because we don't want to be exposed to TCP connections, HTTP RAW requests, and response formats, we need a unified interface that lets us focus on writing Web services in Python.

This interface is the Wsgi:web Server Gateway Interface.

Implement a simple web framework  

One

From Wsgiref.simple_server import make_server def application (environ, start_response): Start_response (' OK ', [(' Co Ntent-type ', ' text/html ')]) return [b ' 

Attention:

The entire application () function itself does not involve any part of parsing HTTP, that is, the underlying code does not need to be written by us, we are only responsible for considering how to respond to the request at a higher level. The application () function must be called by the WSGI server. There are many servers that conform to the WSGI specification, and we can pick one to use. Python has a built-in Wsgi server called the Wsgirefapplication () function, which is an HTTP handler that conforms to the WSGI standard, and it receives two parameters:        // Environ: A Dict object that contains all the HTTP request information;        //start_response: A function that sends an HTTP response. In the application () function, the call: Start_response (' OK ', [(' Content-type ', ' text/html ')]) sends the header of the HTTP response, noting that the header can only be sent once, That is, the start_response () function can only be called once. The Start_response () function receives two parameters, one is an HTTP response code, one is a list of HTTP headers, and each header is represented by a tuple containing two str. Usually, content-type hair should be sent to the browser. Many other commonly used HTTP headers should also be sent. Then, the function returns the value B ' 

Both:  

Print (environ[' path_info ') path=environ[' Path_info '] start_response (' OK ', [(' Content-type ', ' text/html ')] F        1=open ("index1.html", "RB") Data1=f1.read () F2=open ("index2.html", "RB") Data2=f2.read () if path== "/yuan": return [data1] elif path== "/alex": return [data2] else:return ["

Three:  

From Wsgiref.simple_server import Make_server def F1 ():     f1=open ("index1.html", "RB")     data1=f1.read ()     return [data1] def F2 ():     f2=open ("index2.html", "RB")     data2=f2.read ()     return [data2]  def application (environ, start_response):      print (environ[' PATH_INFO '))      path=environ[' Path_info ']    start_response (' K OK ', [' Content-Type ', ' Text/html ')]       if path== "/yuan":         return F1 ()      elif path== "/alex":         return F2 ()      else:        return [" 

Four:  

From Wsgiref.simple_server import Make_server  def F1 (req):     print (req)      print (req["query_string")      f1=open ("index1.html", "RB")      data1=f1.read ()     return [data1] def F2 (req):      f2=open ("index2.html", "RB")     data2=f2.read ()     return [ Data2] import time def f3 (req):        #模版以及数据库       f3=open ("index3.html", "RB")     data3=f3.read ()     times= Time.strftime ("%y-%m-%d%x", Time.localtime ())     data3=str (data3, "UTF8"). Replace ("!time!", STR (times))       return [Data3.encode ("UTF8")]  def routers ():      urlpatterns = (         ('/yuan ', F1),          ('/alex ', F2),         ("/cur_time", F3)      )     return urlpatterns  def application (environ, start_response):      print (environ[' path_info ')     path=environ[' PATH_INFO ']     start_response (' K OK ', [(' Content-type ', ' text/html ')])        urlpatterns = routers ()     func = none    for item in Urlpatterns:         if item[0] = = path:             func = item[1]             break    if func:        return func (environ)     else:        return ["

2.MVC and MTV mode  

The famous MVC pattern: the so-called MVC is to divide Web applications into models (M), controllers (C), view (V) Three layers, and they are connected together in a plug-in, loosely coupled way.
The model is responsible for the business object with the database object (ORM), the view is responsible for interacting with the user (page), the controller (C) accepts the user's input call model and the view completes the user's request.

The Django MTV model is essentially no different from the MVC pattern, and it's just a little different from the definition of each component in order to remain loosely coupled, as Django's MTV represents:

    • Model: Object that is responsible for business objects and databases (ORM)
    • Template (Template): Responsible for how to display the page to the user
    • View: Responsible for business logic, and call model and template when appropriate

In addition, Django has a URL dispatcher that distributes page requests for URLs to different view processes, and then calls the corresponding model and template

  

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