【问题标题】:Django: conditional URL patterns?Django:条件 URL 模式?
【发布时间】:2013-06-11 06:42:21
【问题描述】:

我想使用不同的robots.txt 文件,具体取决于我的服务器是生产服务器还是开发服务器。

为此,我想在urls.py 中以不同的方式路由请求:

urlpatterns = patterns('',
   // usual patterns here
)

if settings.IS_PRODUCTION: 
  urlpatterns.append((r'^robots\.txt$', direct_to_template, {'template': 'robots_production.txt', 'mimetype': 'text/plain'}))
else:
  urlpatterns.append((r'^robots\.txt$', direct_to_template, {'template': 'robots_dev.txt', 'mimetype': 'text/plain'}))

但是,这不起作用,因为我没有正确使用patterns 对象:我得到AttributeError at /robots.txt - 'tuple' object has no attribute 'resolve'

如何在 Django 中正确执行此操作?

【问题讨论】:

    标签: django django-urls


    【解决方案1】:

    试试这个:

    if settings.IS_PRODUCTION: 
      additional_settings = patterns('',
         (r'^robots\.txt$', direct_to_template, {'template': 'robots_production.txt', 'mimetype': 'text/plain'}),
      )
    else:
      additional_settings = patterns('',
          (r'^robots\.txt$', direct_to_template, {'template': 'robots_dev.txt', 'mimetype': 'text/plain'}),
      )
    
    urlpatterns += additional_settings
    

    由于您要附加 tuple 类型,因此 append 不起作用。
    此外,pattern() 会为您调用urlresolver。在你的情况下你不是,因此错误。

    【讨论】:

    • urlpatterns 不是元组。 patterns 方法返回一个列表,所以 append 可以这样做。
    • @PauloBu 你是对的 - 但我的意思是,你必须连接 tuple 类型
    • 哦,我明白了!,我知道了 :)
    【解决方案2】:

    在 Django 1.8 及更高版本中,添加 URL 很简单:

    if settings.IS_PRODUCTION:
        urlpatterns += [
          url(r'^robots\.txt$', direct_to_template, {'template': 'robots_production.txt', 'mimetype': 'text/plain'}),
        ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2015-08-22
      • 2021-12-25
      • 2011-04-10
      • 2012-06-18
      相关资源
      最近更新 更多