Django 1.11中文文档:URL dispatcher

URL dispatcher

A clean, elegant URL scheme is an important detail in a high-quality Web application. Django lets you design URLs however you want, with no framework limitations.

简洁、优雅的URL设计对于高质量的web应用来说是非常重要的,Django允许你随心所欲的设计URLs,而不受框架的约束。

There’s no .php or .cgi required, and certainly none of that 0,2097,1-1-1928,00 nonsense.

不再要求.php 或 .cgi ,更不会要求0,2097,1-1-1928,00这样无意义 的东西

See Cool URIs don’t change, by World Wide Web creator Tim Berners-Lee, for excellent arguments on why URLs should be clean and usable.

参见World Wide Web的发明者写的Cool URIs don’t change,里面详细说了为什么URLs应该简洁易用。

Overview
概览

To design URLs for an app, you create a Python module informally called a URLconf (URL configuration). This module is pure Python code and is a simple mapping between URL patterns (simple regular expressions) to Python functions (your views).

要给应用设计URLs,需首先创建一个叫URLconf(URL 配置)的Python模块。这个模块是纯粹的Python代码,包含了URL模式(简单正则表达式)到Python函数(你的视图)的简单映射。

This mapping can be as short or as long as needed. It can reference other mappings. And, because it’s pure Python code, it can be constructed dynamically.

这个映射关系可长可短。也可以引用其他的映射。而且,由于它是纯粹的Python代码,它可以动态的调整。

Django also provides a way to translate URLs according to the active language. See the internationalization documentation for more information.

Django还提供当前语言翻译URL的一种方法,详细信息参考internationalization documentation

How Django processes a request

How Django processes a request

When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:

当一个用户请求Django 站点的一个页面,下面是Django 系统决定执行哪个Python 代码的算法:

  1. Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONFsetting, but if the incoming HttpRequest
     object has a urlconf attribute (set by middleware), its value will be used in place of the ROOT_URLCONF setting.

    Django首先会使用root URLconf模块。通常,这是 ROOT_URLCONF配置,但如果这个请求带有urlconf 属性(通过中间件设置),那它的值会覆盖ROOT_URLCONF的配置

  2. Django loads that Python module and looks for the variable urlpatterns. This should be a Python list of django.conf.urls.url() instances.

    Django加载该Python模块并匹配url模式。它是django.conf.urls.url() 实例的Python列表。

  3. Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.

    Django 依次匹配每个URL模式,直到匹配到第一个为止。

  4. Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function (or a class-based view). The view gets passed the following arguments:

    一旦其中的一个正则表达式匹配上,Django 将导入并调用给出的视图,它是一个简单的Python 函数( 或者是class-based view)。视图函数将获得如下参数:

    • An instance of HttpRequest.

    • 一个HttpRequest实例

    • If the matched regular expression returned no named groups, then the matches from the regular expression are provided as positional arguments.

    • 如果匹配的正则表达式返回的是未命名的组,那么正则表达式匹配的内容将作为位置参数提供给视图

    • The keyword arguments are made up of any named groups matched by the regular expression, overridden by any arguments specified in the optional kwargs argument to django.conf.urls.url().

    • 关键字参数由正则表达式匹配的命名组组成,但是可被django.conf.urls.url()的可选参数kwargs覆盖。

    • If no regex matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view. See Error handling below.

    • 如果没有匹配到正则表达式,或者如果过程中抛出一个异常,Django 将调用一个错误处理视图。请参见下面的Error handling 。

Example
示例

Here’s a sample URLconf:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),
    url(r'^articles/([0-9]{4})/$', views.year_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
]

Notes:

  • To capture a value from the URL, just put parenthesis around it.

  • 若要从URL捕获一个值,只需要加一个圆括号括起来即可

  • There’s no need to add a leading slash, because every URL has that. For example, it’s ^articles, not ^/articles.

  • 开头不需要再加斜杠,因为每个URL都有。比如说,应写^articles, 而不是 ^/articles.

  • The ‘r’ in front of each regular expression string is optional but recommended. It tells Python that a string is “raw” – that nothing in the string should be escaped. See Dive Into Python’s explanation.

  • 每个正则表达式前面的‘r’不强求,但是推荐加上。它告诉python这个字符串是“原始的”——字符串中任何字符都不用转义。参见Dive Into Python’s explanation

