3

複数のHTTP(GET、POST、PUT、DELETE)メソッドを持つ同じURLを取得しようとしていますが、メソッドごとにフラスコ認証を使用した異なる認証があります。

私はクラスのようなもの以上を作成しようとしました

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')

4

2 に答える 2

6

私が見ることができる唯一の合理的なオプションは、Flask-RESTful のResourceクラスのサブクラスを作成し、メソッドごとのデコレータを自分で実装することです。その後、リソースはクラスから継承して、この機能を持つことができます。

Resourceサブクラスでは、メソッドの代替実装を提供する必要があります: dispatch_requesthttps://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')
于 2015-03-10T17:00:32.277 に答える
3

これもできることがわかった

class User(Resource):


    @Admin.auth.login_required
    def post(self):
        '''..etc'''
    @Users.auth.login_required
    def get(self):
        '''..etc'''
于 2015-03-10T22:11:39.567 に答える