flask中如何通过类的名字得到类的对象

2019-08-21  本文已影响0人  python与数据分析

出错 :AttributeError: 'str' object has no attribute 'allow_api' // Werkzeug Debugger

class AdminScope:
    allow_api = ['v1.super_get_user']


class UserScope:
    allow_api = []


def is_in_scope(scope, endpoint):
    if endpoint in scope.allow_api:
        return True
    else:
        return False

我们可以看到出错代码在:scope.allow_api这块,这里的scope是类变量,传入的是AdminScope或UserScope,现在需要通过动态创建对象,也就是类的名字调用类的变量,显然我上面的方法是不行的。

解决办法:通过globals,下面断点可以看到,globals中以字典的方式存放了AdminScope、UserScope这两个类,所以scope = globals()[scope]()即可。

image.png
上一篇下一篇

猜你喜欢

热点阅读