从WSGI或shell

时间:2015-09-01 20:57:35

标签: python django apache mod-wsgi

我使用mod_wsgi在Apache服务器上部署了一个Django项目,使用前缀URL /mysite,即我的Apache配置包含

WSGIScriptAlias /mysite /var/www/mysite/mysite/wsgi.py

从Web服务器进程调用reverse('myview')(来自django.core.urlresolvers)时,它会返回预期的网址/mysite/myview,即包含前缀网址。

但是,当从脚本(例如cronjob)调用reverse('myview')时,而不是通过Web服务器进程调用时,只返回/myview而没有所需的前缀URL。我的示例脚本如下所示:

import sys
import os
import django

sys.path.append('/var/www/mysite')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
django.setup()

from django.core.urlresolvers import reverse
print reverse('myview') # prints '/myview'

有没有办法在Web服务器上下文外部运行时包含前缀URL,以便可以从两个上下文运行相同的reverse('myview')代码并返回相同的值?

1 个答案:

答案 0 :(得分:3)

Django only expects a SCRIPT_NAME in the context of a web request. It is retrieved from the WSGI environment or the FORCE_SCRIPT_NAME setting and set for the duration of the request.

To manually set a script name, use set_script_prefix():

from django.core.urlresolvers import set_script_prefix

set_script_prefix('/mysite')

Note that this is 1) a private, undocumented function, and 2) stored in a thread-local variable.