我正在为我的Django项目写一个小应用程序。这个想法是创建一些小部件-小的视图功能,可以通过包含标签添加到模板中,以显示一些附加信息(例如博客记录、快速链接列表、菜单等)。为此,我想创建类似于默认的templatetag
注册机制。通常我需要以下组件:
我现在写的是这样的:
# -*- coding: utf-8 -*-
REGISTERED_WIDGETS = []
class Library(object):
"""
Utility class for registering defined widgets
"""
def widget(self, view=None, name=None, form_class=None):
if name is None:
name = view.__name__
def decorator(view):
print 'registering', view
REGISTERED_WIDGETS.append((view, name, form_class))
def wrapper(request, *args, **kwargs):
return view(request, *args, **kwargs)
return wrapper
if view is not None:
return decorator(view)
else:
return decorator
def search_widgets():
"""
Search for 'widgets.py' modules inside installed applications and import them,
hence initializing its registration
"""
from django.conf import settings
for app in settings.INSTALLED_APPS:
try:
module = __import__(app + '.widgets')
print module
except ImportError:
pass
else:
print 'Imported widgets from ', app
if __name__ == '__main__':
search_widgets()
print REGISTERED_WIDGETS
为了测试它,我在小工具.py在我的一个应用程序中:
^{pr2}$我现在遇到了一个愚蠢的问题——当运行这个模块时,我想看到注册的_WIDGETS变量填充了找到的WIDGETS,但是它是空的。实际上,我看到了这个输出:
>>> %run widgets/base.py
<module 'django' from '/usr/lib/python2.7/dist-packages/django/__init__.pyc'>
Imported widgets from django.contrib.admin
registering <function dummy_widget at 0x364f320>
<module 'experiments' from '/home/east825/Development/pycharm-experiments/experiments/../experiments/__init__.pyc'>
Imported widgets from experiments.layout
[]
我好像忘了一些关于python共享全局变量行为的重要信息。 有什么建议吗?在
有可能你的模块基准.py被导入两次?在
在开始处添加打印基准.py有“指纹”基准.py“处决”之类的。在
编辑:或者更好的,打印id(注册的嫘uwidgets)
相关问题 更多 >
编程相关推荐