美文网首页
flask中如何通过类的名字得到类的对象

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

作者: python与数据分析 | 来源:发表于2019-08-21 18:15 被阅读0次

    出错 :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

    相关文章

      网友评论

          本文标题:flask中如何通过类的名字得到类的对象

          本文链接:https://www.haomeiwen.com/subject/gfvtjctx.html