gpt4 book ai didi

Django:urls.py 中的 urlpatterns 格式

转载 作者:行者123 更新时间:2023-12-03 11:13:23 25 4
gpt4 key购买 nike

我注意到在 Django 中有两种格式 urlpatterns在文件 urls.py :

urlpatterns = [
url(...),
url(...),
]


urlpatterns = pattern('',
url(...),
url(...),
)

第一个是 url的列表实例,第二个调用 pattern具有空字符串和数字 url 的模块实例作为参数。
  • 两者有什么区别?
  • 第二种格式的空字符串的目的是什么?
  • 推荐使用哪一种?
  • 最佳答案

    根据 the documentation , patterns是:

    A function that takes a prefix, and an arbitrary number of URL patterns, and returns a list of URL patterns in the format Django needs.

    The first argument to patterns() is a string prefix.



    它还提供了一个示例,说明您可能想要使用它的原因:

    from django.conf.urls import patterns, url

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

    In this example, each view has a common prefix – 'news.views'. Instead of typing that out for each entry in urlpatterns, you can use the first argument to the patterns() function to specify a prefix to apply to each view function.

    With this in mind, the above example can be written more concisely as:

    from django.conf.urls import patterns, url

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


    但是,请注意,此功能已弃用:

    Deprecated since version 1.8:

    urlpatterns should be a plain list of django.conf.urls.url() instances instead.



    请注意 the explanation as to why包括(有充分的理由,显然!):

    Thus patterns() serves little purpose and is a burden when teaching new users (answering the newbie’s question "why do I need this empty string as the first argument to patterns()?").

    关于Django:urls.py 中的 urlpatterns 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31474285/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com