2

I've implemented my own context processor and I'm trying to configure it properly in django's settings:

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as DEFAULT_PROCESSORS
MY_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
    'com.mysite.apps.myapp.processors.MyProcessor.MyProcessor.process',
)
TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_PROCESSORS + MY_CONTEXT_PROCESSORS

but I got the following error:

Error importing request processor module com.mysite.apps.myapp.processors.MyProcessor.MyProcessor: "No module named MyProcessor"

MyProcessor is a simple class with a static method "process" (I love OOP and I use classes and package architecture in my project). It exits and is spelled correctly... so what's wrong?

UPDATE:

by replacing my class with a simple "process" function ("com.mysite.apps.myapp.processors.MyProcessor.process") it works... but I'm not satisfied... how does Django load these processors? I use a packages/classes approach everywhere in my app (models, tests, views...) and it usually works... what's the difference here? Since the dynamic nature of Python, a path like "com.mysite.apps.myapp.processors.MyProcessor.MyProcessor" should be resolved independently from a class or a standard "submodule"... don't you agree?

4

2 回答 2

2

Django 不知道是.表示子包还是该包中的变量。因此foo.bar.baz.quux,假设 , foo,bar都是baz包,并且quux(即最后一个值)是该模块的属性。

TEMPLATE_CONTEXT_PROCESSORSdjango.template.context.get_standard_processors最终由(源代码)导入其值。

这是该函数中的相关代码:

i = path.rfind('.')
module, attr = path[:i], path[i+1:]

因此,您无法访问模块内的嵌套值。这在我能看到的任何地方都没有明确记录。如果您真的想访问静态方法,我能看到的唯一选择是:

class MyProcessor(object):

    @staticmethod
    def process(request):
        # whatever ...


process = MyProcessor.process

然后添加到您的TEMPLATE_CONTEXT_PROCESSORS "com.mysite.apps.myapp.processors.MyProcessor.process"

于 2013-06-21T12:04:56.860 回答
0

你有一个名为 的文件MyProcessor.py吗?听起来 Python 期望你拥有:

com/mysite/processors/MyProcessor.py
于 2013-06-21T10:04:32.520 回答