The Django Book

Chapter 3: The Basics of Dynamic Web Pages

第三章:动态网页基础

In the previous chapter, we explained how to set up a Django project and run the Django development server. Of course, that site doesnt actually do anything useful yetall it does is display the It worked! message. Lets change that. This chapter introduces how to create dynamic Web pages with Django.

前一章中,我们解释了如何建立一个 Django 项目并启动 Django 开发服务器。当然,那个网站实际并没有干什么有用的事情,它所做的只是显示 It worked! 消息。让我们来做些改变。本章将介绍如何使用 Django 创建动态网页。

Your First View: Dynamic Content

第一份视图:动态内容

As our first goal, lets create a Web page that displays the current date and time. This is a good example of a dynamic Web page, because the contents of the page are not staticrather, the contents change according to the result of a computation (in this case, a calculation of the current time). This simple example doesnt involve a database or any sort of user inputjust the output of your servers internal clock.

我们的第一个目标是创建一个显示当前日期和时间的网页。这是一个不错的 动态 网页范例,因为该页面的内容不是静态的。相反,其内容是随着计算(本例中是对当前时间的计算)的结果而变化的。这个简单的范例既不涉及数据库,也不需要任何用户输入,仅输出服务器的内部时钟。

To create this page, well write a view function . A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image or anything, really. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere you want, as long as its on your Python path. Theres no other requirementno magic, so to speak. For the sake of putting the code somewhere , lets create a file called views.py in the mysite directory, which you created in the previous chapter.

我们将编写一个 视图函数 以创建该页面。所谓的视图函数(或 视图 ),只不过是一个接受 Web 请求并返回 Web 响应的 Python 函数。实际上,该响应可以是一份网页的 HTML 内容、一次重定向、一条 404 错误、一份 XML 文档、一幅图片,或其它任何东西。视图本身包含返回该响应所需的任意逻辑。该段代码可以随意放置,只要在 Python 的路径设置中就可以了。没有其它要求——也可以说是没有任何奇特之处。为了给这些代码一个 存身之处 ,让我们在上一章所创建的 mysite 目录中新建一份名为 views.py 的文件。

Heres a view that returns the current date and time, as an HTML document:

以下是一个以 HTML 方式返回当前的日期与时间的视图 (view),:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

Lets step through this code one line at a time:

我们逐行逐句地分析一遍这段代码:

First, we import the class HttpResponse , which lives in the django.http module. See Appendix H for further details on the HttpRequest and HttpResponse objects.

首先,我们从 django.http 模块导入(import) HttpResponse 类。参阅附录 H 了解更多关于 HttpRequestHttpResponse 的细节。

Then we import the datetime module from Pythons standard library, the set of useful modules that comes with Python. The datetime module contains several functions and classes for dealing with dates and times, including a function that returns the current time.

然后我们从 Python 标准库(Python 自带的实用模块集合)中导入(import) datetime 模块。 datetime 模块包含几个处理日期和时间的函数(functions)和类(classes),其中就包括返回当前时间的函数。

Next, we define a function called current_datetime . This is the view function. Each view function takes an HttpRequest object as its first parameter, which is typically named request .

接下来,我们定义了一个叫做 current_datetime 的函数。这就是所谓的视图函数(view function)。每个视图函数都以一个 HttpRequest 对象为第一个参数,该参数通常命名为 request

Note that the name of the view function doesnt matter; it doesnt have to be named in a certain way in order for Django to recognize it. Were calling it current_datetime here, because that name clearly indicates what it does, but it could just as well be named super_duper_awesome_current_time , or something equally revolting. Django doesnt care. The next section explains how Django finds this function.

注意视图函数的名称并不重要;并不一定非得以某种特定的方式命名才能让 Django 识别它。此处,我们称之为 current_datetime ,只是因为该名字明确地指出了它的功能,而它也可以被命名为 super_duper_awesome_current_time 或者其它同样莫名其妙的名字。Django 并不关心其名字。下一节将解释 Django 如何查找该函数。

The first line of code within the function calculates the current date/time, as a datetime.datetime object, and stores that as the local variable now .

函数中的第一行代码计算当前日期和时间,并以 datetime.datetime 对象的形式保存为局部变量 now

The second line of code within the function constructs an HTML response using Pythons format-string capability. The %s within the string is a placeholder, and the percent sign after the string means Replace the %s with the value of the variable now . (Yes, the HTML is invalid, but were trying to keep the example simple and short.)

函数的第二行代码用 Python 的格式化字符串(format-string)功能构造了一段 HTML 响应。字符串里面的 %s 是占位符,字符串之后的百分号表示使用变量 now 的值替换 %s 。(是的,这段 HTML 不合法,但我们只不过是想让范例尽量保持简短而已。)

Finally, the view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object. (There are exceptions, but well get to those later.)

最后,该视图返回一个包含所生成响应的 HttpResponse 对象。每个视图函数都负责返回一个 HttpResponse 对象。(也有例外,但是我们稍后才会接触到。)

Djangos Time Zone

Django 时区 (Time Zone)

Django includes a TIME_ZONE setting that defaults to America/Chicago . This probably isnt where you live, so you might want to change it in your settings.py . See Appendix E for details.

Django 包含一个默认为 America/ChicagoTIME_ZONE 设置。这可能不是你所居住的时区,因此你可以在 settings.py 文件中修改它。请参阅附录 E 了解更多细节。

Mapping URLs to Views

将 URL 映射到视图

So, to recap, this view function returns an HTML page that includes the current date and time. But how do we tell Django to use this code? Thats where URLconfs come in.

那么概括起来,该视图函数返回了包含当前日期和时间的一段 HTML 页面。但是如何告诉 Django 使用这段代码呢?这就是 URLconfs 登场的地方了。

A URLconf is like a table of contents for your Django-powered Web site. Basically, its a mapping between URL patterns and the view functions that should be called for those URL patterns. Its how you tell Django, For this URL, call this code, and for that URL, call that code. Remember that the view functions need to be on the Python path.

URLconf 就像是 Django 所支撑网站的目录。它的本质是 URL 模式以及要为该 URL 模式调用的视图函数之间的映射表。你就是以这种方式告诉 Django,对于这个 URL 调用这段代码,对于那个 URL 调用那段代码。但必须记住的是视图函数必须位于 Python 搜索路径之中。

