python-decorators

python decorator arguments with @ syntax

南笙酒味 提交于 2019-12-12 10:39:37
问题 I'm trying to use a cached property decorator that can take arguments. I looked at this implementation: http://www.daniweb.com/software-development/python/code/217241/a-cached-property-decorator from functools import update_wrapper def cachedProperty (func ,name =None ): if name is None : name =func .__name__ def _get (self ): try : return self .__dict__ [name ] except KeyError : value =func (self ) self .__dict__ [name ]=value return value update_wrapper (_get ,func ) def _del (self ): self

Authentication via decorators in Flask

别来无恙 提交于 2019-12-12 10:24:15
问题 I have the following code which works. It authenticates admin users for the given url. If the users is not Admin then it returns a 401. Snippet 1: __author__ = 'xxxx' from flask import render_template, url_for from flask import Blueprint, redirect, request, session, abort from google.appengine.api import users admin_routes = Blueprint('admin_routes', __name__) @admin_routes.route('/xxxx') def basic(): user = users.get_current_user() if user: if not users.is_current_user_admin(): return abort

Flask: why app.route() decorator, should always be the outermost?

放肆的年华 提交于 2019-12-12 09:28:44
问题 Say, I have a hand-crafted @login-required decorator: from functools import wraps def login_required(decorated_function): """Decorator to check if user is logged in.""" @wraps(decorated_function) def wrapper(*args, **kwargs): if False: # just to check it's working return decorated_function(*args, **kwargs) else: flash('You need to login, to access this page') return redirect(url_for('login')) return wrapper and a function, decorated with @app.route() and @login_required ( endpoint for login

Python timeout decorator

一世执手 提交于 2019-12-12 08:12:49
问题 I'm using the code solution mentioned here. I'm new to decorators, and don't understand why this solution doesn't work if I want to write something like the following: @timeout(10) def main_func(): nested_func() while True: continue @timeout(5) def nested_func(): print "finished doing nothing" => Result of this will be no timeout at all. We will be stuck on endless loop. However if I remove @timeout annotation from nested_func I get a timeout error. For some reason we can't use decorator on

Passing default arguments to a decorator in python

廉价感情. 提交于 2019-12-12 07:28:06
问题 I am trying to find a way to pass my functions default arguments to the decorator. I have to say I am fairly new to the decorator business, so maybe I just don't understand it properly, but I have not found any answers yet. So here my modified example from the python functools.wraps manual page. from functools import wraps def my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print 'Calling decorated function' print 'args:', args print 'kwargs:', kwds return f(*args, **kwds) return

Accessing original decorated function for test purposes

只愿长相守 提交于 2019-12-12 07:22:33
问题 I'm using a decorator( @render_to from the django_annoying package) in a view function. But the thing is that I wanted to get the original dict that is returned by the view function for test purposes, instead of the HttpResponse object that the decorator returns. The decorator uses @wraps (from functools ). If there is no way to access this, then do you have any idea of how to test this? 回答1: The wrapped function will be available as a function closure cell. Which cell exactly depends on how

How can I send unknown list of arguments to a python decorator — when the decorator is a method of a different class?

∥☆過路亽.° 提交于 2019-12-12 04:47:05
问题 This question is related to another question I just asked. I have created a python decorator as shown below. I want this decorator to accept an unknown list of arguments. But there is an added wrinkle. The decorator is an instance method of another class: #!/usr/bin/env python from functools import wraps class A: def my_decorator(self, func=None, **kwargs): def inner_function(decorated_function): def wrapped_func(*fargs, **fkwargs): print kwargs return decorated_function(*fargs, **fkwargs)

real-time decorator for functions and generators

泄露秘密 提交于 2019-12-11 17:44:26
问题 I have a situation in which I need to hook certain functions so that I can inspect the return values and track them. This is useful for tracking for example running averages of values returned by methods/functions. However, these methods/function can also be generators. However, if i'm not wrong, python detects generators when parsing and when the function is called at runtime it always returns a generator. Thus I can't simply do something like: import types def decorator(func): average =

How to wrap these decorated functions into a class?

。_饼干妹妹 提交于 2019-12-11 17:03:20
问题 I am attempting to wrap V2 of the Slack API into a class so that I can keep information about my bot encapsulated. Here is one of their example snippets: import slack slack_token = os.environ["SLACK_API_TOKEN"] rtmclient = slack.RTMClient(token=slack_token) @slack.RTMClient.run_on(event='message') def say_hello(**payload): data = payload['data'] if 'Hello' in data['text']: channel_id = data['channel'] thread_ts = data['ts'] user = data['user'] webclient = payload['web_client'] webclient.chat

Why is my decorator breaking for this Flask-Login endpoint?

若如初见. 提交于 2019-12-11 13:03:26
问题 I've figured out how to make Flask-Login authenticate a user based on an LDAP lookup. Now I'd like to add some authorization to the mix - that is, only allow access to certain endpoints if a user has both logged in and belongs to the right groups. I'm not sure if this is the right way to do it, but I thought I could just add a decoration to an endpoint: @app.route('/top_secret') @authorize @login_required def top_secret(): return render_template("top_secret.html") and (for now) make a