gpt4 book ai didi

python-2.7 - 带有 flask 身份验证 :multiple HTTP method with different authentication 的 flask Restful

转载 作者:行者123 更新时间:2023-12-03 15:57:06 27 4
gpt4 key购买 nike

我正在尝试使用具有多个 HTTP(GET、POST、PUT、DELETE)方法的相同 url,并且对于每种方法,它使用 flask-auth 进行不同的身份验证。

我尝试创建的不仅仅是类

class GetUser(Resource):


decorators = [Users.auth.login_required]
def get(self):
'''..etc'''

class PostUser(Resource):


decorators = [Admin.auth.login_required]
def post(self):
'''..etc'''

restful_api.add_resource(GetUser,'/User')
restful_api.add_resource(PostUser,'/User')

但发生的事情是 restful_api.add_resource(PostUser,'/User') 将覆盖 restful_api.add_resource(GetUser,'/User')

最佳答案

我能看到的唯一合理的选择是您创建 Flask-RESTful 的 Resource 类的子类并自己实现 per-method 装饰器。然后你的资源可以从你的类继承来拥有这个功能。

在您的 Resource 子类中,您需要提供 dispatch_request 方法的替代实现:https://github.com/flask-restful/flask-restful/blob/master/flask_restful/init.py#L543 .

处理装饰器的代码是这样的:

    for decorator in self.method_decorators:
meth = decorator(meth)

我猜你可以把 method_decorators 改成字典,然后按如下方式应用装饰器:

    for decorator in self.method_decorators[request.method.lower()]:
meth = decorator(meth)

那么你上面的例子就变成了:

class User(MyResource):
method_decorators = {
'get': [Users.auth.login_required],
'post': [Admin.auth.login_required]
}

def get(self):
'''..etc'''

def post(self):
'''..etc'''

restful_api.add_resource(User,'/User')

关于python-2.7 - 带有 flask 身份验证 :multiple HTTP method with different authentication 的 flask Restful ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28961824/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com