Your Python Path

Python 搜索路径

Your Python path is the list of directories on your system where Python looks when you use the Python import statement.

Python 搜索路径 就是使用 import 语句时,Python 所查找的系统目录清单。

For example, lets say your Python path is set to ['', '/usr/lib/python2.4/site-packages', '/home/username/djcode/'] . If you execute the Python code from foo import bar , Python will first check for a module called foo.py in the current directory. (The first entry in the Python path, an empty string, means the current directory.) If that file doesnt exist, Python will look for the file /usr/lib/python2.4/site-packages/foo.py . If that file doesnt exist, it will try /home/username/djcode/foo.py . Finally, if that file doesnt exist, it will raise ImportError .

举例来说,假定你将 Python 路径设置为 ['','/usr/lib/python2.4/site-packages','/home/username/djcode/'] 。如果执行代码 from foo import bar ,Python 将会首先在当前目录查找 foo.py 模块( Python 路径第一项的空字符串表示当前目录)。如果文件不存在,Python将查找 /usr/lib/python2.4/site-packages/foo.py 文件。如果文件也不存在,它将尝试 /home/username/djcode/foo.py 。最后,如果 这个 文件还不存在,它将引发 ImportError 异常。

If youre interested in seeing the value of your Python path, start the Python interactive interpreter and type import sys , followed by print sys.path .

如果对了解 Python 搜索路径值感兴趣,可以启动 Python 交互式解释程序,输入 import sys ,接着输入 print sys.path

Generally you dont have to worry about setting your Python pathPython and Django will take care of things for you automatically behind the scenes. (If youre curious, setting the Python path is one of the things that the manage.py file does.)

通常,你不必关心 Python 搜索路径的设置。Python 和 Django 会在后台自动帮你处理好。(如果有兴趣了解的话,Python 搜索路径的设置工作是 manage.py 文件的职能之一。)

When you executed django-admin.py startproject in the previous chapter, the script created a URLconf for you automatically: the file urls.py . Lets edit that file. By default, it looks something like this:

前一章中执行 django-admin.py startproject 时,该脚本会自动为你建了一份 URLconf(即 urls.py 文件)。让我们编辑一下这份文件。預設情况下它是下面这个样子:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    # Example:
    # (r'^mysite/', include('mysite.apps.foo.urls.foo')),

    # Uncomment this for admin:
#     (r'^admin/', include('django.contrib.admin.urls')),
)

Lets step through this code one line at a time:

让我们逐行逐句分析一遍这段代码:

  • The first line imports all objects from the django.conf.urls.defaults module, including a function called patterns .

  • 第一行从 django.conf.urls.defaults 模块引入了所有的对象,其中包括了叫做 patterns 的函数。

  • The second line calls the function patterns() and saves the result into a variable called urlpatterns . The patterns() function gets passed only a single argumentthe empty string. The rest of the lines are commented out. (The string can be used to supply a common prefix for view functions, but well skip this advanced usage for now.)

  • 第二行调用 patterns() 函数并将返回结果保存到 urlpatterns 变量。 patterns() 函数只传入了一个空字符串参数。其他代码行都被注释掉了。 (该字符串可用作视图函数的通用前缀,但目前我们将略过这种高级用法。)

The main thing to note here is the variable urlpatterns , which Django expects to find in your ROOT_URLCONF module. This variable defines the mapping between URLs and the code that handles those URLs.

当前应该注意是 urlpatterns 变量, Django 期望能从 ROOT_URLCONF 模块中找到它。该变量定义了 URL 以及用于处理这些 URL 的代码之间的映射关系。

By default, everything in the URLconf is commented outyour Django application is a blank slate. (As a side note, thats how Django knew to show you the It worked! page in the last chapter. If your URLconf is empty, Django assumes you just started a new project and, hence, displays that message.)

默认情况下,URLconf 所有内容都被注释起来了——Django 应用程序还是白版一块。(旁注:这也就是上一章中 Django 显示“It worked!”页面的原因。如果 URLconf 为空,Django 会认定你才创建好新项目,因此也就显示那种信息。)

Lets edit this file to expose our current_datetime view:

现在编辑该文件用来展示我们的 current_datetime 视图:

from django.conf.urls.defaults import *
from mysite.views import current_datetime

urlpatterns = patterns('',
    (r'^time/$', current_datetime),
)

We made two changes here. First, we imported the current_datetime view from its module (mysite/views.py , which translates into mysite.views in Python import syntax). Next, we added the line (r'^time/$', current_datetime), . This line is referred to as a URLpattern its a Python tuple in which the first element is a simple regular expression and the second element is the view function to use for that pattern.

我们做了两处修改。首先,我们从模块 (在 Python 的 import 语法中, mysite/views.py 转译为 mysite.views ) 中引入了 current_datetime 视图。接着,我们加入了 (r'^time/$', current_datetime), 这一行。该行就是所谓的 URLpattern ,它是一个 Python 元组,其第一个元素是简单的正则表达式,第二个元素是为该模式应用的视图函数。

In a nutshell, we just told Django that any request to the URL /time/ should be handled by the current_datetime view function.

简单来说,我们只是告诉 Django,所有指向 URL /time/ 的请求都应由 current_datetime 这个视图函数来处理。

A few things are worth pointing out:

下面是一些需要注意的地方:

Note that, in this example, we passed the current_datetime view function as an object without calling the function. This is a key feature of Python (and other dynamic languages): functions are first-class objects, which means you can pass them around just like any other variables. Cool stuff, eh?

注意,该例中,我们将 current_datetime 视图函数作为对象传递,而不是调用它。这是 Python (及其它动态语言的) 的一个重要特性:函数是一级对象(first-class objects), 也就是说你可以像传递其它变量一样传递它们。很酷吧?

The r in r'^time/$' means that '^time/$ is a Python raw string. This allows regular expressions to be written without overly verbose escaping.

r'^time/$' 中的 r 表示 '^time/$' 是一个原始字符串。这样一来就可以避免

System Message: WARNING/2 (<string>, line 504)

