Создать декоратор для обработки проверки токена в колбе - PullRequest
0 голосов
/ 10 октября 2019

В моем файле Python службы фляги определены две конечные точки.

  1. Первая конечная точка возвращает список родительских и дочерних узлов из файла mmap json, который она анализирует.
  2. Вторая конечная точка возвращает определенное дочернее поле из файла mmap json, который она анализирует.

Каждая из этих конечных точек может использоваться только после проверки токена. Таким образом, у меня есть следующие реализации:

from flask import request
import requests

def check_token(self):
   # Method to verify the token from the another python Service
   token_header = request.headers['authorization']
   # Remove the 'Basic" part from the token
   auth_token = token_header.split(maxsplit=1)[1]
   self.__payload = {'token' : auth_token} 
   # Append the token to the header by using the payload
   response = requests.get(self.__url, params=self.__payload, verify=False)
   return response

# 1. This endpoint returns a list of parent and child nodes from a mmap json file which it parses.
class SystemList(Resource):

   def get(self, systemname):
      token = check_token()
      if token.ok:
         # Open the mmap file, parse it, and jsonify the result and return it
      # Invalid token present
      else:
           return make_response(
                jsonify("Invalid access as token invalid.")
            )

# 2. The endpoint returns a specific child field from a mmap json file which it parses.
class SystemChildList(Resource):

   def get(self, systemname, id):
      token = check_token()
      if token.ok:
         # Open the mmap file, parse it, and jsonify the result and return it
      # Invalid token present
      else:
           return make_response(
                jsonify("Invalid access as token invalid.")
            )  

Проблема, с которой я столкнулся, заключается в том, что я хочу использовать декоратор для обработки проверки токена.

Я хочу иметь возможность добавить его перед методом get(), например, следующим:

@validatetoken
    def get(self, designation):
       # I am not sure what goes here and what do I need to put here?
       # I want to be able to have one decorator for both of the SystemList and SystemChildList 
       # resource shown above.

Я не уверен в том, что происходит в декораторе. Я действительно новичок в этих понятиях. Любая помощь приветствуется.

1 Ответ

0 голосов
/ 10 октября 2019

Вы можете использовать параметр method_decorators , чтобы достичь

try,

from flask import request
from functools import wraps
import requests

def check_token(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token_header = request.headers['authorization']
        # Remove the 'Basic" part from the token
        auth_token = token_header.split(maxsplit=1)[1]
        __url = "url_for_token_validation"
        __payload = {'token' : auth_token} 
        # Append the token to the header by using the payload
        response = requests.get(__url, params=__payload, verify=False)
        if response.status_code != requests.codes.ok:
            return make_response(
                jsonify("Invalid access as token invalid.")
            )
        return f(*args, **kwargs)
    return decorated


# 1. This endpoint returns a list of parent and child nodes from a mmap json file which it parses.
class SystemList(Resource):
    @check_token
    def get(self, systemname):
        # Open the mmap file, parse it, and jsonify the result and return it

# 2. The endpoint returns a specific child field from a mmap json file which it parses.
class SystemChildList(Resource):
    @check_token
    def get(self, systemname, id):
        # Open the mmap file, parse it, and jsonify the result and return it
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...