python-decorators

How to write Flask decorator with request?

痞子三分冷 提交于 2019-11-30 13:37:54
I am not sure why following decorator[validate_request] doesn't work. What is correct way to write such validation decorator? def validate_request(req_type): if req_type is 'json' and not request.json: abort(400) def decorator(func): @functools.wraps(func) def wrapped_func(*args, **kwargs): return func(*args, **kwargs) return wrapped_func return decorator @app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['PUT']) @validate_request('json') @json def update_task(task_id): # task = filter(lambda t: t['id'] == task_id, tasks) task = [task for task in tasks if task['id'] == task_id] if len

decorator to set attributes of function

老子叫甜甜 提交于 2019-11-30 13:28:49
I want different functions to be executable only if the logged in user has the required permission level. To make my life more complexly simply I want to use decorators. Below I attempy to set attribute permission on 'decorated' functions - as shown below. def permission(permission_required): def wrapper(func): def inner(*args, **kwargs): setattr(func, 'permission_required', permission_required) return func(*args, **kwargs) return inner return wrapper @permission('user') def do_x(arg1, arg2): ... @permission('admin') def do_y(arg1, arg2): ... But when I do: fn = do_x if logged_in_user.access

Applying a decorator to an imported function?

自古美人都是妖i 提交于 2019-11-30 04:36:42
I want to import a function: from random import randint and then apply a decorator to it: @decorator randint I was wondering if there was some syntactic sugar for this (like what I have above), or do I have to do it as follows: @decorator def randintWrapper(*args): return random.randint(*args) Decorators are just syntactic sugar to replace a function object with a decorated version, where decorating is just calling (passing in the original function object). In other words, the syntax: @decorator_expression def function_name(): # function body roughly (*) translates to: def function_name(): #

How to Make Decorators Optionally Turn On Or Off

旧时模样 提交于 2019-11-29 23:27:58
问题 I am asking, given a function with a decorator, is it possible to run the function without invoking the decorator call? Given a function foo , is it possible to optionally Turn On or Off a decorator on it? Given @decorator def foo(): //do_somthing Is it possible run foo with decorator Turned Off? There may exist some function where you may wish to run it with or without the decorator. For example(and not a good one, since it involves efficient caching) turn off decorator based caching in a

Flask: Decorator to verify JSON and JSON Schema

自作多情 提交于 2019-11-29 21:52:56
I have a flask application with calls expecting JSON payload. Before each call is processed, I have a 2-step error checking process: Assert that the payload is a valid JSON Assert that the JSON payload complies with a specific schema Which is implemented in the following fashion: @app.route('/activate', methods=['POST']) def activate(): request_id = request.__hash__() # Assert that the payload is a valid JSON try: input = request.json except BadRequest, e: msg = "payload must be a valid json" return jsonify({"error": msg}), 400 # JSON Schema Validation try: validate(request.json, app.config[

decorator to set attributes of function

爷,独闯天下 提交于 2019-11-29 19:06:37
问题 I want different functions to be executable only if the logged in user has the required permission level. To make my life more complexly simply I want to use decorators. Below I attempy to set attribute permission on 'decorated' functions - as shown below. def permission(permission_required): def wrapper(func): def inner(*args, **kwargs): setattr(func, 'permission_required', permission_required) return func(*args, **kwargs) return inner return wrapper @permission('user') def do_x(arg1, arg2):

How to write Flask decorator with request?

佐手、 提交于 2019-11-29 18:42:36
问题 I am not sure why following decorator[validate_request] doesn't work. What is correct way to write such validation decorator? def validate_request(req_type): if req_type is 'json' and not request.json: abort(400) def decorator(func): @functools.wraps(func) def wrapped_func(*args, **kwargs): return func(*args, **kwargs) return wrapped_func return decorator @app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['PUT']) @validate_request('json') @json def update_task(task_id): # task = filter

How can I decorate all functions imported from a file?

泪湿孤枕 提交于 2019-11-29 11:31:01
I have created many functions that are divided into different files, now I would like to apply the same decorator for all of them without modifying the files and without applying the decorators one by one. I have tried to use this explanation written by delnan, but I got no success for imported functions. About the decorator, it must update a list every time a function within a class is executexecuted with the function arguments and values, just like this other question I asked. Any suggestions to help me with this issue? Thanks A little bit of introspection ( dir() ) and dynamic look-up with

How to get source code of function that is wrapped by a decorator?

北慕城南 提交于 2019-11-29 09:41:23
问题 I wanted to print the source code for my_func , that is wrapped by my_decorator : import inspect from functools import wraps def my_decorator(some_function): @wraps(some_function) def wrapper(): some_function() return wrapper @my_decorator def my_func(): print "supposed to return this instead!" return print inspect.getsource(my_func) However, it returns source for wrapper instead: @wraps(some_function) def wrapper(): some_function() Is there a way for it to print the following instead? def my

How can one attach a decorator to a function “after the fact” in python?

半城伤御伤魂 提交于 2019-11-29 02:08:25
The way I understand decorators of function in python (and I might be wrong), is that they are supposed to add side effects and modify the return value of a function. Now decorators are added above the function definition of the function to be decorated or by an assignment. Here is a small example: def print_args_decor(function): def wrapper(*args, **kwargs): print 'Arguments:', args, kwargs # Added side-effect return function(*args, **kwargs)*5 # Modified return value return wrapper @print_args_decor def do_stuff(strg, n=10): """Repeats strg a few times.""" return strg * n new_decorated_func