Block quote ends without a blank line; unexpected unindent.

正则表达式有过多的转义字符。

You should exclude the expected slash at the beginning of the '^time/$' expression in order to match /time/ . Django automatically puts a slash before every expression. At first glance, this may seem odd, but URLconfs can be included in other URLconfs, and leaving off the leading slash simplifies matters. This is further covered in Chapter 8.

不必在 '^time/$' 前加斜杠(/)来匹配 /time/ , 因为 Django 会自动在每个表 达式前添加一个斜杠。乍看起来,这好像有点奇怪,但是 URLconfs 可能由其它的 URLconfs 所引用, 所以不加前面的斜杠可让事情简单一些。这一点在第 8 章中将有进一步阐述。

The caret character (^ ) and dollar sign character ($ ) are important. The caret means require that the pattern matches the start of the string, and the dollar sign means require that the pattern matches the end of the string.

上箭头 ^ 和美元符号 $ 符号非常重要。上箭头要求表达式对字符串的头部进行匹配,美元符号则要求表达式对字符串的尾部进行匹配。

This concept is best explained by example. If we had instead used the pattern '^time/' (without a dollar sign at the end), then any URL that starts with time/ would match, such as /time/foo and /time/bar , not just /time/ . Similarly, if we had left off the initial caret character ('time/$' ), Django would match any URL that ends with time/ , such as /foo/bar/time/ . Thus, we use both the caret and dollar sign to ensure that only the URL /time/ matches. Nothing more, nothing less.

最好还是用范例来说明一下这个概念。如果我们用 '^time/' (结尾没有$), 那么以 time/ 开始的 任意 URL 都会匹配,比如 /time/foo/time/bar , 不仅仅是 /time/ 。同样的,如果我们去掉最前面的 ^ ( 'time/$' ), Django 一样会匹配由 time/ 结束的 任意 URL /time/ ,比如 /foo/bar/time/ 。 因此,我们必须同时用上 ^ 和 $ 来精确匹配 URL /time/ 。不能多也不能少。

You may be wondering what happens if someone requests /time . This is handled as youd hope (via a redirect) as long as the APPEND_SLASH setting is True . (See Appendix E for some good bedtime reading on this topic.)

你可能想如果有人请求 /time 也可以同样处理。如果 APPEND_SLASH 的 设置是 True 的话,系统会重定向到 /time/ ,这样就可以一样处理了。 (有关内容请查看附录 E )

To test our changes to the URLconf, start the Django development server, as you did in Chapter 2, by running the command python manage.py runserver . (If you left it running, thats fine, too. The development server automatically detects changes to your Python code and reloads as necessary, so you dont have to restart the server between changes.) The server is running at the address http://127.0.0.1:8000/ , so open up a Web browser and go to http://127.0.0.1:8000/time/ . You should see the output of your Django view.

启动Django开发服务器来测试修改好的 URLconf, 运行命令行 python manage.py runserver 。 (如果你让它一直运行也可以,开发服务器会自动监测代码改动并自动重新载入,所以不需要手工重启) 开发服务器的地址是 http://127.0.0.1:8000/ ,打开你的浏览器访问 http://127.0.0.1:8000/time/ 。 你就可以看到输出结果了。

Hooray! Youve made your first Django-powered Web page.

万岁!你已经创建了第一个Django的web页面。

Regular Expressions

正则表达式

Regular expressions (or regexes ) are a compact way of specifying patterns in text. While Django URLconfs allow arbitrary regexes for powerful URL-matching capability, youll probably use only a few regex patterns in practice. Heres a small selection of common patterns:

正则表达式 (或 regexes ) 是通用的文本模式匹配的方法。Django URLconfs 允许你 使用任意的正则表达式来做强有力的URL映射,不过通常你实际上可能只需要使用很少的一 部分功能。下面就是一些常用通用模式:

Symbol Matches
. (dot) Any character
\d Any digit
[A-Z] Any character, A-Z (uppercase)
[a-z] Any character, a-z (lowercase)
[A-Za-z] Any character, a-z (case insensitive)
+ One or more of the previous expression (e.g., \d+ matches one or more digit)
[^/]+ All characters except forward slash
? Zero or more of the previous expression (e.g., \d* matches zero or more digits)
{1,3} Between one and three (inclusive) of the previous expression
符号 匹配
. (dot) 任意字符
\d 任意数字
[A-Z] 任意字符, A-Z (大写)
[a-z] 任意字符, a-z (小写)
[A-Za-z] 任意字符, a-z (不区分大小写)
+ 匹配一个或更多 (例如, \d+ 匹配一个或 多个数字字符)
[^/]+ 不是/的任意字符
* 匹配0个或更多 (例如, \d* 匹配0个 或更多数字字符)
{1,3} 匹配1个到3个(包含)

For more on regular expressions, see http://www.djangoproject.com/r/python/re-module/.

有关正则表达式的更多内容,请访问 http://www.djangoproject.com/r/python/re-module/.

How Django Processes a Request

Django是怎么处理请求的

We should point out several things about what just happened. Heres the nitty-gritty of what goes on when you run the Django development server and make requests to Web pages:

我们必须对刚才所发生的几件事情进行一些说明。它们是运行Django开发服务器和构造Web页面请求的本质所在。

The command python manage.py runserver imports a file called settings.py from the same directory. This file contains all sorts of optional configuration for this particular Django instance, but one of the most important settings is ROOT_URLCONF . The ROOT_URLCONF setting tells Django which Python module should be used as the URLconf for this Web site.

命令 python manage.py runserver 从同一目录载入文件 settings.py 。 该文件包含了这个特定的Django实例所有的各种可选配置,其中一个最重要的配置就是 ROOT_URLCONFROOT_URLCONF 告诉Django哪个Python模块应该用作本网站的 URLconf。

Remember when django-admin.py startproject created the files settings.py and urls.py ? Well, the autogenerated settings.py has a ROOT_URLCONF that points to the autogenerated urls.py . Convenient.

还记得 django-admin.py startproject 创建的文件 settings.pyurls.py 吗? 这是系统自动生成的 settings.pyROOT_URLCONF 默认设置是 urls.py

