Python/Django 导入了错误的模块(相对的模块应该是绝对的)
我正在使用 Django 1.2 pre-alpha 和 Python 2.4。是的,我知道,但我坚持下去。我们目前无法升级,无论如何我怀疑这就是答案。
我有两个模板标记库:foo
和bar
。然而,foo
也是一个顶级包的名称,而且它恰好是bar
的包:
foo-1.2.3/
foo/
conf/
settings.py
templatetags/
bar.py
bar-4.5/
somepackage/
templatetags/
foo.py
标签库bar.py
包含这样一行:
from foo.conf import settings
...并且您希望它加载 foo-1.2.3/foo/conf/settings.py 。
但没有:
TemplateSyntaxError:“bar”不是有效的标签库:无法从 django.templatetags.bar 加载模板库,没有名为 conf 的模块
不幸的是,Django 执行 一点魔法,将所有模板标签库绑定到 django.templatetags.*
。因此,bar
被导入为 django.templatetags.bar
,当它调用 from foo.conf import settings
时,它最终会导入 >bar-4.5/somepackage/templatetags/foo.py
。啊!
您有任何解决此问题的想法吗?
我在导入之前设置了一个断点,并且我已确认 foo-1.2.3
位于开头sys.path,但 import
关键字仍然找到错误的 foo
。
如果有帮助,请注意,我可以修改 foo-1.2.3
包(因为它已在本地签入并正在逐步淘汰),但我拒绝修改 bar-4.5< /code> 包(因为它是一个开源包并且已在系统范围内安装)。
I'm using Django 1.2 pre-alpha and Python 2.4. Yeah, I know, but I'm stuck with it. We can't upgrade at the moment and I doubt that's the answer anyway.
I've got two template tag libraries, foo
and bar
. However, foo
is also the name of a top-level package, and it happens to be the package of bar
:
foo-1.2.3/
foo/
conf/
settings.py
templatetags/
bar.py
bar-4.5/
somepackage/
templatetags/
foo.py
The tag library bar.py
contains a line like this:
from foo.conf import settings
...and you would expect it to load foo-1.2.3/foo/conf/settings.py
.
But no:
TemplateSyntaxError: 'bar' is not a valid tag library: Could not load template library from django.templatetags.bar, No module named conf
Unfortunately, Django performs a little magic and binds all template tag libraries to django.templatetags.*
. Thus, bar
is being imported as django.templatetags.bar
, and when it calls from foo.conf import settings
it ends up importing bar-4.5/somepackage/templatetags/foo.py
. Ugh!
Do you have any ideas how to fix this?
I've set a breakpoint right before the import, and I've confirmed that foo-1.2.3
is at the beginning of sys.path
, but the import
keyword still finds the wrong foo
.
If it helps, note that I can modify the foo-1.2.3
package (because it's been checked in locally and is being phased out), but I refuse to modify the bar-4.5
package (because it's an open-source package and has been installed system-wide).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过几个小时的黑客攻击,这成功了。
原始代码:
新代码:(
我可能不需要第二行。)
Ewww。
After a few more hours of hacking, this did the trick.
Original code:
New code:
(I probably don't need the second line.)
Ewww.