【发布时间】:2013-07-01 00:19:22
【问题描述】:
我正在编写以下内容来为我的 urls.py 生成 URL:
urls = {
'overview': {
r'^$': [ 'Index' ],
r'^/account$': [ 'Account' ],
},
'content': {
r'^/content$': [ 'Index' ]
r'^/content/upload$': [ 'Uploader', 'Default' ]
}
}
urlpatterns = patterns('')
for module, spec in urls.iteritems():
urlpatterns += patterns('views.'+ module,
[
url(regex, (getattr(module.capitalize() , 'as_view'))(), action=view[0])
if len(view) == 1 else
url(regex, (getattr(view[0], 'as_view'))(), action=view[1])
for regex, view in spec.iteritems()
]
)
我有模块overview 和content,分别有Overview 和Content 和Uploader 类。
如果view 数组(例如,[ 'Index' ] 包含单个元素,我使用模块的大写形式(例如,overview 变为 Overview)来生成路由:
url(r'^$', Overview.as_view(), action='Index')
如果它包含两个元素(例如,[ 'Uploader', 'Default' ]),第一个元素指定类名,第二个元素指定方法:
url(r'^$', Uploader.as_view(), action='Default')
您可能已经注意到,问题在于我使用了getattr(),它的第一个参数需要类引用。所以,我的问题是是否有任何方法可以从包含所述类对象标识符的字符串中获取类对象,例如来自'Uploader' 的Uploader 类。
作为免责声明,这些不是我的确切路线,只是一个例子。当然,关于我在这里的整体设计,也欢迎进一步的 cmets。
【问题讨论】:
标签: python django string class getattr