Example requests:

请求的例子:

  • A request to /articles/2005/03/ would match the third entry in the list. Django would call the function views.month_archive(request, ‘2005’, ‘03’).

  • /articles/2005/03/ 请求会匹配到url列表中的第三个。Django会调用views.month_archive(request, ‘2005’, ‘03’).

  • /articles/2005/3/ would not match any URL patterns, because the third entry in the list requires two digits for the month.

  • /articles/2005/3/ 不匹配任何URL 模式,因为列表中的第三个模式要求月份应该是两个数字。

  • /articles/2003/ would match the first pattern in the list, not the second one, because the patterns are tested in order, and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this. Here, Django would call the function views.special_case_2003(request)

  • /articles/2003/ 将匹配列表中的第一个模式不是第二个,因为模式按顺序匹配,第一个会首先被匹配通过。为了应对这种情况,你可以在之前插入一些url特例,比如对这里而言,Django会调用views.special_case_2003(request)。

  • /articles/2003 would not match any of these patterns, because each pattern requires that the URL end with a slash.

  • /articles/2003不会匹配任何模式,因为每个URL模式都要求以斜杠结尾

  • /articles/2003/03/03/ would match the final pattern. Django would call the function views.article_detail(request, ‘2003’, ‘03’, ‘03’).

  • /articles/2003/03/03/将匹配最后一个,Django会调用views.article_detail(request, ‘2003’, ‘03’, ‘03’)

Named groups
命名组

The above example used simple, non-named regular-expression groups (via parenthesis) to capture bits of the URL and pass them as positional arguments to a view. In more advanced usage, it’s possible to use named regular-expression groups to capture URL bits and pass them as keyword arguments to a view.

上面的示例使用简单的、没有命名的正则表达式组(通过圆括号)来捕获URL 中的值并以位置参数传递给视图。在更高级的用法中,可以使用命名的正则表达式组来捕获URL 中的值并以关键字参数传递给视图。

In Python regular expressions, the syntax for named regular-expression groups is (?Ppattern), where name
 is the name of the group and pattern is some pattern to match.

在Python 正则表达式中,命名正则表达式组的语法是(?Ppattern),其中name 是组的名称,pattern 是要匹配的模式。

Here’s the above example URLconf, rewritten to use named groups:

在上面示例中的URLconf中,用命名组重写后:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),
    url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
    url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
    url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail),
]

This accomplishes exactly the same thing as the previous example, with one subtle difference: The captured values are passed to view functions as keyword arguments rather than positional arguments. For example:

这基本与上次的例子是一样的,只有一个细微差别:捕获的值作为关键字参数而不是位置参数传递给视图函数。例如:

  • A request to /articles/2005/03/ would call the function views.month_archive(request, year=’2005’, month=’03’), instead of views.month_archive(request, ‘2005’, ‘03’).

  • /articles/2005/03/请求将调用views.month_archive(request, year=’2005’, month=’03’),而不是views.month_archive(request, ‘2005’, ‘03’)

  • A request to /articles/2003/03/03/ would call the function views.article_detail(request, year=’2003’, month=’03’, day=’03’).

  • /articles/2003/03/03/ 请求将调用views.article_detail(request, year=’2003’, month=’03’, day=’03’).

In practice, this means your URLconfs are slightly more explicit and less prone to argument-order bugs – and you can reorder the arguments in your views’ function definitions. Of course, these benefits come at the cost of brevity; some developers find the named-group syntax ugly and too verbose.

在实际应用中,这意味你的URLconf 会更加明晰且不容易产生参数顺序问题的错误 —— 你可以在你的视图函数定义中重新安排参数的顺序。当然,这带来好处的同时牺牲了简洁性;有些开发人员认为命名组语法丑陋且繁琐。

The matching/grouping algorithm
匹配/分组的算法
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值