Django:条件URL模式



我想使用不同的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中正确地做到这一点?

试试这个:

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。在你的情况下,你没有,因此错误。

在Django 1.8及以上版本中,添加url很简单:

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

最新更新