Django + Apache wsgi = 路径问题

0 投票
3 回答
1734 浏览
提问于 2025-04-15 22:39

我有一个视图,用来生成界面语言选项菜单。

def lang_menu(request,language):

    lang_choices = []
    import os.path

    for lang in settings.LANGUAGES:
        if os.path.isfile("gui/%s.py" % lang) or os.path.isfile("gui/%s.pyc" % lang):
            langimport = "from gui.%s import menu" % lang
            try:
                exec(langimport)
            except ImportError:
                lang_choices.append({'error':'invalid language file'})
            else:
                lang_choices.append(menu)
        else:
            lang_choices.append({'error':'lang file not found'})

    t = loader.get_template('gui/blocks/lang_menu_options.html')

    data = ''

    for lang in lang_choices:
        if not 'error' in lang:
            data = "%s\n%s" % (data,t.render(Context(lang)))

    if not data:
        data = "Error! No languages configured or incorrect language files!"

    return Context({'content':data})

当我在开发服务器上运行(python manage.py runserver ...)时,一切都正常。但是当我把我的应用移到apache wsgi服务器上时,出现了错误:“No languages configured or incorrect language files!”。

这是我的Apache配置:

<VirtualHost *:9999>

WSGIScriptAlias / "/usr/local/etc/django/terminal/django.wsgi"

<Directory "/usr/local/etc/django/terminal">
    Options +ExecCGI
    Allow From All
</Directory>

Alias /media/ "/usr/local/lib/python2.5/site-packages/django/contrib/admin/media/"
<Location /media/>
    SetHandler None
</Location>

<Directory "/usr/local/lib/python2.5/site-packages/django/contrib/admin/media/>
    Allow from all
</Directory>

Alias /static/ "/usr/local/etc/django/terminal/media/"
<Location /static/>
    SetHandler None
</Location>

ServerName *******
ServerAlias *******
ErrorLog /var/log/django.error.log
TransferLog /var/log/django.access.log

</VirtualHost>

django.wsgi:

import os, sys
sys.path.append('/usr/local/etc/django')
sys.path.append('/usr/local/etc/django/terminal')
os.environ['DJANGO_SETTINGS_MODULE'] = 'terminal.settings'

import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()

看起来像是路径配置的问题,但我在这里卡住了……

3 个回答

1

很难看清楚发生了什么,因为虽然你在循环中存储了一些有用的错误信息,但最后又用一个通用的错误信息把它们全部覆盖了。其实,列出遇到的错误会更有帮助。

我还想问问,为什么你要手动管理语言文件,而不是使用系统自带的国际化/本地化处理功能呢?

2

如果你在 lang_menu 里调用这个,它会给你正确的路径吗?

os.path.abspath(os.path.dirname(__file__))

如果这个确实指向你视图模块所在的文件夹,你可以在这个基础上构建出一个绝对路径,比如:

here = lambda *x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
if os.path.isfile(here('gui', '%s.py' % lang)):
    ...
1

问题可能出在这一行代码 os.path.isfile("gui/%s.py" % lang)。你这里使用的是相对路径。建议改用绝对路径,这样就没问题了。

还有一些其他建议:

  1. 不要用 exec 来导入文件,建议使用 __import__
  2. 不要通过查找文件来决定配置!这样做既慢又不可靠。可以把数据存储在数据库里,比如。

撰写回答