如何在Flask中使用login_required和一个类? [英] How to use login_required with a class, in Flask?

查看:645
本文介绍了如何在Flask中使用login_required和一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  from flask_login import login_required $ b $ from flask_restful import资源

@所需的登录
类MyClass(资源):
# ...

在主文件中,我调用类的方法:

  api.add_resource(MyClass,'/ some_url',methods = ['GET','PUT','POST','DELETE'])

我想我正在使用 @login_required 在这里,因为我得到错误
AttributeError:'function'object has no attribute'as_view'



所以我假设 @login_required 只能用于函数。有没有一种方法将其与一个类合并?

解决方案

您可以给它应该运行的装饰器:

$ p $ class MyClass(Resource):
decorators = [login_required]


from flask_login import login_required
from flask_restful import Resource

@login required
class MyClass(Resource):
    #...

In the main file I call the class's methods like:

api.add_resource(MyClass, '/some_url', methods=['GET', 'PUT', 'POST', 'DELETE'])

I think I am using @login_required the wrong way here, since I get the error AttributeError: 'function' object has no attribute 'as_view'

So I am assuiming that @login_required can only be used with functions. Is there a way to incorporate it with a class?

解决方案

you could give the class the decorators it should run :

class MyClass(Resource):
    decorators = [login_required]

这篇关于如何在Flask中使用login_required和一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