When a request comes insay, a request to the URL /time/ Django loads the URLconf pointed to by the ROOT_URLCONF setting. Then it checks each of the URLpatterns in that URLconf in order, comparing the requested URL with the patterns one at a time, until it finds one that matches. When it finds one that matches, it calls the view function associated with that pattern, passing an HttpRequest object as the first parameter to the function. (More on HttpRequest later.)

当访问 URL /time/ 时,Django 根据 ROOT_URLCONF 的设置装载 URLconf 。 然后按顺序逐个匹配URLconf里的URLpatterns,直到找到一个匹配的。当找到这个匹配 的URLpatterns就调用相关联的view函数,并把 HttpRequest 对象作为第一个参数。 (稍后再给出 HttpRequest 的更多信息)

The view function is responsible for returning an HttpResponse object.

该 view 函数负责返回一个 HttpResponse 对象。

You now know the basics of how to make Django-powered pages. Its quite simple, reallyjust write view functions and map them to URLs via URLconfs. You might think it would be slow to map URLs to functions using a series of regular expressions, but youd be surprised.

你现在知道了怎么做一个 Django-powered 页面了,真的很简单,只需要写视图函数并用 URLconfs把它们和URLs对应起来。你可能会认为用一系列正则表达式将URLs映射到函数也许会比较慢,但事实却会让你惊讶。

How Django Processes a Request: Complete Details

Django如何处理一个请求:完整的细节

In addition to the straightforward URL-to-view mapping just described, Django provides quite a bit of flexibility in processing requests.

除了刚才所说到的简明URL-to-view映射方式之外,Django在请求处理方面提供了大量的灵活性。

The typical flowURLconf resolution to a view function which returns an HttpResponse can be short-circuited or augmented via middleware. The deep secrets of middleware will be fully covered in Chapter 15, but a quick sketch (see Figure 3-1) should aid you in conceptually fitting the pieces together.

通过 URLconf 解析到哪个视图函数来返回 HttpResponse 可以通过中间件(middleware) 来短路或者增强。关于中间件的细节将在第十五章详细谈论,这里给出 图3-1 让你先了解 大体概念.

The complete flow of a Django request and response. Django request 和 response 的完整流程。

Figure 3-1: The complete flow of a Django request and response.

图3-1:Django请求和回应的完整流程

When an HTTP request comes in from the browser, a server-specific handler constructs the HttpRequest passed to later components and handles the flow of the response processing.

当服务器收到一个HTTP请求以后,一个服务器特定的 handler 会创建 HttpRequest 并传递给下一个组件并处理。

The handler then calls any available Request or View middleware. These types of middleware are useful for augmenting incoming HttpRequest objects as well as providing special handling for specific types of requests. If either returns an HttpResponse , processing bypasses the view.

这个 handler 然后调用所有可用的Request或者View中间件。这些类型的中间件通常是用来 增强 HttpRequest 对象来对一些特别类型的request做些特别处理。只要其中有一个 返回 HttpResponse ,系统就跳过对视图的处理。

Bugs slip by even the best programmers, but exception middleware can help squash them. If a view function raises an exception, control passes to the Exception middleware. If this middleware does not return an HttpResponse , the exception is re-raised.

即便是最棒的程序员也会有出错的时候, 这个时候 异常处理中间件(exception middleware) 可以帮你的大忙。如果一个视图函数抛出异常,控制器会传递给异常处理中间件处理。如果这个 中间件没有返回 HttpResponse ,意味着它不能处理这个异常,这个异常将会再次抛出。

Even then, all is not lost. Django includes default views that create a friendly 404 and 500 response.

即便是这样,你也不用担心。Django包含預設的视图来生成友好的404 和 500 回应(response)。

Finally, response middleware is good for post-processing an HttpResponse just before its sent to the browser or doing cleanup of request-specific resources.

最后, response middleware 做发送 HttpResponse 给浏览器之前的后处理或者清除 请求用到的相关资源。

URLconfs and Loose Coupling

URL配置和弱配對

Nows a good time to highlight a key philosophy behind URLconfs and behind Django in general: the principle of loose coupling . Simply put, loose coupling is a software-development approach that values the importance of making pieces interchangeable. If two pieces of code are loosely coupled, then changes made to one of the pieces will have little or no effect on the other.

现在是好时机来指出Django和URL配置背后的哲学: 松耦合 原则。简单的说,松耦合是一个 重要的保证互换性的软件开发方法。如果两段代码是松耦合的,那么改动其中一段代码不会 影响另一段代码,或者只有很少的一点影响。

Djangos URLconfs are a good example of this principle in practice. In a Django Web application, the URL definitions and the view functions they call are loosely coupled; that is, the decision of what the URL should be for a given function, and the implementation of the function itself, reside in two separate places. This lets a developer switch out one piece without affecting the other.

Django的URL配置就是一个很好的例子。在Django的应用程序中,URL的定义和视图函数之间是松 耦合的,换句话说,决定URL返回哪个视图函数和实现这个视图函数是在两个不同的地方。这使得 开发人员可以修改一块而不会影响另一块。

