python/django:如何检测和避免导入名称冲突?

python/django:如何检测和避免导入名称冲突?,python,django,import,conflict,Python,Django,Import,Conflict,我有一个愿望,我需要一些帮助。 在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应用程序中,我有以下代码:

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
,它被错误地使用了,所以我像这样更改代码(非常难看,但仍然有效):


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

一种解决方案是通过对导入的
上下文使用别名来避免冲突:

from django.template import Context as template_context

然后,当您需要尝试使用的版本时,只需参考模板上下文。

一种解决方案是通过对导入的
上下文使用别名来避免冲突:

from django.template import Context as template_context

然后,当您需要尝试使用的版本时,只需参考模板上下文。

使用
\uuuuuu内置模块中的
\uuuuuuuu导入功能:

#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

使用
\uuuuu内置模块中的
\uuuuuu导入
功能:

#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