Tuesday, September 10, 2019

Example Python Decorator

ex.1
====

from functools import wraps

from flask import request, jsonify

def token_admin_required(f):
    @wraps(f)
    def decorated(*agrs, **kwagrs):

        token = None

        if 'X-API-KEY' in request.headers:
            token = request.headers['X-API-KEY']

        if not token:
            return jsonify({'message': 'Token is missing.'})

        if token != 'token-key':
            return jsonify({'message': 'Your Token is Wrong or Invalid'})

       # check token
        # print('TOKEN: {}'.format(token) )
        return f(*agrs, **kwagrs)

    return decorated

ex.2
====

import time
import datetime


def decorators(f):
    def wrappers(*args, **kwargs):
        print('Before')
        ret = f(*args, **kwargs)
        print('After')
        return ret
    return wrappers


def timer(f):
    def wrappers(*args, **kwargs):
        before = time.time()
        ret = f(*args, **kwargs)
        print("Function took: ", time.time() - before, "second")
        return ret
    return wrappers


def logger(func):
    def wrappers(*args, **kwargs):
        with open('log.txt', 'a') as f:
            f.write("called function with " + " ".join(
                [str(arg) for arg in args]) + " at " + str(datetime.datetime.now()) + "\n")
            ret = func(*args, **kwargs)
            return ret
    return wrappers


@logger
def add(a, b):
    return a + b


print(add(3, 4))




1 comment:

Note: Only a member of this blog may post a comment.

ALCATEL 6900

write memory copy running certified reload from working no rollback-timeout