In contrast, other Web development platforms couple the URL to the program. In typical PHP (http://www.php.net/) applications, for example, the URL of your application is designated by where you place the code on your filesystem. In early versions of the CherryPy Python Web framework (http://www.cherrypy.org/), the URL of your application corresponded to the name of the method in which your code lived. This may seem like a convenient shortcut in the short term, but it can get unmanageable in the long run.

相比之下,其他的Web开发平台紧耦合和URL到代码中。在典型的PHP (http://www.php.net/) 应用,URL的设计是通过放置代码的目录来实现。在早期的 CherryPy Python Web framework (http://www.cherrypy.org/) 中,URL对应处理的方法名。这可能在短期看起来是便利之举, 但是长期会带来难维护的问题。

For example, consider the view function we wrote earlier, which displays the current date and time. If we wanted to change the URL for the application say, move it from /time/ to /currenttime/ we could make a quick change to the URLconf, without having to worry about the underlying implementation of the function. Similarly, if we wanted to change the view functionaltering its logic somehowwe could do that without affecting the URL to which the function is bound. Furthermore, if we wanted to expose the current-date functionality at several URLs, we could easily take care of that by editing the URLconf, without having to touch the view code.

比方说,考慮先前写的视图函数,这个函数显示当前日期和时间。如果我们想把它的URL 从原来的 /time/ 改变到 /currenttime/ ,我们只需要快速的修改一下URL配置即可, 不用担心这个函数的内部实现。同样的,如果我们想要修改这个函数的内部实现也不用担心会影响 到对应的URL。此外,如果我们想要输出这个函数到 一些 URL, 我们只需要修改URL配置而不用 去改动视图的代码。

Thats loose coupling in action. Well continue to point out examples of this important philosophy throughout this book.

Django大量应用松耦合。我们将在本书中继续给出这一重要哲学的相关例子。

404 Errors

404 错误

In our URLconf thus far, weve defined only a single URLpattern: the one that handles requests to the URL /time/ . What happens when a different URL is requested?

In our URLconf thus far, weve defined only a single URLpattern: the one that handles requests to the URL /time/ . What happens when a different URL is requested?

To find out, try running the Django development server and hitting a page such as http://127.0.0.1:8000/hello/ or http://127.0.0.1:8000/does-not-exist/ , or even http://127.0.0.1:8000/ (the site root). You should see a Page not found message (see Figure 3-2). (Pretty, isnt it? We Django people sure do like our pastel colors.) Django displays this message because you requested a URL thats not defined in your URLconf.

让我们试试看,运行Django开发服务器并访问类似 http://127.0.0.1:8000/hello/ 或者 http://127.0.0.1:8000/does-not-exist/ ,甚至 http://127.0.0.1:8000/ (网站根目录)。你将会看到一个 “Page not found” 页面(图 3-2)。(挺漂亮的,是吧? 你会喜欢上我们的配色方案的;-) 如果请求的URL没有在URL配置里设置,Django就会显示这个页面。

Screenshot of Djangos 404 page. Djangos 404 页面截屏.

Figure 3-2. Djangos 404 page

图 3-2. Django的 404 页面

The utility of this page goes beyond the basic 404 error message; it also tells you precisely which URLconf Django used and every pattern in that URLconf. From that information, you should be able to tell why the requested URL threw a 404.

这个页面的功能不只是显示404的基本错误信息,它同样精确的告诉你Django使用了哪个URL配置和 这个配置里的每一个模式。这样,你应该能了解到为什么这个请求会抛出404错误。

Naturally, this is sensitive information intended only for you, the Web developer. If this were a production site deployed live on the Internet, we wouldnt want to expose that information to the public. For that reason, this Page not found page is only displayed if your Django project is in debug mode . Well explain how to deactivate debug mode later. For now, just know that every Django project is in debug mode when you first create it, and if the project is not in debug mode, a different response is given.

当然,这些敏感的信息应该只呈现给你-开发者。如果是部署到了因特网上的站点就不应该暴露 这些信息。出于这个考虑,这个“Page not found”页面只会在 调试模式(debug mode) 下 显示。我们将在以后说明怎么关闭调试模式。现在,你只需要知道所有的Django项目在创建后都 是在调试模式下的,如果关闭了调试模式,结果将会不一样。

Your Second View: Dynamic URLs

第二个视图:动态URL

In our first view example, the contents of the pagethe current date/time were dynamic, but the URL (/time/ ) was static. In most dynamic Web applications, though, a URL contains parameters that influence the output of the page.

在我们的第一个视图范例中,尽管内容是动态的,但是URL ( /time/ )是静态的。在 大多数动态web应用程序,URL通常都包含有相关的参数。

Lets create a second view that displays the current date and time offset by a certain number of hours. The goal is to craft a site in such a way that the page /time/plus/1/ displays the date/time one hour into the future, the page /time/plus/2/ displays the date/time two hours into the future, the page /time/plus/3/ displays the date/time three hours into the future, and so on.

让我们创建第二个视图来显示当前时间和加上时间偏差量的时间,设计是这样的: /time/plus/1/ 显示当前时间+1个小时的页面 /time/plus/2/ 显示当前时间+2个小时的页面 /time/plus/3/ 显示当前时间+3个小时的页面,以此类推。

A novice might think to code a separate view function for each hour offset, which might result in a URLconf like this:

新手可能会考虑写不同的视图函数来处理每个时间偏差量,URL配置看起来就象这样:

urlpatterns = patterns('',
    (r'^time/$', current_datetime),
    (r'^time/plus/1/$', one_hour_ahead),
    (r'^time/plus/2/$', two_hours_ahead),
    (r'^time/plus/3/$', three_hours_ahead),
    (r'^time/plus/4//$', four_hours_ahead),
)

Clearly, this line of thought is flawed. Not only would this result in redundant view functions, but also the application is fundamentally limited to supporting only the predefined hour rangesone, two, three, or four hours. If, all of a sudden, we wanted to create a page that displayed the time five hours into the future, wed have to create a separate view and URLconf line for that, furthering the duplication and insanity. We need to do some abstraction here.

很明显,这样处理是不太妥当的。不但有很多冗余的视图函数,而且整个应用也被限制了只支持 预先定义好的时间段,2小时,3小时,或者4小时。如果哪天我们要实现 5 小时,我们就 不得不再单独创建新的视图函数和配置URL,既重复又混乱。我们需要在这里做一点抽象,提取 一些共同的东西出来。

A Word About Pretty URLs

关于漂亮URL的一点建议

If youre experienced in another Web development platform, such as PHP or Java, you may be thinking, Hey, lets use a query string parameter!, something like /time/plus?hours=3 , in which the hours would be designated by the hours parameter in the URLs query string (the part after the ? ).

如果你有其他Web开发平台的经验,例如PHP或者JAVA,你可能会想,好吧,让我们来用一个 查询字符串参数来表示它们吧,例如 /time/plus?hours=3 ,哪个时间段用 hours 参数代表,URL的查询字符串(query string)是URL里 ? 后面的字符串。

You can do that with Django (and well tell you how later, if you really must know), but one of Djangos core philosophies is that URLs should be beautiful. The URL /time/plus/3/ is far cleaner, simpler, more readable, easier to recite to somebody aloud and just plain prettier than its query string counterpart. Pretty URLs are a sign of a quality Web application.

可以 在Django里也这样做 (如果你真的想要这样做,我们稍后会告诉你怎么做), 但是Django的一个核心理念就是URL必须看起来漂亮。URL /time/plus/3/ 更加清晰, 更简单,也更有可读性,可以很容易的大声念出来,因为它是纯文本,没有查询字符串那么 复杂。漂亮的URL就像是高质量的Web应用的一个标志。

Djangos URLconf system encourages pretty URLs by making it easier to use pretty URLs than not to.

Django的URL配置系统可以使你很容易的设置漂亮的URL,而不是相反

Wildcard URLpatterns

带通配符的URL匹配模式

Continuing with our hours_ahead example, lets put a wildcard in the URLpattern. As we mentioned previously, a URLpattern is a regular expression; hence, we can use the regular expression pattern \d+ to match one or more digits:

继续我们的 hours_ahead 范例,让我们在URL模式里使用通配符。我们前面讲到,URL模式 是一个正则表达式,因此,我们可以使用正则表达式模式 \d+ 来匹配一个或多个数字:

from django.conf.urls.defaults import *
from mysite.views import current_datetime, hours_ahead

urlpatterns = patterns('',
    (r'^time/$', current_datetime),
    (r'^time/plus/\d+/$', hours_ahead),
)

This URLpattern will match any URL such as /time/plus/2/ , /time/plus/25/ , or even /time/plus/100000000000/ . Come to think of it, lets limit it so that the maximum allowed offset is 99 hours. That means we want to allow either one- or two-digit numbersin regular expression syntax, that translates into \d{1,2} :

这个URL模式将匹配类似 /time/plus/2/ , /time/plus/25/ ,甚至 /time/plus/100000000000/ 的任何URL。更进一步,让我们把它限制在最大允许99个小时, 这样我们就只允许一个或两个数字,正则表达式的语法就是 \d{1,2} :

(r'^time/plus/\d{1,2}/$', hours_ahead),

Note

备注

When building Web applications, its always important to consider the most outlandish data input possible, and decide whether or not the application should support that input. Weve curtailed the outlandishness here by limiting the offset to 99 hours. And, by the way, The Outlandishness Curtailers would be a fantastic, if verbose, band name.

在建造Web应用的时候,尽可能多考虑可能的数据输入是很重要的,然后决定哪些我们可以接受。 在这里我们就设置了99个小时的时间段限制。

Now that weve designated a wildcard for the URL, we need a way of passing that data to the view function, so that we can use a single view function for any arbitrary hour offset. We do this by placing parentheses around the data in the URLpattern that we want to save. In the case of our example, we want to save whatever number was entered in the URL, so lets put parentheses around the \d{1,2} :

现在我们已经设计了一个带通配符的URL,我们需要一个方法把它传递到视图函数里去,这样 我们只用一个视图函数就可以处理所有的时间段了。我们使用圆括号把参数在URL模式里标识 出来。在这个例子中,我们想要把这些数字作为参数,用圆括号把 \d{1,2} 包围起来:

(r'^time/plus/(\d{1,2})/$', hours_ahead),

If youre familiar with regular expressions, youll be right at home here; were using parentheses to capture data from the matched text.

如果你熟悉正则表达式,那么你应该已经了解,正则表达式也是用圆括号来从文本里 提取 数据的。

The final URLconf, including our previous current_datetime view, looks like this:

最终的 current_datetime URLconf,包含我们前面的视图,看起来像这样:

from django.conf.urls.defaults import *
from mysite.views import current_datetime, hours_ahead

urlpatterns = patterns('',
    (r'^time/$', current_datetime),
    (r'^time/plus/(\d{1,2})/$', hours_ahead),
)

With that taken care of, lets write the hours_ahead view.

现在开始写 hours_ahead 视图。

Coding Order

编码次序

In this example, we wrote the URLpattern first and the view second, but in the previous example, we wrote the view first, then the URLpattern. Which technique is better? Well, every developer is different.

這個例子中,我們先寫了URLpattern ,然後是視圖,但是在前面的例子中,我們先寫了視圖,然後是URLpattern 。哪種技術更好?嗯,怎麼說呢,每個開發者是不一樣的。

If youre a big-picture type of person, it may make the most sense to you to write all of the URLpatterns for your application at the same time, at the start of your project, and then code up the views. This has the advantage of giving you a clear to-do list, and it essentially defines the parameter requirements for the view functions youll need to write.

如果你是喜欢从总体上来把握事物(注:或译为“大局观”)类型的人,你应该会想在项目开始 的时候就写下所有的URL配置。这会给你带来一些好处,例如,给你一个清晰的to-do列表,让你 更好的定义视图所需的参数。

If youre more of a bottom-up developer, you might prefer to write the views first, and then anchor them to URLs afterward. Thats OK, too.

如果你从更像是一个自底向上的开发者,你可能更喜欢先写视图, 然后把它们挂接到URL上。这同样是可以的。

In the end, it comes down to which technique fits your brain the best. Both approaches are valid.

最后,取决与你喜欢哪种技术,两种方法都是可以的。

hours_ahead is very similar to the current_datetime view we wrote earlier, with a key difference: it takes an extra argument, the number of hours of offset. Add this to views.py :

hours_ahead 和我们以前写的 current_datetime 很象,关键的区别在于: 它多了一个额外参数,时间差。 views.py 修改如下:

def hours_ahead(request, offset):
    offset = int(offset)
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
    return HttpResponse(html)

Lets step through this code one line at a time:

让我们一次一行通一下这些代码:

Just as we did for our current_datetime view, we import the class django.http.HttpResponse and the datetime module.

就像我们在我们的 current_datetime 视图中所作的一样,我们导入 django.http.HttpResponse 类和 datetime 模块。

The view function, hours_ahead , takes two parameters: request and offset .

视图函数, hours_ahead , 有 两个 参数: requestoffset .

request is an HttpRequest object, just as in current_datetime . Well say it again: each view always takes an HttpRequest object as its first parameter.

request 是一个 HttpRequest 对象, 就像在 current_datetime 中一样. 再说一次好了: 每一个视图 总是 以一个 HttpRequest 对象作为 它的第一个参数。

offset is the string captured by the parentheses in the URLpattern. For example, if the requested URL were /time/plus/3/ , then offset would be the string '3' . If the requested URL were /time/plus/21/ , then offset would be the string '21' . Note that captured strings will always be strings , not integers, even if the string is composed of only digits, such as '21' .

offset 是从匹配的URL里提取出来的。例如: 如果URL是 /time/plus/3/ 那么 offset 是字符串 '3' , 如果URL是 /time/plus/21/ ,那么 offset 是字符串 '21' , 注意,提取的字符串总是 字符串 ,不是整数,即便都是数字组成,就象 '21'

We decided to call the variable offset , but you can call it whatever youd like, as long as its a valid Python identifier. The variable name doesnt matter; all that matters is that its the second argument to the function (after request ). Its also possible to use keyword, rather than positional, arguments in an URLconf. We cover that in Chapter 8.

在这里我们命名变量为 offset ,你也可以任意命名它,只要符合Python 的语法。变量名是无关紧要的,重要的是它的位置,它是这个函数的第二个 参数 (在 request 的后面)。你还可以使用关键字来定义它,而不是用 位置。详情请看第八章。

The first thing we do within the function is call int() on offset . This converts the string value to an integer.

我们在这个函数中要做的第一件事情就是在 offset 上调用 int() . 这会把这个字符串值转换为整数。

Note that Python will raise a ValueError exception if you call int() on a value that cannot be converted to an integer, such as the string 'foo' . However, in this example we dont have to worry about catching that exception, because we can be certain offset will be a string containing only digits. We know that because the regular-expression pattern in our URLconf (\d{1,2}) captures only digits. This illustrates another nicety of URLconfs: they provide a fair level of input validation.

注意Python可能会在你调用 int() 来转换一个不能转换成整数时抛出 ValueError 异常,例如字符串 'foo' 。 当然,在这个范例中我们不用担心这个问题,因为我们已经确定 offset 是 只包含数字字符的字符串。因为正则表达式 (\d{1,2}) 只提取数字字符。 这也是URL配置的另一个好处:提供了清晰的输入数据有效性确认。

The next line of the function shows why we called int() on offset . On this line, we calculate the current time plus a time offset of offset hours, storing the result in dt . The datetime.timedelta function requires the hours parameter to be an integer.

下一行显示了我们为什么调用 int() 来转换 offset 。 这一行我们要 计算当前时间加上这个时间差 offset 小时,保存结果到变量 dtdatetime.timedelta 函数的参数 hours 必须是整数类型。

Next, we construct the HTML output of this view function, just as we did in current_datetime . A small difference in this line from the previous line is that it uses Pythons format-string capability with two values, not just one. Hence, there are two %s symbols in the string and a tuple of values to insert: (offset, dt) .

这行和前面的那行的一个微小差别就是,它使用带有两个值的Python的格式化字符串功能, 而不仅仅是一个值。因此,在字符串中有两个 %s 符号和一个以进行插入的值的元组: (offset, dt)

Finally, we return an HttpResponse of the HTMLagain, just as we did in current_datetime .

最后,我们再一次返回一个HTML的 HttpResponse ,就像我们在 current_datetime 做的一样。

With that view function and URLconf written, start the Django development server (if its not already running), and visit http://127.0.0.1:8000/time/plus/3/ to verify it works. Then try http://127.0.0.1:8000/time/plus/5/ . Then http://127.0.0.1:8000/time/plus/24/ . Finally, visit http://127.0.0.1:8000/time/plus/100/ to verify that the pattern in your URLconf only accepts one- or two-digit numbers; Django should display a Page not found error in this case, just as we saw in the 404 Errors section earlier. The URL http://127.0.0.1:8000/time/plus/ (with no hour designation) should also throw a 404.

在完成视图函数和URL配置编写后,启动Django开发服务器,用浏览器访问 http://127.0.0.1:8000/time/plus/3/ 来确认它工作正常。 然后是 http://127.0.0.1:8000/time/plus/5/ 。再然后是 http://127.0.0.1:8000/time/plus/24/ 。最后,访问 http://127.0.0.1:8000/time/plus/100/ 来检验URL配置里设置的模式是否只 接受一个或两个数字;Django会显示一个 Page not found error 页面, 和以前看到的 404 错误一样。访问URL http://127.0.0.1:8000/time/plus/ (没有 定义时间差) 也会抛出404错误。

If youre following along while coding at the same time, youll notice that the views.py file now contains two views. (We omitted the current_datetime view from the last set of examples for clarity.) Put together, views.py should look like this:

你现在已经注意到 views.py 文件中包含了两个视图, views.py 看起来象这样:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

def hours_ahead(request, offset):
    offset = int(offset)
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
    return HttpResponse(html)

Djangos Pretty Error Pages

Django 漂亮的出错页面

Take a moment to admire the fine Web application weve made so far now lets break it! Well deliberately introduce a Python error into our views.py file by commenting out the offset = int(offset) line in the hours_ahead view:

花几分钟时间欣赏一下我们写好的Web应用程序,然后我们再来搞点小破坏。我们故意在 views.py 文件中引入一项 Python 错误,注释掉 hours_ahead 视图中的 offset = int(offset) 一行。

def hours_ahead(request, offset):
    #offset = int(offset)
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt)
    return HttpResponse(html)

Load up the development server and navigate to /time/plus/3/ . Youll see an error page with a significant amount of information, including a TypeError message displayed at the very top: "unsupported type for timedelta hours component: str" .

启动开发服务器,然后访问 /time/plus/3/ 。你会看到一个包含大量信息的出错页,最上面 的一条 TypeError 信息是: "unsupported type for timedelta hours component: str"

What happened? Well, the datetime.timedelta function expects the hours parameter to be an integer, and we commented out the bit of code that converted offset to an integer. That caused datetime.timedelta to raise the TypeError . Its the typical kind of small bug that every programmer runs into at some point.

怎么回事呢?是的, datetime.timedelta 函数要求 hours 参数必须为整型, 而我们注释掉了将 offset 转为整型的代码。这样导致 datetime.timedelta 弹出 TypeError 异常。这是所有程序员某个时候都可能碰到的一种典型错误。

The point of this example was to demonstrate Djangos error pages. Take some time to explore the error page and get to know the various bits of information it gives you.

这个例子是为了展示 Django 的出错页面。我们来花些时间看一看这个出错页,了解一下其中 给出了哪些信息。

Here are some things to notice:

以下是值得注意的一些要点:

At the top of the page, you get the key information about the exception: the type of exception, any parameters to the exception (the "unsupported type" message in this case), the file in which the exception was raised, and the offending line number.

在页面顶部,你可以得到关键的异常信息:异常数据类型、异常的参数 (如本例中的 "unsupported type" )、在哪个文件中引发了异常、出错的行号等等。

Under the key exception information, the page displays the full Python traceback for this exception. This is similar to the standard traceback you get in Pythons command-line interpreter, except its more interactive. For each frame in the stack, Django displays the name of the file, the function/method name, the line number, and the source code of that line.

在关键异常信息下方,该页面显示了对该异常的完整 Python 追踪信息。这类似于你在 Python 命令行解释器中获得的追溯信息,只不过后者更具交互性。对栈中的每一帧,Django 均显示了其文件名、函数或方法名、行号及该行源代码。

Click the line of source code (in dark gray), and youll see several lines from before and after the erroneous line, to give you context.

点击该行代码 (以深灰色显示),你可以看到出错行的前后几行,从而得知相关上下文情况。

Click Local vars under any frame in the stack to view a table of all local variables and their values, in that frame, at the exact point in the code at which the exception was raised. This debugging information is invaluable.

点击栈中的任何一帧的“Local vars”可以看到一个所有局部变量的列表,以及在出错 那一帧时它们的值。这些调试信息是无价的。

Note the Switch to copy-and-paste view text under the Traceback header. Click those words, and the traceback will switch to a alternate version that can be easily copied and pasted. Use this when you want to share your exception traceback with others to get technical support such as the kind folks in the Django IRC chat room or on the Django users mailing list.

注意“Traceback”下面的“Switch to copy-and-paste view”文字。点击这些字,追溯会 切换另一个视图,它让你很容易地复制和粘贴这些内容。当你想同其他人分享这些异常 追溯以获得技术支持时(比如在 Django 的 IRC 聊天室或邮件列表中),可以使用它。

Next, the Request information section includes a wealth of information about the incoming Web request that spawned the error: GET and POST information, cookie values, and meta information, such as CGI headers. Appendix H has a complete reference of all the information a request object contains.

接下来的“Request information”部分包含了有关产生错误的 Web 请求的大量信息: GET 和 POST、cookie 值、元数据(象 CGI 头)。在附录H里给出了request的对象的 完整参考。

Below the Request information section, the Settings section lists all of the settings for this particular Django installation. All the available settings are covered in detail in Appendix E. For now, take a look at the settings to get an idea of the information available.

Request信息的下面,“Settings”列出了 Django 使用的具体配置信息。同样在附录E 给出了settings 配置的完整参考。现在,大概浏览一下,对它们有个大致印象就好了。

The Django error page is capable of displaying more information in certain special cases, such as the case of template syntax errors. Well get to those later, when we discuss the Django template system. For now, uncomment the offset = int(offset) line to get the view function working properly again.

Django 的出错页某些情况下有能力显示更多的信息,比如模板语法错误。我们讨论 Django 模板系统时再说它们。现在,取消 offset = int(offset) 这行的注释,让它重新正常 工作。

Are you the type of programmer who likes to debug with the help of carefully placed print statements? You can use the Django error page to do sojust without the print statements. At any point in your view, temporarily insert an assert False to trigger the error page. Then, you can view the local variables and state of the program. (Theres a more advanced way to debug Django views, which well explain later, but this is the quickest and easiest.)

不知道你是不是那种使用小心放置的 print 语句来帮助调试的程序员?你其实可以用 Django 出错页来做这些,而不用 print 语句。在你视图的任何位置,临时插入一个 assert False 来触发出错页。然后,你就可以看到局部变量和程序语句了。(还有更高级的办法来调试 Django 视图,我们后来再说,但这个是最快捷最简单的办法了。)

Finally, its obvious that much of this information is sensitiveit exposes the innards of your Python code and Django configurationand it would be foolish to show this information on the public Internet. A malicious person could use it to attempt to reverse-engineer your Web application and do nasty things. For that reason, the Django error page is only displayed when your Django project is in debug mode. Well explain how to deactivate debug mode later. For now, just know that every Django project is in debug mode automatically when you start it. (Sound familiar? The Page not found errors, described in the 404 Errors section, work the same way.)

最后,很显然这些信息很多是敏感的,它暴露了你 Python 代码的内部结构以及 Django 配置,在 Internet 上公开这信息是很愚蠢的。不怀好意的人会尝试使用它攻击你的 Web 应用程序,做些下流之事。因此,Django 出错信息仅在 debug 模式下才会显现。我们稍后 说明如何禁用 debug 模式。现在,你只要知道 Django 服务器在你开启它时默认运行在 debug 模式就行了。(听起来很熟悉?“Page not found”错误,“404 错误”一节也这样描述过。)

Whats next?

下一章将要讲?

System Message: WARNING/2 (<string>, line 2036)

Title underline too short.

下一章将要讲?
``````````

Weve so far been producing views by hard-coding HTML into the Python code. Unfortunately, this is nearly always a bad idea. Luckily, Django ships with a simple yet powerful template engine that allows you to separate the design of the page from the underlying code. Well dive into Djangos template engine in the next chapter.

我们现在已经学会了怎么在Python代码里硬编码HTML代码来处理视图。可惜的是,这种方法通常不是一个好方法。幸运的是,Django内建有一个简单有强大的模板处理引擎来让你分离两种工作:设计HTML页面和编写Python代码。下一章我们将深入到Django的模板引擎里去。

Copyright 2006 Adrian Holovaty and Jacob Kaplan-Moss.
This work is licensed under the GNU Free Document License.
Hosting graciously provided by media temple
Chinese translate hosting by py3k.cn. 粤ICP备16122281号-1