2013-04-18 34 views
2

我有一个,我需要一些帮助。 在我的Django应用程序,我有这样的代码:python/django:如何检测并避免导入名称冲突?

from django.template import Context 

render_dict = {'scan': oval_scan, 'user': user, 'vulns': oval_vulns, 'asset_vulns': asset_vulns} 
report_html = get_template('oval_report.html').render(Context(render_dict)) 

然而,Django的给了我以下错误:

Traceback (most recent call last): 
    File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111, in get_response 
    response = callback(request, *callback_args, **callback_kwargs) 
    File "/home/nopsec/nopsecvrm/apps/pegasus/views.py", line 2359, in ovalReport 
    report_html = get_template('pegasus/oval_report.html').render(Context(render_dict)) 
    File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 121, in render 
    context.render_context.push() 
AttributeError: 'Context' object has no attribute 'render_context' 

我记得有一次,我遇到了这个错误,因为还有另外一个Context别的地方另进口包,这是用来错误,所以我改变了这样的代码(非常难看,但工程):

import django 

render_dict = {'scan': oval_scan, 'user': user, 'vulns': oval_vulns, 'asset_vulns': asset_vulns} 
report_html = get_template('report.html').render(django.template.Context(render_dict)) 

我的问题是:我怎么能通过查看回溯错误来确定哪个Context错误地使用了django?我该如何解决这种情况?谢谢。

回答

4

一个解决办法是通过别名,你导入Context以避免冲突:

from django.template import Context as template_context 

然后直接在您需要时您要使用的版本来template_context。

+0

这是非常不错的! –

0

__builtins__模块使用__import__功能:

#Detecting name conflicts: 
module_name_as_string = 'mymodule' 

if module_name_as_string in globals(): #we have name collision 
    try: 
     custom_module = __import__(module_name_as_string) 
    except ImportError: 
     pass