有時候在開發一些 API 時,會需要經過驗證的步驟,例如在 cookie 或是 request 當中帶入一個 access token 以進行驗證,這編寫了一個簡單的例子可供參考。

import json
def access_token_required(handler):

    def warped_handler(req):
        if 'access_token' not in req.query_params:
            return HTTPResponse(
                json.dumps({'err': True, 'msg': 'Url should contains access_token'}),
                status=400,
                content_type='application/json'
            )

        access_token = req.query_params['access_token']
        # check your access token here!

        if access_token != 'correct token':
            return Response(
                json.dumps({'err': True, 'msg': 'Invalid access token'}),
                status=400,
                content_type='application/json'
            )

        handler(req)

    return warped_handler

接下來指需要在處理 request 的函式上面加上這個修飾器(Decorator)即可!

@access_token_required
def my_request_handler(request):
    # handling response with valid access token...

Share Your Thought