Django: routing and view

label DjangoPythonWeb Frameworkframeengineer
231 people read comment(0) Collection report

brief introduction

Django framework is the United States Company World (World Co? NB) engineer Adrian holovaty and Simon Willison in (,, the company running the news website development process, gradually improve the rich and, in 2005 revenue, is by far the python world fame, one of the largest web framework.

Django comes from the word Gypsy, D is not pronounced, Chinese usually turn to Jiang Ge, but there are also people quite funny called strong brother. Official pronunciation point here:

Django framework named in the twentieth Century thirty's France's famous jazz guitarist Reinhardt Django - one of the greatest guitarist to date, even though he has only three fingers on his left hand:


Stability: Django framework is quite resistant to build, has been widely adopted by Disqus, Instagram, Pinterest, Mozilla and other agencies, the official statement is based on the Django station, you can support 50 thousand times per second click access.

Product positioning: the positioning of the Django framework is to support the development of large and medium-sized dynamic web sites, providing a complete set of extensions and tools. However, the whole framework of the decomposition is relatively clear, if you are willing to put aside the Django tool, to go deep into each component, you will find that the application of Django to a variety of sizes, can be quite good support.

Django and WSGI

According to the usual practice in Python, Django is not a complete web back-end framework, it is only responsible for WSGI application development, in the production environment in your Django application should be with a WSGI server supporting, by a WSGI server is responsible for network communication.

WSGI, full name Server Gateway Interface Web, or Web Server Gateway Interface Python, is a simple and universal interface between Web server and Web application defined by Python language.


WSGI divides the Web service into two parts: the server and the application. The WGSI server is only responsible for two things related to the network: receiving the browser's HTTP request, sending the HTTP response to the browser; and the specific processing logic of the HTTP request, then by calling the WSGI application.

Implementation of a WSGI application, only to meet the 3 requirements:

Is a function that can be called, for example, a function, or a class that can be called.CallMethod) example
WSGI application should return a value that can be iterated (Iterable), such as a string list
Before returning the WSGI application, the WSGI server should call the start_response function to send the status code and the HTTP message header.
Minimum WSGI application

One of the simplest applications that meet the WSGI protocol requires a specified form of function:

Wsgiref.simple_server import make_server from

Wsgi_app def (environ, start_response):
Start_response (OK''200, [('Context-Type','text/plain')])
'such a tiny WSGI app return! '

Httpd = make_server ('', 80, wsgi_app)
Httpd.serve_forever ()

Environ is a HTTP request contains all the information dictionary /Dict, generate the request by the WSGI server HTTP unpack.

Create WSGI application objects

Django framework for a WSGI application of the structure of the decomposition, some parts by the framework to complete, some parts need to be implemented by the developer. Therefore, the development of a Django based framework for Web applications, in fact, is the need to fill the Django framework agreed by the developer to complete the parts.

According to the Django convention, the core component of a WSGI application has two: routing tables and views. The core function of the Django framework is the routing: according to the URL request in the HTTP, find the routing table, the HTTP request distribution to a different view to deal with:


It should be noted that, in the Django framework, since the application (application) has a specific meaning, we will use the Django project to represent the WSGI application object in the Django framework.

Creating a WSGI application object is very simple, which is done by calling the get_wsgi_application () function. This object is used to dock with the WSGI server:

Django.core.wsgi import get_wsgi_application from
Wsgi_app = get_wsgi_application ()

Global configuration object

But has a point to be noted, the Django framework relies heavily on to a global object configuration settings to customize its behavior. Therefore, we need to before creates WSGI application objects, the first to use the default initialization the global configuration object:

Django.conf import settings from
Settings.configure ()

In the sample code you see, we set its DEBUG property to True, which will enable the Django framework to run in the debug state, output debugging information.

Write view function

DJango in the view is a standard Python function, but because the Django framework to call this function, so the function as a view of the two agreed to meet:


Input: the first argument is a HttpRequest object, which is a complete package of the Django framework for a HTTP request, and the view function extracts the information from the object.

Output: the return value should be a HttpResponse object, the Django framework will complete the response to the WSGI server based on the returned object.

A simple view function looks like this:

V_index def (req):
HttpResponse return ('Hello, World! ')

View function is usually called by the framework, we do not need to call the view function directly. But this is not prohibited, and sometimes (such as automatic testing) is also useful. A HttpRequest object is constructed in the framework of the imitation, which is passed to the view function:

Req = HttpRequest ()
V_index print (req)

Define routing table

Django framework according to the HTTP request URL to find the corresponding view function, it is natural, the routing table to use a list of objects, each of which records a URL model and a view of the corresponding relationship:

Urlpatterns = [
URL (r'^$', v_index),
URL (r'^about/$', v_about),

URL () function is used to generate a route, the first argument is a regular expression, used to match the URL of the HTTP request, R prefix is used to prevent escape regular string; the second parameter is we define the view function.

If you are familiar with regular expressions, there may be a little doubt about why the above regular expression does not contain the previous one. For example, if the user requests the URL is /about/, then our regular expression should be written in ^/about/$is right?

Well, so, simply, it's the Django framework that ate the prefix before using the routing table you've defined... Before this, back on this point.

Registered routing table

In a point of scale application, there may be a number of development groups, each development group to maintain a separate routing table. Therefore, in the Django framework, it is required to tell the Django framework to use the routing table as the root routing table.

Use global configuration object root urlconf attribute to register root routing table and shall specify a with variable urlpatterns module name, Django will dynamic import this module and use the urlpatterns variable values as a routing table for this attribute.

Therefore, in general, the routing table variable should be named as urlpatterns.

Docking WSGI server

Strictly speaking, until the last lesson, a Django project was developed, and the rest is deployed to the production environment to go.


In the production environment, you can dock the production level of the WSGI server, such as: Apache + Gunicorn, mod_wsgi or wWSGI. But we still skip this link, the development phase, first to find a simple WSGI server to run up!

Using Python built-in simple WSGI server, the introduction, the creation of the server, run:

Wsgiref.simple_server import make_server from
Httpd = make_server ('', 80, wsgi_app)
Httpd.serve_forever ()

More content such as URL distribution, URL reverse resolution, view function, request and response, middleware, etc., as well as the practice of this paper, please refer to:

step on
Guess you're looking for
View comments
* the above user comments only represent their personal views, does not represent the views or position of the CSDN website
    personal data
    • visit4464 times
    • Integral:Two hundred and eleven
    • Grade
    • Rank:Thousands of miles away
    • original16
    • Reproduced:0
    • Translation:0
    • Comments:1
    Classification of articles
    Latest comments