我想使用不同的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'}),
]