text
stringlengths
0
1.05M
meta
dict
from functools import wraps def lazy(func): def lazy_func(self, *args, **kwargs): cached_attribute = '_cached' if not hasattr(self, cached_attribute): setattr(self, cached_attribute, {}) if func.__name__ not in getattr(self, cached_attribute): getattr(self, cached_attribute)[func.__name__] = func( self, *args, **kwargs) return getattr(self, cached_attribute)[func.__name__] return wraps(func)(lazy_func) def memoize(func): def wrapper(self, *args, **kwargs): mem_args = kwargs.items() mem_args += ('args', args) mem_args = tuple(mem_args) memoized_attribute = '_memoized' if not hasattr(self, memoized_attribute): setattr(self, memoized_attribute, {}) memoized_cache = getattr(self, memoized_attribute) memoized_key = func.__name__ memoized_cache.setdefault(memoized_key, {}) if mem_args not in memoized_cache[memoized_key]: result = func(self, *args, **kwargs) memoized_cache[memoized_key][mem_args] = result return memoized_cache[memoized_key][mem_args] return wraps(func)(wrapper)
{ "repo_name": "bueda/django-comrade", "path": "comrade/functional.py", "copies": "1", "size": "1199", "license": "mit", "hash": -4100328486929083000, "line_mean": 36.46875, "line_max": 66, "alpha_frac": 0.6021684737, "autogenerated": false, "ratio": 3.892857142857143, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9985259991557143, "avg_score": 0.001953125, "num_lines": 32 }
from functools import wraps def logit(logfile='out.log'): def logging_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): log_string = func.__name__ + " was called" print(log_string) # Open the logfile and append with open(logfile, 'a') as opened_file: # Now we log to the specified logfile opened_file.write(log_string + '\n') return wrapped_function return logging_decorator @logit() def myfunc1(): pass myfunc1() # Output: myfunc1 was called # A file called out.log now exists, with the above string @logit(logfile='func2.log') def myfunc2(): pass myfunc2() # Output: myfunc2 was called # A file called func2.log now exists, with the above string #class way # class logit(object): # def __init__(self, logfile='out.log'): # self.logfile = logfile # def __call__(self, func): # log_string = func.__name__ + " was called" # print(log_string) # # Open the logfile and append # with open(self.logfile, 'a') as opened_file: # # Now we log to the specified logfile # opened_file.write(log_string + '\n') # # Now, send a notification # self.notify() # def notify(self): # # logit only logs, no more # pass # @logit() # def myfunc1(): # pass # class email_logit(logit): # ''' # A logit implementation for sending emails to admins # when the function is called. # ''' # def __init__(self, email='admin@myproject.com', *args, **kwargs): # self.email = email # super(email_logit, self).__init__(*args, **kwargs) # def notify(self): # # Send an email to self.email # # Will not be implemented here # pass
{ "repo_name": "mndarren/Code-Lib", "path": "Python_lib/pythonPractice/logDecorator.py", "copies": "1", "size": "1819", "license": "apache-2.0", "hash": 8411436289181679000, "line_mean": 26.1641791045, "line_max": 71, "alpha_frac": 0.5766904893, "autogenerated": false, "ratio": 3.4846743295019156, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45613648188019157, "avg_score": null, "num_lines": null }
from functools import wraps def memoize(func, cache, num_args): """ Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be usable as dictionary keys. Only the first num_args are considered when creating the key. """ def wrapper(*args): mem_args = args[:num_args] if mem_args in cache: return cache[mem_args] result = func(*args) cache[mem_args] = result return result return wraps(func)(wrapper) class Promise(object): """ This is just a base class for the proxy class created in the closure of the lazy function. It can be used to recognize promises in code. """ pass def lazy(func, *resultclasses): """ Turns any callable into a lazy evaluated callable. You need to give result classes or types -- at least one is needed so that the automatic forcing of the lazy evaluation code is triggered. Results are not memoized; the function is evaluated on every access. """ class __proxy__(Promise): """ Encapsulate a function call and act as a proxy for methods that are called on the result of that function. The function is not evaluated until one of the methods on the result is called. """ __dispatch = None def __init__(self, args, kw): self.__func = func self.__args = args self.__kw = kw if self.__dispatch is None: self.__prepare_class__() def __reduce__(self): return ( _lazy_proxy_unpickle, (self.__func, self.__args, self.__kw) + resultclasses ) def __prepare_class__(cls): cls.__dispatch = {} for resultclass in resultclasses: cls.__dispatch[resultclass] = {} for (k, v) in resultclass.__dict__.items(): # All __promise__ return the same wrapper method, but they # also do setup, inserting the method into the dispatch # dict. meth = cls.__promise__(resultclass, k, v) if hasattr(cls, k): continue setattr(cls, k, meth) cls._delegate_str = str in resultclasses cls._delegate_unicode = unicode in resultclasses assert not (cls._delegate_str and cls._delegate_unicode), "Cannot call lazy() with both str and unicode return types." if cls._delegate_unicode: cls.__unicode__ = cls.__unicode_cast elif cls._delegate_str: cls.__str__ = cls.__str_cast __prepare_class__ = classmethod(__prepare_class__) def __promise__(cls, klass, funcname, func): # Builds a wrapper around some magic method and registers that magic # method for the given type and method name. def __wrapper__(self, *args, **kw): # Automatically triggers the evaluation of a lazy value and # applies the given magic method of the result type. res = self.__func(*self.__args, **self.__kw) for t in type(res).mro(): if t in self.__dispatch: return self.__dispatch[t][funcname](res, *args, **kw) raise TypeError("Lazy object returned unexpected type.") if klass not in cls.__dispatch: cls.__dispatch[klass] = {} cls.__dispatch[klass][funcname] = func return __wrapper__ __promise__ = classmethod(__promise__) def __unicode_cast(self): return self.__func(*self.__args, **self.__kw) def __str_cast(self): return str(self.__func(*self.__args, **self.__kw)) def __cmp__(self, rhs): if self._delegate_str: s = str(self.__func(*self.__args, **self.__kw)) elif self._delegate_unicode: s = unicode(self.__func(*self.__args, **self.__kw)) else: s = self.__func(*self.__args, **self.__kw) if isinstance(rhs, Promise): return -cmp(rhs, s) else: return cmp(s, rhs) def __mod__(self, rhs): if self._delegate_str: return str(self) % rhs elif self._delegate_unicode: return unicode(self) % rhs else: raise AssertionError('__mod__ not supported for non-string types') def __deepcopy__(self, memo): # Instances of this class are effectively immutable. It's just a # collection of functions. So we don't need to do anything # complicated for copying. memo[id(self)] = self return self def __wrapper__(*args, **kw): # Creates the proxy object, instead of the actual value. return __proxy__(args, kw) return wraps(func)(__wrapper__) def _lazy_proxy_unpickle(func, args, kwargs, *resultclasses): return lazy(func, *resultclasses)(*args, **kwargs) def allow_lazy(func, *resultclasses): """ A decorator that allows a function to be called with one or more lazy arguments. If none of the args are lazy, the function is evaluated immediately, otherwise a __proxy__ is returned that will evaluate the function when needed. """ def wrapper(*args, **kwargs): for arg in list(args) + kwargs.values(): if isinstance(arg, Promise): break else: return func(*args, **kwargs) return lazy(func, *resultclasses)(*args, **kwargs) return wraps(func)(wrapper) class LazyObject(object): """ A wrapper for another class that can be used to delay instantiation of the wrapped class. By subclassing, you have the opportunity to intercept and alter the instantiation. If you don't need to do that, use SimpleLazyObject. """ def __init__(self): self._wrapped = None def __getattr__(self, name): if self._wrapped is None: self._setup() return getattr(self._wrapped, name) def __setattr__(self, name, value): if name == "_wrapped": # Assign to __dict__ to avoid infinite __setattr__ loops. self.__dict__["_wrapped"] = value else: if self._wrapped is None: self._setup() setattr(self._wrapped, name, value) def __delattr__(self, name): if name == "_wrapped": raise TypeError("can't delete _wrapped.") if self._wrapped is None: self._setup() delattr(self._wrapped, name) def _setup(self): """ Must be implemented by subclasses to initialise the wrapped object. """ raise NotImplementedError # introspection support: __members__ = property(lambda self: self.__dir__()) def __dir__(self): if self._wrapped is None: self._setup() return dir(self._wrapped) class SimpleLazyObject(LazyObject): """ A lazy object initialised from any function. Designed for compound objects of unknown type. For builtins or objects of known type, use django.utils.functional.lazy. """ def __init__(self, func): """ Pass in a callable that returns the object to be wrapped. If copies are made of the resulting SimpleLazyObject, which can happen in various circumstances within Django, then you must ensure that the callable can be safely run more than once and will return the same value. """ self.__dict__['_setupfunc'] = func # For some reason, we have to inline LazyObject.__init__ here to avoid # recursion self._wrapped = None def __str__(self): if self._wrapped is None: self._setup() return str(self._wrapped) def __unicode__(self): if self._wrapped is None: self._setup() return unicode(self._wrapped) def __deepcopy__(self, memo): if self._wrapped is None: # We have to use SimpleLazyObject, not self.__class__, because the # latter is proxied. result = SimpleLazyObject(self._setupfunc) memo[id(self)] = result return result else: # Changed to use deepcopy from copycompat, instead of copy # For Python 2.4. from django.utils.copycompat import deepcopy return deepcopy(self._wrapped, memo) # Need to pretend to be the wrapped class, for the sake of objects that care # about this (especially in equality tests) def __get_class(self): if self._wrapped is None: self._setup() return self._wrapped.__class__ __class__ = property(__get_class) def __eq__(self, other): if self._wrapped is None: self._setup() return self._wrapped == other def __hash__(self): if self._wrapped is None: self._setup() return hash(self._wrapped) def _setup(self): self._wrapped = self._setupfunc()
{ "repo_name": "strogo/djpcms", "path": "djpcms/utils/functional.py", "copies": "1", "size": "9253", "license": "bsd-3-clause", "hash": 8467806824284121000, "line_mean": 34.5884615385, "line_max": 130, "alpha_frac": 0.5643575057, "autogenerated": false, "ratio": 4.540235525024534, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0012060505752652816, "num_lines": 260 }
from functools import wraps def refresh(func): """ Decorator that can be applied to model method that forces a refresh of the model. Note this decorator ensures the state of the model is what is currently within the database and therefore overwrites any current field changes. For example, assume we have the following model: .. code-block:: python class MyModel(models.Model): counter = models.IntegerField() @refresh def my_method(self): print counter Then the following is performed: .. code-block:: python i = MyModel.objects.create(counter=1) i.counter = 3 i.my_method() # prints 1 This behavior is useful in a distributed system, such as celery, where "asserting the world is the responsibility of the task" - see http://celery.readthedocs.org/en/latest/userguide/tasks.html?highlight=model#state Note that the refresh of the model uses the approach outlined in https://github.com/planop/django/blob/ticket_901/django/db/models/base.py#L1012 which was discovered after from https://code.djangoproject.com/ticket/901#comment:29 which is a Django ticket which discusses a specific method 'refresh' on a model. """ @wraps(func) def inner(self, *args, **kwargs): # Refresh the model instance - see https://github.com/planop/django/blob/ticket_901/django/db/models/base.py#L1012 new_self = self.__class__._base_manager.using(self._state.db).get(pk=self.pk) for f in self.__class__._meta.fields: setattr(self, f.name, getattr(new_self, f.name)) return func(self, *args, **kwargs) return inner
{ "repo_name": "alexhayes/django-toolkit", "path": "django_toolkit/models/decorators.py", "copies": "1", "size": "1770", "license": "mit", "hash": -3963672083450451000, "line_mean": 37.5, "line_max": 148, "alpha_frac": 0.6502824859, "autogenerated": false, "ratio": 4.154929577464789, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5305212063364788, "avg_score": null, "num_lines": null }
from functools import wraps def setupmethod(f): """Use this decorator for methods that change the internal state / parameters of the system, such that the eigenstates have to be recalculated. This method will reset the 'data was changed' flag""" @wraps(f) def decorated(self, *ops, **kwops): if self.ready: self.makeNotReady() return f(self, *ops, **kwops) return decorated def buildmethod(f): """Use this decorator for methods that only need to be run once for a certain set of parameters. This method will only be run if data was changed. The 'data was changed' flag will remain unchanged.""" @wraps(f) def decorated(self, *ops, **kwops): if not self.ready: return f(self, *ops, **kwops) return decorated def resultmethod(f): """Use this decorator for methods that use the eigenstates to calculate their resutls. This method will make the system ready and set the 'data was changed'""" @wraps(f) def decorated(self, *ops, **kwops): self.makeReady() return f(self, *ops, **kwops) return decorated class SetupClass: """A class for building object trees, where a change to a leaf leads to a change in all parent nodes up to the root. The change is normally postponed to avoid repeated cascading update propagation until access to the state-dependent data of a parent node is required. The instance variable *ready* is used to indicate pending updates. Changes to this variable should be made through instance methods `makeReady()` and `makeNotReady()`. Subclasses should implement the `_build()` method that updates the object state as necessary based on children state. """ def __init__(self, parent=None): self.ready = False self.parent = parent def makeReady(self): """Ensures that the object state is up-to-date. Will call `_build()` if necessary. """ if not self.ready: self._build() self.ready = True def makeNotReady(self): """Sets 'update pending' status for this node and all parent nodes. """ self.ready = False if self.parent is not None: self.parent.makeNotReady()
{ "repo_name": "TimofeyBalashov/MagnetizationTunneling", "path": "pyatoms/core/Setup.py", "copies": "1", "size": "2338", "license": "mit", "hash": 7895009785695639000, "line_mean": 30.5945945946, "line_max": 81, "alpha_frac": 0.6398631309, "autogenerated": false, "ratio": 4.321626617375231, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5461489748275231, "avg_score": null, "num_lines": null }
from functools import wraps def timecached(func): """ Décorateur permettant d'associer un cache à la fonction `func` : - la première fois que `func` est appelée, le résultat qu'elle renvoie est stocké dans le cache ; - par la suite, lorsque `func` est appelée de nouveau, c'est le résultat stocké dans le cache qui est renvoyé, sans qu'il soit nécessaire de recalculer `func`. Le cache est indexé sur les dates ; par conséquent, le premier argument de `func` doit représenter une date. Par ailleurs, `func` doit être une méthode d'un objet disposant d'un membre `cache` implémentant le cache en lui-même. """ @wraps(func) # Pour préserver la docstring et le nom de `func`. def wrapper(self, date, *args): currdate = self.cache.currentdate if currdate is not None and date != currdate: self.cache.flush() # Nettoyage du cache key = self.cache.makekey(func, date, *args) if key not in self.cache.keys: res = func(self, date, *args) self.cache.register(date, key, res) return self.cache.get(key) return wrapper class DateCache: "Cache indexé sur le temps." def __init__(self): """ Initialise une nouvelle instance de la classe `DateCache`. """ #FIXME: implémenter les méthodes nécessaires pour que le cache puisse # être utilisé exactement comme un dictionnaire ? self._prevdata = {} self._currdata = {} self.currentdate = None @property def keys(self): "Ensemble des clefs enregistrées dans le cache." return self._currdata.keys() def makekey(self, func, date, *args): """ Renvoie la clef utilisée pour stocker le résultat du calcul `func(date, *args)`. """ return (func.__name__,) + args def register(self, date, key, value): """ Enregistre une valeur dans le cache. Paramètres : ------------ date Date pour laquelle stocker `value`. key Clef associée à `value`. value Valeur à stocker. """ if self.currentdate is None: self.currentdate = date elif self.currentdate != date: raise ValueError("DateCache is meant to store data "\ "for only one date at at time.") self._currdata[key] = value def get(self, key): "Renvoie la valeur associée à la clef `key`." return self._currdata[key] def getprev(self, funcname, *args): """ Renvoie la dernière valeur sauvegardée dans le cache pour la méthode correspondant à `funcname` avec les arguments `*args`. """ #FIXME: le `getprev` n'est pas très naturel... key = (funcname,) + args if key in self._prevdata.keys(): return self._prevdata[key] raise KeyError("%s not in cache." % str(key)) def flush(self): "Nettoie le cache." for key, value in self._currdata.items(): # On écrase une éventuelle valeur existante. self._prevdata[key] = (self.currentdate, value) self._currdata = {} self.currentdate = None
{ "repo_name": "latour-a/efficientmc", "path": "efficientmc/utils.py", "copies": "1", "size": "3319", "license": "mit", "hash": 940781977440465400, "line_mean": 33.5052631579, "line_max": 77, "alpha_frac": 0.5918242831, "autogenerated": false, "ratio": 3.4505263157894737, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4542350598889474, "avg_score": null, "num_lines": null }
from functools import wraps def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) ... from django.contrib.auth.views \ import redirect_to_login return redirect_to_login( path, login_url, redirect_field_name) return _wrapped_view return decorator def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): actual_decorator = user_passes_test( lambda u: u.is_authenticated(), login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator @login_required def top_secret_view(request, bunker_id, document_id): ... @login_required(login_url="/super_secret/login") def super_top_secret_view(request, bunker_id, document_id): ...
{ "repo_name": "AnthonyBriggs/Python-101", "path": "hello_python_source_py3/chapter 07/user_passes_test.py", "copies": "2", "size": "1242", "license": "mit", "hash": -4778184909556162000, "line_mean": 30.05, "line_max": 59, "alpha_frac": 0.5982286634, "autogenerated": false, "ratio": 3.917981072555205, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.05382720392130834, "num_lines": 40 }
from functools import wraps def validate_params(valid_options, params): """ Helps us validate the parameters for the request :param valid_options: a list of strings of valid options for the api request :param params: a dict, the key-value store which we really only care about the key which has tells us what the user is using for the API request :returns: None or throws an exception if the validation fails """ #crazy little if statement hanging by himself :( if not params: return #We only allow one version of the data parameter to be passed data_filter = ['data', 'source', 'external_url', 'embed'] multiple_data = [key for key in params.keys() if key in data_filter] if len(multiple_data) > 1: raise Exception("You can't mix and match data parameters") #No bad fields which are not in valid options can pass disallowed_fields = [key for key in params.keys() if key not in valid_options] if disallowed_fields: field_strings = ",".join(disallowed_fields) raise Exception("{0} are not allowed fields".format(field_strings)) def validate_blogname(fn): """ Decorator to validate the blogname and let you pass in a blogname like: client.blog_info('codingjester') or client.blog_info('codingjester.tumblr.com') or client.blog_info('blog.johnbunting.me') and query all the same blog. """ @wraps(fn) def add_dot_tumblr(*args, **kwargs): if (len(args) > 1 and ("." not in args[1])): args = list(args) args[1] += ".tumblr.com" return fn(*args, **kwargs) return add_dot_tumblr
{ "repo_name": "gcd0318/pytumblr", "path": "pytumblr/helpers.py", "copies": "7", "size": "1734", "license": "apache-2.0", "hash": 9012486638342097000, "line_mean": 35.125, "line_max": 82, "alpha_frac": 0.6320645905, "autogenerated": false, "ratio": 3.949886104783599, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8081950695283598, "avg_score": null, "num_lines": null }
from functools import wraps DO = 1 SEND = 2 CALL = 3 RETURN = 4 TRY = 5 LOOP = 6 GET_STATE = 7 GLOBAL = "__GLOBAL__" DONT_RETURN = "__DONT_RETURN__" def workflow(f): @wraps(f) def _workflow(*args, **kwargs): state = {} excepts = {} global send_command, send send = None send_command = None def process(command, value): global send_command, send if command == SEND: send = value elif command == DO: for _value in value: for __value, __command in _value: result = process(__value, __command) if result != DONT_RETURN: return result elif command == RETURN: return value elif command == GET_STATE: send_command = state elif command == CALL: value() else: raise Exception("Unknown command") return DONT_RETURN try: generator = f(*args, **kwargs) while True: commands = generator.send(send) send = None try: while True: command, value = commands.send(send_command) send_command = None result = process(command, value) if result != DONT_RETURN: return result except StopIteration: pass except StopIteration: try: return state[GLOBAL] except: return state return _workflow def maybe_callable(value, *args): return value(*args()) if callable(value) else value
{ "repo_name": "runekaagaard/workflows", "path": "workflows/__init__.py", "copies": "1", "size": "1839", "license": "unlicense", "hash": 5627648623299331000, "line_mean": 26.0588235294, "line_max": 68, "alpha_frac": 0.450788472, "autogenerated": false, "ratio": 5.224431818181818, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6175220290181819, "avg_score": null, "num_lines": null }
from functools import wraps from aiohttp.abc import AbstractView from aiohttp.web import HTTPForbidden, json_response, StreamResponse try: import ujson as json except ImportError: import json from .cfg import cfg from .utils import url_for, redirect, get_cur_user def _get_request(args): # Supports class based views see web.View if isinstance(args[0], AbstractView): return args[0].request return args[-1] def user_to_request(handler): '''Add user to request if user logged in''' @wraps(handler) async def decorator(*args): request = _get_request(args) request[cfg.REQUEST_USER_KEY] = await get_cur_user(request) return await handler(*args) return decorator def login_required(handler): @user_to_request @wraps(handler) async def decorator(*args): request = _get_request(args) if not request[cfg.REQUEST_USER_KEY]: return redirect(get_login_url(request)) return await handler(*args) return decorator def restricted_api(handler): @user_to_request @wraps(handler) async def decorator(*args): request = _get_request(args) if not request[cfg.REQUEST_USER_KEY]: return json_response({'error': 'Access denied'}, status=403) response = await handler(*args) if not isinstance(response, StreamResponse): response = json_response(response, dumps=json.dumps) return response return decorator def admin_required(handler): @wraps(handler) async def decorator(*args): request = _get_request(args) response = await login_required(handler)(request) if request['user']['email'] not in cfg.ADMIN_EMAILS: raise HTTPForbidden(reason='You are not admin') return response return decorator def get_login_url(request): return url_for('auth_login').with_query({ cfg.BACK_URL_QS_KEY: request.path_qs})
{ "repo_name": "imbolc/aiohttp-login", "path": "aiohttp_login/decorators.py", "copies": "1", "size": "1959", "license": "isc", "hash": -4827226534677620000, "line_mean": 27.3913043478, "line_max": 72, "alpha_frac": 0.6625829505, "autogenerated": false, "ratio": 3.9979591836734696, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5160542134173469, "avg_score": null, "num_lines": null }
from functools import wraps from aiohttp.web import HTTPBadRequest from . import schema, list_schema from .utils import parse_qs from .autils import mark_coro from .vdecorator import ValidationDecorator, ErrorHandler, mergeof from .errors import error_to_json from .ast_transformer import import_module import_module('covador.aiohttp_t', (('fn', True),)) from .aiohttp_t import get_form, get_json def error_adapter(func): @wraps(func) def inner(ctx): return func(get_request(ctx.args[0]), ctx) return inner @ErrorHandler @error_adapter def error_handler(_request, ctx): raise HTTPBadRequest(body=error_to_json(ctx.exception), content_type='application/json') def get_qs(request): try: return request['_covador_qs'] except KeyError: qs = request['_covador_qs'] = parse_qs(request.query_string or '') return qs def get_request(obj): return getattr(obj, 'request', obj) _query_string = lambda request, *_args, **_kwargs: get_qs(get_request(request)) _form = mark_coro(lambda request, *_args, **_kwargs: get_form(get_request(request))) _args = lambda request, *_args, **_kwargs: get_request(request).match_info _json_body = mark_coro(lambda request, *_args, **_kwargs: get_json(get_request(request))) query_string = ValidationDecorator(_query_string, error_handler, list_schema) form = ValidationDecorator(_form, error_handler, list_schema) params = mergeof(query_string, form) args = ValidationDecorator(_args, error_handler, schema) json_body = ValidationDecorator(_json_body, error_handler, schema)
{ "repo_name": "baverman/covador", "path": "covador/aiohttp.py", "copies": "1", "size": "1598", "license": "mit", "hash": 2096776840539917000, "line_mean": 29.7307692308, "line_max": 89, "alpha_frac": 0.7108886108, "autogenerated": false, "ratio": 3.5353982300884956, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9734943262081681, "avg_score": 0.00226871576136282, "num_lines": 52 }
from functools import wraps from alembic.migration import MigrationContext from alembic.operations import Operations import sqlalchemy as sa from toolz.curried import do, operator as op from catalyst.assets.asset_writer import write_version_info from catalyst.errors import AssetDBImpossibleDowngrade from catalyst.utils.preprocess import preprocess from catalyst.utils.sqlite_utils import coerce_string_to_eng @preprocess(engine=coerce_string_to_eng) def downgrade(engine, desired_version): """Downgrades the assets db at the given engine to the desired version. Parameters ---------- engine : Engine An SQLAlchemy engine to the assets database. desired_version : int The desired resulting version for the assets database. """ # Check the version of the db at the engine with engine.begin() as conn: metadata = sa.MetaData(conn) metadata.reflect() version_info_table = metadata.tables['version_info'] starting_version = sa.select((version_info_table.c.version,)).scalar() # Check for accidental upgrade if starting_version < desired_version: raise AssetDBImpossibleDowngrade(db_version=starting_version, desired_version=desired_version) # Check if the desired version is already the db version if starting_version == desired_version: # No downgrade needed return # Create alembic context ctx = MigrationContext.configure(conn) op = Operations(ctx) # Integer keys of downgrades to run # E.g.: [5, 4, 3, 2] would downgrade v6 to v2 downgrade_keys = range(desired_version, starting_version)[::-1] # Disable foreign keys until all downgrades are complete _pragma_foreign_keys(conn, False) # Execute the downgrades in order for downgrade_key in downgrade_keys: _downgrade_methods[downgrade_key](op, conn, version_info_table) # Re-enable foreign keys _pragma_foreign_keys(conn, True) def _pragma_foreign_keys(connection, on): """Sets the PRAGMA foreign_keys state of the SQLite database. Disabling the pragma allows for batch modification of tables with foreign keys. Parameters ---------- connection : Connection A SQLAlchemy connection to the db on : bool If true, PRAGMA foreign_keys will be set to ON. Otherwise, the PRAGMA foreign_keys will be set to OFF. """ connection.execute("PRAGMA foreign_keys=%s" % ("ON" if on else "OFF")) # This dict contains references to downgrade methods that can be applied to an # assets db. The resulting db's version is the key. # e.g. The method at key '0' is the downgrade method from v1 to v0 _downgrade_methods = {} def downgrades(src): """Decorator for marking that a method is a downgrade to a version to the previous version. Parameters ---------- src : int The version this downgrades from. Returns ------- decorator : callable[(callable) -> callable] The decorator to apply. """ def _(f): destination = src - 1 @do(op.setitem(_downgrade_methods, destination)) @wraps(f) def wrapper(op, conn, version_info_table): conn.execute(version_info_table.delete()) # clear the version f(op) write_version_info(conn, version_info_table, destination) return wrapper return _ @downgrades(1) def _downgrade_v1(op): """ Downgrade assets db by removing the 'tick_size' column and renaming the 'multiplier' column. """ # Drop indices before batch # This is to prevent index collision when creating the temp table op.drop_index('ix_futures_contracts_root_symbol') op.drop_index('ix_futures_contracts_symbol') # Execute batch op to allow column modification in SQLite with op.batch_alter_table('futures_contracts') as batch_op: # Rename 'multiplier' batch_op.alter_column(column_name='multiplier', new_column_name='contract_multiplier') # Delete 'tick_size' batch_op.drop_column('tick_size') # Recreate indices after batch op.create_index('ix_futures_contracts_root_symbol', table_name='futures_contracts', columns=['root_symbol']) op.create_index('ix_futures_contracts_symbol', table_name='futures_contracts', columns=['symbol'], unique=True) @downgrades(2) def _downgrade_v2(op): """ Downgrade assets db by removing the 'auto_close_date' column. """ # Drop indices before batch # This is to prevent index collision when creating the temp table op.drop_index('ix_equities_fuzzy_symbol') op.drop_index('ix_equities_company_symbol') # Execute batch op to allow column modification in SQLite with op.batch_alter_table('equities') as batch_op: batch_op.drop_column('auto_close_date') # Recreate indices after batch op.create_index('ix_equities_fuzzy_symbol', table_name='equities', columns=['fuzzy_symbol']) op.create_index('ix_equities_company_symbol', table_name='equities', columns=['company_symbol']) @downgrades(3) def _downgrade_v3(op): """ Downgrade assets db by adding a not null constraint on ``equities.first_traded`` """ op.create_table( '_new_equities', sa.Column( 'sid', sa.Integer, unique=True, nullable=False, primary_key=True, ), sa.Column('symbol', sa.Text), sa.Column('company_symbol', sa.Text), sa.Column('share_class_symbol', sa.Text), sa.Column('fuzzy_symbol', sa.Text), sa.Column('asset_name', sa.Text), sa.Column('start_date', sa.Integer, default=0, nullable=False), sa.Column('end_date', sa.Integer, nullable=False), sa.Column('first_traded', sa.Integer, nullable=False), sa.Column('auto_close_date', sa.Integer), sa.Column('exchange', sa.Text), ) op.execute( """ insert into _new_equities select * from equities where equities.first_traded is not null """, ) op.drop_table('equities') op.rename_table('_new_equities', 'equities') # we need to make sure the indices have the proper names after the rename op.create_index( 'ix_equities_company_symbol', 'equities', ['company_symbol'], ) op.create_index( 'ix_equities_fuzzy_symbol', 'equities', ['fuzzy_symbol'], ) @downgrades(4) def _downgrade_v4(op): """ Downgrades assets db by copying the `exchange_full` column to `exchange`, then dropping the `exchange_full` column. """ op.drop_index('ix_equities_fuzzy_symbol') op.drop_index('ix_equities_company_symbol') op.execute("UPDATE equities SET exchange = exchange_full") with op.batch_alter_table('equities') as batch_op: batch_op.drop_column('exchange_full') op.create_index('ix_equities_fuzzy_symbol', table_name='equities', columns=['fuzzy_symbol']) op.create_index('ix_equities_company_symbol', table_name='equities', columns=['company_symbol']) @downgrades(5) def _downgrade_v5(op): op.create_table( '_new_equities', sa.Column( 'sid', sa.Integer, unique=True, nullable=False, primary_key=True, ), sa.Column('symbol', sa.Text), sa.Column('company_symbol', sa.Text), sa.Column('share_class_symbol', sa.Text), sa.Column('fuzzy_symbol', sa.Text), sa.Column('asset_name', sa.Text), sa.Column('start_date', sa.Integer, default=0, nullable=False), sa.Column('end_date', sa.Integer, nullable=False), sa.Column('first_traded', sa.Integer), sa.Column('auto_close_date', sa.Integer), sa.Column('exchange', sa.Text), sa.Column('exchange_full', sa.Text) ) op.execute( """ insert into _new_equities select equities.sid as sid, sym.symbol as symbol, sym.company_symbol as company_symbol, sym.share_class_symbol as share_class_symbol, sym.company_symbol || sym.share_class_symbol as fuzzy_symbol, equities.asset_name as asset_name, equities.start_date as start_date, equities.end_date as end_date, equities.first_traded as first_traded, equities.auto_close_date as auto_close_date, equities.exchange as exchange, equities.exchange_full as exchange_full from equities inner join -- Nested select here to take the most recently held ticker -- for each sid. The group by with no aggregation function will -- take the last element in the group, so we first order by -- the end date ascending to ensure that the groupby takes -- the last ticker. (select * from (select * from equity_symbol_mappings order by equity_symbol_mappings.end_date asc) group by sid) sym on equities.sid == sym.sid """, ) op.drop_table('equity_symbol_mappings') op.drop_table('equities') op.rename_table('_new_equities', 'equities') # we need to make sure the indicies have the proper names after the rename op.create_index( 'ix_equities_company_symbol', 'equities', ['company_symbol'], ) op.create_index( 'ix_equities_fuzzy_symbol', 'equities', ['fuzzy_symbol'], ) @downgrades(6) def _downgrade_v6(op): op.drop_table('equity_supplementary_mappings')
{ "repo_name": "enigmampc/catalyst", "path": "catalyst/assets/asset_db_migrations.py", "copies": "1", "size": "10230", "license": "apache-2.0", "hash": 2832154078629196300, "line_mean": 31.3734177215, "line_max": 78, "alpha_frac": 0.6013685239, "autogenerated": false, "ratio": 3.9743589743589745, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 316 }
from functools import wraps from alembic.migration import MigrationContext from alembic.operations import Operations import sqlalchemy as sa from toolz.curried import do, operator as op from zipline.assets.asset_writer import write_version_info from zipline.errors import AssetDBImpossibleDowngrade from zipline.utils.preprocess import preprocess from zipline.utils.sqlite_utils import coerce_string_to_eng @preprocess(engine=coerce_string_to_eng) def downgrade(engine, desired_version): """Downgrades the assets db at the given engine to the desired version. Parameters ---------- engine : Engine An SQLAlchemy engine to the assets database. desired_version : int The desired resulting version for the assets database. """ # Check the version of the db at the engine with engine.begin() as conn: metadata = sa.MetaData(conn) metadata.reflect() version_info_table = metadata.tables['version_info'] starting_version = sa.select((version_info_table.c.version,)).scalar() # Check for accidental upgrade if starting_version < desired_version: raise AssetDBImpossibleDowngrade(db_version=starting_version, desired_version=desired_version) # Check if the desired version is already the db version if starting_version == desired_version: # No downgrade needed return # Create alembic context ctx = MigrationContext.configure(conn) op = Operations(ctx) # Integer keys of downgrades to run # E.g.: [5, 4, 3, 2] would downgrade v6 to v2 downgrade_keys = range(desired_version, starting_version)[::-1] # Disable foreign keys until all downgrades are complete _pragma_foreign_keys(conn, False) # Execute the downgrades in order for downgrade_key in downgrade_keys: _downgrade_methods[downgrade_key](op, conn, version_info_table) # Re-enable foreign keys _pragma_foreign_keys(conn, True) def _pragma_foreign_keys(connection, on): """Sets the PRAGMA foreign_keys state of the SQLite database. Disabling the pragma allows for batch modification of tables with foreign keys. Parameters ---------- connection : Connection A SQLAlchemy connection to the db on : bool If true, PRAGMA foreign_keys will be set to ON. Otherwise, the PRAGMA foreign_keys will be set to OFF. """ connection.execute("PRAGMA foreign_keys=%s" % ("ON" if on else "OFF")) # This dict contains references to downgrade methods that can be applied to an # assets db. The resulting db's version is the key. # e.g. The method at key '0' is the downgrade method from v1 to v0 _downgrade_methods = {} def downgrades(src): """Decorator for marking that a method is a downgrade to a version to the previous version. Parameters ---------- src : int The version this downgrades from. Returns ------- decorator : callable[(callable) -> callable] The decorator to apply. """ def _(f): destination = src - 1 @do(op.setitem(_downgrade_methods, destination)) @wraps(f) def wrapper(op, conn, version_info_table): conn.execute(version_info_table.delete()) # clear the version f(op) write_version_info(conn, version_info_table, destination) return wrapper return _ @downgrades(1) def _downgrade_v1(op): """ Downgrade assets db by removing the 'tick_size' column and renaming the 'multiplier' column. """ # Drop indices before batch # This is to prevent index collision when creating the temp table op.drop_index('ix_futures_contracts_root_symbol') op.drop_index('ix_futures_contracts_symbol') # Execute batch op to allow column modification in SQLite with op.batch_alter_table('futures_contracts') as batch_op: # Rename 'multiplier' batch_op.alter_column(column_name='multiplier', new_column_name='contract_multiplier') # Delete 'tick_size' batch_op.drop_column('tick_size') # Recreate indices after batch op.create_index('ix_futures_contracts_root_symbol', table_name='futures_contracts', columns=['root_symbol']) op.create_index('ix_futures_contracts_symbol', table_name='futures_contracts', columns=['symbol'], unique=True) @downgrades(2) def _downgrade_v2(op): """ Downgrade assets db by removing the 'auto_close_date' column. """ # Drop indices before batch # This is to prevent index collision when creating the temp table op.drop_index('ix_equities_fuzzy_symbol') op.drop_index('ix_equities_company_symbol') # Execute batch op to allow column modification in SQLite with op.batch_alter_table('equities') as batch_op: batch_op.drop_column('auto_close_date') # Recreate indices after batch op.create_index('ix_equities_fuzzy_symbol', table_name='equities', columns=['fuzzy_symbol']) op.create_index('ix_equities_company_symbol', table_name='equities', columns=['company_symbol']) @downgrades(3) def _downgrade_v3(op): """ Downgrade assets db by adding a not null constraint on ``equities.first_traded`` """ op.create_table( '_new_equities', sa.Column( 'sid', sa.Integer, unique=True, nullable=False, primary_key=True, ), sa.Column('symbol', sa.Text), sa.Column('company_symbol', sa.Text), sa.Column('share_class_symbol', sa.Text), sa.Column('fuzzy_symbol', sa.Text), sa.Column('asset_name', sa.Text), sa.Column('start_date', sa.Integer, default=0, nullable=False), sa.Column('end_date', sa.Integer, nullable=False), sa.Column('first_traded', sa.Integer, nullable=False), sa.Column('auto_close_date', sa.Integer), sa.Column('exchange', sa.Text), ) op.execute( """ insert into _new_equities select * from equities where equities.first_traded is not null """, ) op.drop_table('equities') op.rename_table('_new_equities', 'equities') # we need to make sure the indices have the proper names after the rename op.create_index( 'ix_equities_company_symbol', 'equities', ['company_symbol'], ) op.create_index( 'ix_equities_fuzzy_symbol', 'equities', ['fuzzy_symbol'], ) @downgrades(4) def _downgrade_v4(op): """ Downgrades assets db by copying the `exchange_full` column to `exchange`, then dropping the `exchange_full` column. """ op.drop_index('ix_equities_fuzzy_symbol') op.drop_index('ix_equities_company_symbol') op.execute("UPDATE equities SET exchange = exchange_full") with op.batch_alter_table('equities') as batch_op: batch_op.drop_column('exchange_full') op.create_index('ix_equities_fuzzy_symbol', table_name='equities', columns=['fuzzy_symbol']) op.create_index('ix_equities_company_symbol', table_name='equities', columns=['company_symbol']) @downgrades(5) def _downgrade_v5(op): op.create_table( '_new_equities', sa.Column( 'sid', sa.Integer, unique=True, nullable=False, primary_key=True, ), sa.Column('symbol', sa.Text), sa.Column('company_symbol', sa.Text), sa.Column('share_class_symbol', sa.Text), sa.Column('fuzzy_symbol', sa.Text), sa.Column('asset_name', sa.Text), sa.Column('start_date', sa.Integer, default=0, nullable=False), sa.Column('end_date', sa.Integer, nullable=False), sa.Column('first_traded', sa.Integer), sa.Column('auto_close_date', sa.Integer), sa.Column('exchange', sa.Text), sa.Column('exchange_full', sa.Text) ) op.execute( """ insert into _new_equities select equities.sid as sid, sym.symbol as symbol, sym.company_symbol as company_symbol, sym.share_class_symbol as share_class_symbol, sym.company_symbol || sym.share_class_symbol as fuzzy_symbol, equities.asset_name as asset_name, equities.start_date as start_date, equities.end_date as end_date, equities.first_traded as first_traded, equities.auto_close_date as auto_close_date, equities.exchange as exchange, equities.exchange_full as exchange_full from equities inner join -- Nested select here to take the most recently held ticker -- for each sid. The group by with no aggregation function will -- take the last element in the group, so we first order by -- the end date ascending to ensure that the groupby takes -- the last ticker. (select * from (select * from equity_symbol_mappings order by equity_symbol_mappings.end_date asc) group by sid) sym on equities.sid == sym.sid """, ) op.drop_table('equity_symbol_mappings') op.drop_table('equities') op.rename_table('_new_equities', 'equities') # we need to make sure the indicies have the proper names after the rename op.create_index( 'ix_equities_company_symbol', 'equities', ['company_symbol'], ) op.create_index( 'ix_equities_fuzzy_symbol', 'equities', ['fuzzy_symbol'], )
{ "repo_name": "magne-max/zipline-ja", "path": "zipline/assets/asset_db_migrations.py", "copies": "1", "size": "10135", "license": "apache-2.0", "hash": -2870723432412469000, "line_mean": 31.5884244373, "line_max": 78, "alpha_frac": 0.600197336, "autogenerated": false, "ratio": 3.999605367008682, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5099802703008681, "avg_score": null, "num_lines": null }
from functools import wraps from allura import model as M from ming.orm.ormsession import ThreadLocalORMSession from pylons import c def with_user_project(username): def _with_user_project(func): @wraps(func) def wrapped(*args, **kw): user = M.User.by_username(username) c.user = user n = M.Neighborhood.query.get(name='Users') shortname = 'u/' + username p = M.Project.query.get(shortname=shortname, neighborhood_id=n._id) if not p: n.register_project(shortname, user=user, user_project=True) ThreadLocalORMSession.flush_all() ThreadLocalORMSession.close_all() return func(*args, **kw) return wrapped return _with_user_project def with_tool(project_shortname, ep_name, mount_point=None, mount_label=None, ordinal=None, post_install_hook=None, username='test-admin', **override_options): def _with_tool(func): @wraps(func) def wrapped(*args, **kw): c.user = M.User.by_username(username) p = M.Project.query.get(shortname=project_shortname) c.project = p if mount_point and not p.app_instance(mount_point): c.app = p.install_app(ep_name, mount_point, mount_label, ordinal, **override_options) if post_install_hook: post_install_hook(c.app) while M.MonQTask.run_ready('setup'): pass ThreadLocalORMSession.flush_all() ThreadLocalORMSession.close_all() elif mount_point: c.app = p.app_instance(mount_point) return func(*args, **kw) return wrapped return _with_tool with_discussion = with_tool('test', 'Discussion', 'discussion') with_link = with_tool('test', 'Link', 'link') with_tracker = with_tool('test', 'Tickets', 'bugs') with_wiki = with_tool('test', 'Wiki', 'wiki') with_git = with_tool('test', 'Git', 'src-git', 'Git', type='git') with_hg = with_tool('test', 'Hg', 'src-hg', 'Mercurial', type='hg') with_svn = with_tool('test', 'SVN', 'src', 'SVN') def with_repos(func): @wraps(func) @with_git @with_hg @with_svn def wrapped(*args, **kw): return func(*args, **kw) return wrapped
{ "repo_name": "leotrubach/sourceforge-allura", "path": "Allura/allura/tests/decorators.py", "copies": "1", "size": "2342", "license": "apache-2.0", "hash": -566391402208446600, "line_mean": 35.59375, "line_max": 101, "alpha_frac": 0.584970111, "autogenerated": false, "ratio": 3.5112443778110944, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.958348147924933, "avg_score": 0.0025466019123530324, "num_lines": 64 }
from functools import wraps from allure_commons._core import plugin_manager from allure_commons.types import LabelType, LinkType from allure_commons.utils import uuid4 from allure_commons.utils import func_parameters def safely(result): if result: return result[0] else: def dummy(function): return function return dummy def label(label_type, *labels): return safely(plugin_manager.hook.decorate_as_label(label_type=label_type, labels=labels)) def severity(severity_level): return label(LabelType.SEVERITY, severity_level) def epic(*epics): return label(LabelType.EPIC, *epics) def feature(*features): return label(LabelType.FEATURE, *features) def story(*stories): return label(LabelType.STORY, *stories) def tag(*tags): return label(LabelType.TAG, *tags) def link(url, link_type=LinkType.LINK, name=None): return safely(plugin_manager.hook.decorate_as_link(url=url, link_type=link_type, name=name)) def issue(url, name=None): return link(url, link_type=LinkType.ISSUE, name=name) def testcase(url, name=None): return link(url, link_type=LinkType.TEST_CASE, name=name) class Dynamic(object): @staticmethod def label(label_type, *labels): plugin_manager.hook.add_label(label_type=label_type, labels=labels) @staticmethod def severity(severity_level): Dynamic.label(LabelType.SEVERITY, severity_level) @staticmethod def feature(*features): Dynamic.label(LabelType.FEATURE, *features) @staticmethod def story(*stories): Dynamic.label(LabelType.STORY, *stories) @staticmethod def tag(*tags): Dynamic.label(LabelType.TAG, *tags) @staticmethod def link(url, link_type=LinkType.LINK, name=None): plugin_manager.hook.add_link(url=url, link_type=link_type, name=name) @staticmethod def issue(url, name=None): Dynamic.link(url, link_type=LinkType.TEST_CASE, name=name) @staticmethod def testcase(url, name=None): Dynamic.link(url, link_type=LinkType.TEST_CASE, name=name) def step(title): if callable(title): return StepContext(title.__name__, ({}, {}))(title) else: return StepContext(title, ({}, {})) class StepContext: def __init__(self, title, params): self.title = title self.params = params self.uuid = uuid4() def __enter__(self): args, kwargs = self.params args.update(kwargs) params = list(args.items()) plugin_manager.hook.start_step(uuid=self.uuid, title=self.title, params=params) def __exit__(self, exc_type, exc_val, exc_tb): plugin_manager.hook.stop_step(uuid=self.uuid, title=self.title, exc_type=exc_type, exc_val=exc_val, exc_tb=exc_tb) def __call__(self, func): @wraps(func) def impl(*a, **kw): __tracebackhide__ = True params = func_parameters(func, *a, **kw) args, kwargs = params with StepContext(self.title.format(*args.values(), **kwargs), params): return func(*a, **kw) return impl class Attach(object): def __call__(self, body, name=None, attachment_type=None, extension=None): plugin_manager.hook.attach_data(body=body, name=name, attachment_type=attachment_type, extension=extension) def file(self, source, name=None, attachment_type=None, extension=None): plugin_manager.hook.attach_file(source=source, name=name, attachment_type=attachment_type, extension=extension) attach = Attach() class fixture(object): def __init__(self, fixture_function, parent_uuid=None, name=None): self._fixture_function = fixture_function self._parent_uuid = parent_uuid self._name = name if name else fixture_function.__name__ self._uuid = uuid4() self.parameters = None def __call__(self, *args, **kwargs): _args, _kwargs = func_parameters(self._fixture_function, *args, **kwargs) _args.update(kwargs) self.parameters = list(_args.items()) with self: return self._fixture_function(*args, **kwargs) def __enter__(self): plugin_manager.hook.start_fixture(parent_uuid=self._parent_uuid, uuid=self._uuid, name=self._name, parameters=self.parameters) def __exit__(self, exc_type, exc_val, exc_tb): plugin_manager.hook.stop_fixture(parent_uuid=self._parent_uuid, uuid=self._uuid, name=self._name, exc_type=exc_type, exc_val=exc_val, exc_tb=exc_tb) class test(object): def __init__(self, _test, context): self._test = _test self._uuid = uuid4() self.context = context self.parameters = None def __call__(self, *args, **kwargs): _args, _kwargs = func_parameters(self._test, *args, **kwargs) _args.update(_kwargs) self.parameters = list(_args.items()) with self: return self._test(*args, **kwargs) def __enter__(self): plugin_manager.hook.start_test(parent_uuid=None, uuid=self._uuid, name=None, parameters=self.parameters, context=self.context) def __exit__(self, exc_type, exc_val, exc_tb): plugin_manager.hook.stop_test(parent_uuid=None, uuid=self._uuid, name=None, context=self.context, exc_type=exc_type, exc_val=exc_val, exc_tb=exc_tb)
{ "repo_name": "igogorek/allure-python", "path": "allure-python-commons/src/_allure.py", "copies": "1", "size": "6092", "license": "apache-2.0", "hash": 7544402440775331000, "line_mean": 30.0816326531, "line_max": 119, "alpha_frac": 0.5697636244, "autogenerated": false, "ratio": 3.937944408532644, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5007708032932644, "avg_score": null, "num_lines": null }
from functools import wraps from app import db, app from app.models.mollie import Transaction from flask import url_for from flask_login import current_user from flask_babel import _ from mollie.api.client import Client from mollie.api.error import Error as MollieError import itertools import logging _logger = logging.getLogger(__name__) MollieClient = Client() def init_mollie(f): """Lazy initialization of the mollie client.""" @wraps(f) def wrapped(*args, **kwargs): if app.config['MOLLIE_KEY']: MollieClient.set_api_key(app.config['MOLLIE_KEY']) _logger.info('Using MOLLIE_KEY: %s', app.config['MOLLIE_KEY']) else: _logger.info('Using MOLLIE_KEY: NOTSET') return f(*args, **kwargs) return wrapped @init_mollie def create_transaction(amount, description, user=current_user, callbacks=list()): # Only create a new transaction if there is a related form result if not isinstance(callbacks, list): callbacks = [callbacks] callbacks.sort(key=lambda cb: cb.__class__.__name__) # Commit transaction to the database so it gets an ID transaction = Transaction() db.session.add(transaction) db.session.commit() for cb in callbacks: cb.transaction = transaction db.session.commit() # Create the mollie payment try: payment = MollieClient.payments.create({ 'amount': amount, 'description': "{}, {}".format(user.name, description), 'redirectUrl': url_for('mollie.callback', transaction_id=transaction.id, _external=True), 'metadata': { 'transaction_id': transaction.id, 'user_id': user.id, 'user_email': user.email, 'callbacks': { k: [cb.id for cb in v] for k, v in itertools.groupby(callbacks, key=lambda x: x.__class__.__name__) } } }) transaction.status = payment['status'] transaction.mollie_id = payment['id'] db.session.add(transaction) db.session.commit() return payment.get_payment_url(), transaction except MollieError as e: return False, _('API call failed: %s' % e.message) @init_mollie def check_transaction(transaction): try: payment = MollieClient.payments.get(transaction.mollie_id) transaction.status = payment['status'] db.session.commit() if payment.is_paid(): transaction.process_callbacks() return payment, _('Payment successfully received.') elif payment.is_pending(): return payment, _('Your payment is being processed.') elif payment.is_open(): return payment, _('Your payment has not been completed.') else: status = payment['status'] return None, _('Your payment has status: %s' % status) except MollieError as e: return None, _('API call failed: %s' % e.message) @init_mollie def get_payments(page=0): try: payments = MollieClient.payments.all(offset=page * 20, count=20)[0] return payments['data'], 'success' except MollieError as e: return [], _('Api call failed: %s' % e.message)
{ "repo_name": "viaict/viaduct", "path": "app/utils/mollie.py", "copies": "1", "size": "3417", "license": "mit", "hash": -7251080151420198000, "line_mean": 29.5089285714, "line_max": 75, "alpha_frac": 0.587357331, "autogenerated": false, "ratio": 4.097122302158273, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5184479633158273, "avg_score": null, "num_lines": null }
from functools import wraps from avocado.utils.iter import ins def _check_iter(func): @wraps(func) def decorator(*args, **kwargs): val = func(*args, **kwargs) if not ins(val): raise TypeError for e in val: if not ins(e) or len(e) != 2: raise TypeError return tuple(val) return decorator @_check_iter def eval_choices(val): # try evaling a straight sequence in the format: # [(1,'foo'), (2,'bar'), ...] try: return eval(val) except (SyntaxError, NameError): return None @_check_iter def model_attr(model, attr): # attempts to check the `model' for an attribute `attr': # when: attr = SHAPE_CHOICES # test: model.SHAPE_CHOICES return getattr(model, attr, None) @_check_iter def module_attr(module, attr): return getattr(module, attr, None) def evaluate(mf): ch = mf.choices_handler funcs = ( (model_attr, (mf.model, ch)), (module_attr, (mf.module, ch)), (eval_choices, (ch,)), ) for func, attrs in funcs: try: choices = func(*attrs) break except TypeError: pass else: choices = None return choices
{ "repo_name": "pombredanne/django-avocado", "path": "avocado/fields/evaluators.py", "copies": "1", "size": "1254", "license": "bsd-3-clause", "hash": -9003387830206275000, "line_mean": 22.2222222222, "line_max": 60, "alpha_frac": 0.5645933014, "autogenerated": false, "ratio": 3.743283582089552, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4807876883489552, "avg_score": null, "num_lines": null }
from functools import wraps from backend.components.base_component import BaseComponent from backend.components.clock import Clock from backend.components.modbus_network import ModbusNetwork from backend.misc.sys_types import Mt, Et class AddElementError(Exception): def __init__(self, msg): self.msg = msg class Module(BaseComponent): """Base class for all modules. It implements prototype of command that decorates all read and write functions""" table_name = 'modules' types = {Mt.led_light, Mt.output, Mt.ambient, Mt.input} # Needed for loading objects from database ID = 0 start_timeout = 10 # timeout in ms clock = Clock() items = {} def __init__(self, *args): super().__init__(args[0], Mt(args[1]), args[2]) Module.items[self.id] = self self.ports = {} # Module's physical ports. Dictionary stores elements during configuration so not to connect elment twice to same port self.elements = {} # Module's elements. Keys are registers in which elements values are going to be stored self.modbus = ModbusNetwork() # Reference to modbus. Modbus is a singleton. self.available = True # Flag indicating if there is communication with module self.last_timeout = 0 self.timeout = Module.start_timeout self.max_timeout = 2 self.correct_trans_num = 0 self.transmission_num = 0 self.courupted_trans_num = 0 def is_available(self, ): """Checks if module is available. If it is not but timeout expired it makes module available so there would be communication trial""" if self.available: self.timeout = Module.start_timeout return True else: current_time = self.clock.get_millis() if current_time - self.last_timeout >= self.timeout: self.last_timeout = current_time self.available = True return True return False @staticmethod def command(func): """Decorator for all modbus commands. It counts correct and corupted transmisions. It sets timeout if the transmission was corrupted """ @wraps(func) def func_wrapper(self, ): self.transmission_num += 1 result = func(self) if result: # if there is response from module self.correct_trans_num += 1 return result else: self.available = False self.courupted_trans_num += 1 if self.timeout <= self.max_timeout: self.timeout *= 2 # Increase timeout # TODO notification about module failures return result return func_wrapper def check_port_range(self, port): if port > self.num_of_ports-1 or port < 0: raise AddElementError('Port: ' + str(port) + ' out of range') def check_port_usage(self, port): try: self.ports[port] raise AddElementError('Port: ' + str(port) + ' is in use') except KeyError: pass def check_element_type(self, element): if element.type not in self.accepted_elements: raise AddElementError('Element: ' + element.type.name + ' is not valid for ' + self.type.name) def check_if_element_connected(self, element): if element.module_id and element.module_id != self.id and element.type != Et.blind: # roleta moze byc podlaczona 2 razy do jednego modulu - gora i dol raise AddElementError('Element: ' + str(element.id) + ' already connected to ' + str(element.module_id)) def add_element(self, port, element): self.check_element_type(element) self.check_port_range(port) self.check_port_usage(port) self.check_if_element_connected(element) self.ports[port] = element element.reg_id = port element.module_id = self.id self.elements[element.id] = element class InputModule(Module): """Base class for input modules. It implements read decorator command""" types = {Mt.ambient, Mt.input} items = {} def __init__(self, *args): super().__init__(*args) InputModule.items[self.id] = self @Module.command def read(self,): regs_values = self.modbus.read_regs(self.id, 0, self.num_of_regs) if regs_values: # If transmision was correct for element in self.elements.values(): new_value = regs_values[element.reg_id] if new_value != element.value: element.value = new_value element.new_val_flag = True return True return False class OutputModule(Module): """ Base class for output modules. It implements write decorator command""" types = {Mt.led_light, Mt.output} items = {} def __init__(self, *args): super().__init__(*args) OutputModule.items[self.id] = self self.values = [0 for _ in range(self.num_of_regs)] # values to be written in board modbus registers @staticmethod def write_command(func): """Decorator for modbus write commands it checks which elements values differ. If the communication result is True it updates elements values """ @wraps(func) def func_wrapper(self): elements_to_update = [] for element in self.elements.values(): if element.desired_value != element.value: # element value needs to be updated self.values[element.reg_id] = element.desired_value elements_to_update.append(element) result = func(self) if result: for element in elements_to_update: if element.desired_value != element.value: # element value needs to be updated element.value = element.desired_value # element value is updated element.new_val_flag = True return result return func_wrapper class OutputBoard(OutputModule): num_of_ports = 10 num_of_regs = 10 accepted_elements = {Et.led, Et.heater, Et.ventilator, Et.blind} types = {Mt.output} items = {} def __init__(self, *args): super().__init__(*args) OutputBoard.items[self.id] = self @Module.command @OutputModule.write_command def write(self, ): return self.modbus.write_coils(self.id, 0, self.values) class LedLightBoard(OutputModule): num_of_ports = 3 num_of_regs = 3 accepted_elements = {Et.led} types = {Mt.led_light} items = {} def __init__(self, *args): super().__init__(args[0], Mt(args[1]), args[2]) LedLightBoard.items[self.id] = self @Module.command @OutputModule.write_command def write(self, ): return self.modbus.write_regs(self.id, 0, self.values) class AmbientBoard(InputModule): num_of_ports = 4 num_of_regs = 19 accepted_elements = {Et.ds, Et.dht_hum, Et.dht_temp, Et.ls} types = {Mt.ambient} items = {} def __init__(self, *args): InputModule.__init__(self, *args) AmbientBoard.items[self.id] = self self.ds18b20_counter = 0 def add_element(self, port, element): """For Ambient board ports are not the same as registers. ds18b20 sensors are all working on one port""" self.check_element_type(element) self.check_port_range(port) self.check_if_element_connected(element) try: if self.ports[port]: # Check if something is already on the port if self.ports[port].type == Et.ds: # If on this port is ds18b20 if element.type == Et.ds: # And user wants to connect another ds18b20 pass # everything is fine else: raise AddElementError('Port: ' + port + ' in use') # raise error except KeyError: self.ports[port] = element # Add element to port if element.type == Et.ls: # dodanie elementu do rejestru element.reg_id = 0 elif element.type == Et.dht_temp: element.reg_id = 1 elif element.type == Et.dht_hum: element.reg_id = 2 elif element.type == Et.ds: element.reg_id = 3 + self.ds18b20_counter self.ds18b20_counter += 1 element.module_id = self.id self.elements[element.id] = element class InputBoard(InputModule): num_of_ports = 15 num_of_regs = 15 accepted_elements = {Et.pir, Et.rs, Et.switch} types = {Mt.input} items = {} def __init__(self, *args): InputModule.__init__(self, *args) InputBoard.items[self.id] = self
{ "repo_name": "dzon4xx/system", "path": "backend/components/module.py", "copies": "1", "size": "8924", "license": "mit", "hash": -153626750806933500, "line_mean": 33.3230769231, "line_max": 158, "alpha_frac": 0.5921111609, "autogenerated": false, "ratio": 3.8986456968108345, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49907568577108347, "avg_score": null, "num_lines": null }
from functools import wraps from .blueprints import NodeBlueprint, TangledSource, TangledSelf from .exceptions import NodeError __all__ = ['Tangled'] class TangleMeta(type): @classmethod def __prepare__(mcs, name, bases): """ Setting up class attributes so they are available when the a tangled class body is executed. """ return {'TangledSource': TangledSource, 'self': TangledSelf() } def __new__(meta, name, bases, namespace): namespace['tangled_maps'] = {} return super().__new__(meta, name, bases, namespace) def __init__(cls, name, bases, namespace): """ Setup various class attributes that need to be available for all Tangled sub classes """ for name, attr in namespace.items(): if hasattr(attr, 'mapping_for'): # sets up a map between classes, so that it's possible # to refer to Element instances with other owner classes namespace['tangled_maps'][attr.mapping_for] = attr super().__init__(name, bases, namespace) class Tangled(metaclass=TangleMeta): """ Base class for tangled behaviour. """ builder = None evaluator = None def __init__(self): self.nodes = {} @classmethod def set_handlers(cls, builder, evaluator): cls.builder = builder cls.evaluator = evaluator @staticmethod def tangled_function(func): """ Decorator to create a tangled function element """ @wraps(func) def wrapper(*args): return NodeBlueprint(func, *args) return wrapper @staticmethod def tangled_map(other): """ Decorator that registers the method to be a mapping to the class other """ def register(func): func.mapping_for = other return func return register def subscribe(self, node_name, event): try: # Initialise tree if required getattr(self, node_name) node = self.nodes[node_name] except KeyError: raise NodeError(f'No node {node_name} to subscribe to.') node.register_event(event)
{ "repo_name": "ltron/tangle", "path": "tangle/tangled.py", "copies": "1", "size": "2244", "license": "mit", "hash": 1347157180407395000, "line_mean": 28.1428571429, "line_max": 76, "alpha_frac": 0.5891265597, "autogenerated": false, "ratio": 4.533333333333333, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5622459893033334, "avg_score": null, "num_lines": null }
from functools import wraps from botocore.paginate import TokenDecoder, TokenEncoder from six.moves import reduce from .exceptions import InvalidToken PAGINATION_MODEL = { "list_executions": { "input_token": "next_token", "limit_key": "max_results", "limit_default": 100, "page_ending_range_keys": ["start_date", "execution_arn"], }, "list_state_machines": { "input_token": "next_token", "limit_key": "max_results", "limit_default": 100, "page_ending_range_keys": ["creation_date", "arn"], }, } def paginate(original_function=None, pagination_model=None): def pagination_decorator(func): @wraps(func) def pagination_wrapper(*args, **kwargs): method = func.__name__ model = pagination_model or PAGINATION_MODEL pagination_config = model.get(method) if not pagination_config: raise ValueError( "No pagination config for backend method: {}".format(method) ) # We pop the pagination arguments, so the remaining kwargs (if any) # can be used to compute the optional parameters checksum. input_token = kwargs.pop(pagination_config.get("input_token"), None) limit = kwargs.pop(pagination_config.get("limit_key"), None) paginator = Paginator( max_results=limit, max_results_default=pagination_config.get("limit_default"), starting_token=input_token, page_ending_range_keys=pagination_config.get("page_ending_range_keys"), param_values_to_check=kwargs, ) results = func(*args, **kwargs) return paginator.paginate(results) return pagination_wrapper if original_function: return pagination_decorator(original_function) return pagination_decorator class Paginator(object): def __init__( self, max_results=None, max_results_default=None, starting_token=None, page_ending_range_keys=None, param_values_to_check=None, ): self._max_results = max_results if max_results else max_results_default self._starting_token = starting_token self._page_ending_range_keys = page_ending_range_keys self._param_values_to_check = param_values_to_check self._token_encoder = TokenEncoder() self._token_decoder = TokenDecoder() self._param_checksum = self._calculate_parameter_checksum() self._parsed_token = self._parse_starting_token() def _parse_starting_token(self): if self._starting_token is None: return None # The starting token is a dict passed as a base64 encoded string. next_token = self._starting_token try: next_token = self._token_decoder.decode(next_token) except (ValueError, TypeError): raise InvalidToken("Invalid token") if next_token.get("parameterChecksum") != self._param_checksum: raise InvalidToken( "Input inconsistent with page token: {}".format(str(next_token)) ) return next_token def _calculate_parameter_checksum(self): if not self._param_values_to_check: return None return reduce( lambda x, y: x ^ y, [hash(item) for item in self._param_values_to_check.items()], ) def _check_predicate(self, item): page_ending_range_key = self._parsed_token["pageEndingRangeKey"] predicate_values = page_ending_range_key.split("|") for (index, attr) in enumerate(self._page_ending_range_keys): if not getattr(item, attr, None) == predicate_values[index]: return False return True def _build_next_token(self, next_item): token_dict = {} if self._param_checksum: token_dict["parameterChecksum"] = self._param_checksum range_keys = [] for (index, attr) in enumerate(self._page_ending_range_keys): range_keys.append(getattr(next_item, attr)) token_dict["pageEndingRangeKey"] = "|".join(range_keys) return TokenEncoder().encode(token_dict) def paginate(self, results): index_start = 0 if self._starting_token: try: index_start = next( index for (index, result) in enumerate(results) if self._check_predicate(result) ) except StopIteration: raise InvalidToken("Resource not found!") index_end = index_start + self._max_results if index_end > len(results): index_end = len(results) results_page = results[index_start:index_end] next_token = None if results_page and index_end < len(results): page_ending_result = results[index_end] next_token = self._build_next_token(page_ending_result) return results_page, next_token def cfn_to_api_tags(cfn_tags_entry): api_tags = [{k.lower(): v for k, v in d.items()} for d in cfn_tags_entry] return api_tags def api_to_cfn_tags(api_tags): cfn_tags_entry = [{k.capitalize(): v for k, v in d.items()} for d in api_tags] return cfn_tags_entry
{ "repo_name": "william-richard/moto", "path": "moto/stepfunctions/utils.py", "copies": "2", "size": "5391", "license": "apache-2.0", "hash": 3455755184579512000, "line_mean": 35.4256756757, "line_max": 87, "alpha_frac": 0.5945093675, "autogenerated": false, "ratio": 4.077912254160363, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5672421621660364, "avg_score": null, "num_lines": null }
from functools import wraps from cached_httpbl.middleware import CachedHTTPBLViewMiddleware from django.utils.decorators import available_attrs, decorator_from_middleware cached_httpbl_protect = decorator_from_middleware(CachedHTTPBLViewMiddleware) cached_httpbl_protect.__name__ = "cached_httpbl_protect" cached_httpbl_protect.__doc__ = """ This decorator adds cached httpbl protection in exactly the same way as CachedHTTPBLViewMiddleware, but it can be used on a per view basis. Using both, or using the decorator multiple times, is harmless and efficient. """ def cached_httpbl_exempt(view_func): """ Marks a view function as being exempt from the cached httpbl view protection. """ # We could just do view_func.cached_httpbl_exempt = True, but decorators # are nicer if they don't have side-effects, so we return a new # function. def wrapped_view(*args, **kwargs): return view_func(*args, **kwargs) wrapped_view.cached_httpbl_exempt = True return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
{ "repo_name": "dlancer/django-cached-httpbl", "path": "cached_httpbl/decorators.py", "copies": "1", "size": "1071", "license": "bsd-3-clause", "hash": 4098039014920940000, "line_mean": 40.1923076923, "line_max": 83, "alpha_frac": 0.7516339869, "autogenerated": false, "ratio": 3.8664259927797833, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009269186098454391, "num_lines": 26 }
from functools import wraps from .cd import cd from .needy import ConfiguredNeedy from .platforms import available_platforms from .utility import DummyContextManager try: from exceptions import NotImplementedError except ImportError: pass class Command: def name(self): raise NotImplementedError('name') def add_parser(self, group): pass def execute(self, arguments): raise NotImplementedError('execute') def completer(f): @wraps(f) def wrapper(parsed_args, **kwds): import argcomplete try: with cd(parsed_args.C) if getattr(parsed_args, 'C', None) else DummyContextManager() as _: return f(parsed_args=parsed_args, **kwds) except Exception as e: argcomplete.warn('An error occurred during argument completion: {}'.format(e)) return wrapper try: from argcomplete.completers import DirectoriesCompleter directory_completer = DirectoriesCompleter() except ImportError: directory_completer = None @completer def library_completer(prefix, parsed_args, **kwargs): with ConfiguredNeedy('.', parsed_args) as needy: target_or_universal_binary = parsed_args.universal_binary if getattr(parsed_args, 'universal_binary', None) else needy.target(getattr(parsed_args, 'target', 'host')) return [name for name in needy.libraries(target_or_universal_binary).keys() if name.startswith(prefix)] @completer def target_completer(prefix, **kwargs): if ':' in prefix: # architectures don't have any formal constraints, but we can provide some common ones architectures = ['x86_64', 'i386', 'armv7', 'arm64', 'amd64'] platform = prefix[:prefix.find(':')] return [result for result in [platform + ':' + architecture for architecture in architectures] if result.startswith(prefix)] platform_identifiers = available_platforms().keys() ret = [identifier for identifier in platform_identifiers if identifier.startswith(prefix)] if prefix in platform_identifiers: ret.append(prefix + ':') return ret @completer def universal_binary_completer(prefix, parsed_args, **kwargs): with ConfiguredNeedy('.', parsed_args) as needy: return [name for name in needy.universal_binary_names() if name.startswith(prefix)] def add_target_specification_args(parser, action='executes', allow_universal_binary=True): parser.add_argument('-t', '--target', default='host', help='{} for this target (example: ios:armv7)'.format(action)).completer = target_completer if allow_universal_binary: parser.add_argument('-u', '--universal-binary', help='{} for the universal binary with the given name'.format(action)).completer = universal_binary_completer parser.add_argument('-D', '--define', nargs='*', action='append', help='specify a user-defined variable to be passed to the needs file renderer') for platform in available_platforms().values(): platform.add_arguments(parser)
{ "repo_name": "ccbrown/needy", "path": "needy/command.py", "copies": "3", "size": "3000", "license": "mit", "hash": -8713377419375800000, "line_mean": 37.961038961, "line_max": 173, "alpha_frac": 0.701, "autogenerated": false, "ratio": 4.126547455295736, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0013657257300668582, "num_lines": 77 }
from functools import wraps from cms.api import get_page_draft from cms.cache.permissions import get_permission_cache, set_permission_cache from cms.constants import GRANT_ALL_PERMISSIONS from cms.models import Page, Placeholder from cms.utils import get_current_site from cms.utils.compat.dj import available_attrs from cms.utils.conf import get_cms_setting from cms.utils.permissions import ( cached_func, get_model_permission_codename, get_page_actions_for_user, has_global_permission, ) PAGE_ADD_CODENAME = get_model_permission_codename(Page, 'add') PAGE_CHANGE_CODENAME = get_model_permission_codename(Page, 'change') PAGE_DELETE_CODENAME = get_model_permission_codename(Page, 'delete') PAGE_PUBLISH_CODENAME = get_model_permission_codename(Page, 'publish') PAGE_VIEW_CODENAME = get_model_permission_codename(Page, 'view') # Maps an action to the required Django auth permission codes _django_permissions_by_action = { 'add_page': [PAGE_ADD_CODENAME, PAGE_CHANGE_CODENAME], 'change_page': [PAGE_CHANGE_CODENAME], 'change_page_advanced_settings': [PAGE_CHANGE_CODENAME], 'change_page_permissions': [PAGE_CHANGE_CODENAME], 'delete_page': [PAGE_CHANGE_CODENAME, PAGE_DELETE_CODENAME], 'delete_page_translation': [PAGE_CHANGE_CODENAME, PAGE_DELETE_CODENAME], 'move_page': [PAGE_CHANGE_CODENAME], 'publish_page': [PAGE_CHANGE_CODENAME, PAGE_PUBLISH_CODENAME], 'revert_page_to_live': [PAGE_CHANGE_CODENAME] } def _get_draft_placeholders(page): if page.publisher_is_draft: return page.placeholders.all() return Placeholder.objects.filter(page__pk=page.publisher_public_id) def _check_delete_translation(user, page, language, site=None): return user_can_change_page(user, page, site=site) def _get_page_ids_for_action(user, site, action, check_global=True, use_cache=True): if user.is_superuser or not get_cms_setting('PERMISSION'): # got superuser, or permissions aren't enabled? # just return grant all mark return GRANT_ALL_PERMISSIONS if check_global and has_global_permission(user, site, action=action, use_cache=use_cache): return GRANT_ALL_PERMISSIONS if use_cache: # read from cache if possible cached = get_permission_cache(user, action) get_page_actions = get_page_actions_for_user else: cached = None get_page_actions = get_page_actions_for_user.without_cache if cached is not None: return cached page_actions = get_page_actions(user, site) page_ids = list(page_actions[action]) set_permission_cache(user, action, page_ids) return page_ids def auth_permission_required(action): def decorator(func): @wraps(func, assigned=available_attrs(func)) def wrapper(user, *args, **kwargs): if not user.is_authenticated: return False permissions = _django_permissions_by_action[action] if not user.has_perms(permissions): # Fail fast if the user does not have permissions # in Django to perform the action. return False permissions_enabled = get_cms_setting('PERMISSION') if not user.is_superuser and permissions_enabled: return func(user, *args, **kwargs) return True return wrapper return decorator def change_permission_required(func): @wraps(func, assigned=available_attrs(func)) def wrapper(user, page, site=None): if not user_can_change_page(user, page, site=site): return False return func(user, page, site=site) return wrapper def skip_if_permissions_disabled(func): @wraps(func, assigned=available_attrs(func)) def wrapper(user, page, site=None): if not get_cms_setting('PERMISSION'): return True return func(user, page, site=site) return wrapper @cached_func @auth_permission_required('add_page') def user_can_add_page(user, site=None): if site is None: site = get_current_site() return has_global_permission(user, site, action='add_page') @cached_func @auth_permission_required('add_page') def user_can_add_subpage(user, target, site=None): """ Return true if the current user has permission to add a new page under target. :param user: :param target: a Page object :param site: optional Site object (not just PK) :return: Boolean """ has_perm = has_generic_permission( page=target, user=user, action='add_page', site=site, ) return has_perm @cached_func @auth_permission_required('change_page') def user_can_change_page(user, page, site=None): can_change = has_generic_permission( page=page, user=user, action='change_page', site=site, ) return can_change @cached_func @auth_permission_required('delete_page') def user_can_delete_page(user, page, site=None): has_perm = has_generic_permission( page=page, user=user, action='delete_page', site=site, ) if not has_perm: return False languages = page.get_languages() placeholders = ( _get_draft_placeholders(page) .filter(cmsplugin__language__in=languages) .distinct() ) for placeholder in placeholders.iterator(): if not placeholder.has_delete_plugins_permission(user, languages): return False return True @cached_func @auth_permission_required('delete_page_translation') def user_can_delete_page_translation(user, page, language, site=None): has_perm = has_generic_permission( page=page, user=user, action='delete_page_translation', site=site, ) if not has_perm: return False placeholders = ( _get_draft_placeholders(page) .filter(cmsplugin__language=language) .distinct() ) for placeholder in placeholders.iterator(): if not placeholder.has_delete_plugins_permission(user, [language]): return False return True @cached_func @auth_permission_required('change_page') def user_can_revert_page_to_live(user, page, language, site=None): if not user_can_change_page(user, page, site=site): return False placeholders = ( _get_draft_placeholders(page) .filter(cmsplugin__language=language) .distinct() ) for placeholder in placeholders.iterator(): if not placeholder.has_delete_plugins_permission(user, [language]): return False return True @cached_func @auth_permission_required('publish_page') def user_can_publish_page(user, page, site=None): has_perm = has_generic_permission( page=page, user=user, action='publish_page', site=site, ) return has_perm @cached_func @auth_permission_required('change_page_advanced_settings') def user_can_change_page_advanced_settings(user, page, site=None): has_perm = has_generic_permission( page=page, user=user, action='change_page_advanced_settings', site=site, ) return has_perm @cached_func @auth_permission_required('change_page_permissions') def user_can_change_page_permissions(user, page, site=None): has_perm = has_generic_permission( page=page, user=user, action='change_page_permissions', site=site, ) return has_perm @cached_func @auth_permission_required('move_page') def user_can_move_page(user, page, site=None): has_perm = has_generic_permission( page=page, user=user, action='move_page', site=site, ) return has_perm @cached_func def user_can_view_page(user, page, site=None): if site is None: site = get_current_site() if user.is_superuser: return True public_for = get_cms_setting('PUBLIC_FOR') can_see_unrestricted = public_for == 'all' or (public_for == 'staff' and user.is_staff) page = get_page_draft(page) # inherited and direct view permissions is_restricted = page.has_view_restrictions(site) if not is_restricted and can_see_unrestricted: # Page has no restrictions and project is configured # to allow everyone to see unrestricted pages. return True elif not user.is_authenticated: # Page has restrictions or project is configured # to require staff user status to see pages. return False if user_can_view_all_pages(user, site=site): return True if not is_restricted: # Page has no restrictions but user can't see unrestricted pages return False if user_can_change_page(user, page): # If user has change permissions on a page # then he can automatically view it. return True has_perm = has_generic_permission( page=page, user=user, action='view_page', check_global=False, ) return has_perm @cached_func @auth_permission_required('change_page') def user_can_view_page_draft(user, page, site=None): has_perm = has_generic_permission( page=page, user=user, action='change_page', site=site, ) return has_perm @cached_func @auth_permission_required('change_page') def user_can_change_all_pages(user, site): return has_global_permission(user, site, action='change_page') @auth_permission_required('change_page') def user_can_change_at_least_one_page(user, site, use_cache=True): page_ids = get_change_id_list( user=user, site=site, check_global=True, use_cache=use_cache, ) return page_ids == GRANT_ALL_PERMISSIONS or bool(page_ids) @cached_func def user_can_view_all_pages(user, site): if user.is_superuser: return True if not get_cms_setting('PERMISSION'): public_for = get_cms_setting('PUBLIC_FOR') can_see_unrestricted = public_for == 'all' or (public_for == 'staff' and user.is_staff) return can_see_unrestricted if not user.is_authenticated: return False if user.has_perm(PAGE_VIEW_CODENAME): # This is for backwards compatibility. # The previous system allowed any user with the explicit view_page # permission to see all pages. return True if user_can_change_all_pages(user, site): # If a user can change all pages then he can see all pages. return True return has_global_permission(user, site, action='view_page') def get_add_id_list(user, site, check_global=True, use_cache=True): """ Give a list of page where the user has add page rights or the string "All" if the user has all rights. """ page_ids = _get_page_ids_for_action( user=user, site=site, action='add_page', check_global=check_global, use_cache=use_cache, ) return page_ids def get_change_id_list(user, site, check_global=True, use_cache=True): """ Give a list of page where the user has edit rights or the string "All" if the user has all rights. """ page_ids = _get_page_ids_for_action( user=user, site=site, action='change_page', check_global=check_global, use_cache=use_cache, ) return page_ids def get_change_advanced_settings_id_list(user, site, check_global=True, use_cache=True): """ Give a list of page where the user can change advanced settings or the string "All" if the user has all rights. """ page_ids = _get_page_ids_for_action( user=user, site=site, action='change_page_advanced_settings', check_global=check_global, use_cache=use_cache, ) return page_ids def get_change_permissions_id_list(user, site, check_global=True, use_cache=True): """Give a list of page where the user can change permissions. """ page_ids = _get_page_ids_for_action( user=user, site=site, action='change_page_permissions', check_global=check_global, use_cache=use_cache, ) return page_ids def get_delete_id_list(user, site, check_global=True, use_cache=True): """ Give a list of page where the user has delete rights or the string "All" if the user has all rights. """ page_ids = _get_page_ids_for_action( user=user, site=site, action='delete_page', check_global=check_global, use_cache=use_cache, ) return page_ids def get_move_page_id_list(user, site, check_global=True, use_cache=True): """Give a list of pages which user can move. """ page_ids = _get_page_ids_for_action( user=user, site=site, action='move_page', check_global=check_global, use_cache=use_cache, ) return page_ids def get_publish_id_list(user, site, check_global=True, use_cache=True): """ Give a list of page where the user has publish rights or the string "All" if the user has all rights. """ page_ids = _get_page_ids_for_action( user=user, site=site, action='publish_page', check_global=check_global, use_cache=use_cache, ) return page_ids def get_view_id_list(user, site, check_global=True, use_cache=True): """Give a list of pages which user can view. """ page_ids = _get_page_ids_for_action( user=user, site=site, action='view_page', check_global=check_global, use_cache=use_cache, ) return page_ids def has_generic_permission(page, user, action, site=None, check_global=True): if site is None: site = get_current_site() if page.publisher_is_draft: page_id = page.pk else: page_id = page.publisher_public_id actions_map = { 'add_page': get_add_id_list, 'change_page': get_change_id_list, 'change_page_advanced_settings': get_change_advanced_settings_id_list, 'change_page_permissions': get_change_permissions_id_list, 'delete_page': get_delete_id_list, 'delete_page_translation': get_delete_id_list, 'move_page': get_move_page_id_list, 'publish_page': get_publish_id_list, 'view_page': get_view_id_list, } func = actions_map[action] page_ids = func(user, site, check_global=check_global) return page_ids == GRANT_ALL_PERMISSIONS or page_id in page_ids
{ "repo_name": "rsalmaso/django-cms", "path": "cms/utils/page_permissions.py", "copies": "2", "size": "14521", "license": "bsd-3-clause", "hash": -7930601829181359000, "line_mean": 27.4725490196, "line_max": 95, "alpha_frac": 0.6439639143, "autogenerated": false, "ratio": 3.6068057625434675, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00015530800077547915, "num_lines": 510 }
from functools import wraps from .compat import text b_int = int idfunc = lambda v: v class ValidateError(ValueError): def __init__(self, message, errors): ValueError.__init__(self, message) self.errors = errors def check(func, message=None): message = message or 'Invalid value' @wraps(func) def inner(data): if func(data): return data raise ValueError(message) return inner class Field(object): def __init__(self): self.name = None self.required = True self.default = None self.validators = [] def cast(self, data): return data def validate(self, data): data = self.cast(data) for validator in self.validators: data = validator(data) return data def __call__(self, *validators, **options): obj = object.__new__(self.__class__) obj.__dict__.update(self.__dict__) obj.validators += list(validators) obj.__dict__.update(options) return obj class IntField(Field): def cast(self, data): return b_int(data) class TextField(Field): def __init__(self, encoding='utf-8'): Field.__init__(self) self.encoding = encoding def cast(self, data): return text(data, encoding) any = Field() int = IntField() str = TextField()
{ "repo_name": "baverman/former", "path": "former/types.py", "copies": "1", "size": "1371", "license": "mit", "hash": 1585133809359635700, "line_mean": 19.1617647059, "line_max": 47, "alpha_frac": 0.5820568928, "autogenerated": false, "ratio": 3.997084548104956, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5079141440904956, "avg_score": null, "num_lines": null }
from functools import wraps from concurrent.futures import ThreadPoolExecutor class Tomorrow(): def __init__(self, future, timeout): self._future = future self._timeout = timeout def __getattr__(self, name): if name == '_wait': return self._future.result elif name == '_timeout': return self._timeout else: result = self._future.result(self._timeout) return result.__getattribute__(name) def async(n, base_type, timeout=None): def decorator(f): if isinstance(n, int): pool = base_type(n) elif isinstance(n, base_type): pool = n else: raise TypeError( "Invalid type: %s" % type(base_type) ) @wraps(f) def wrapped(*args, **kwargs): return Tomorrow( pool.submit(f, *args, **kwargs), timeout=timeout ) return wrapped return decorator def threads(n, timeout=None): return async(n, ThreadPoolExecutor, timeout)
{ "repo_name": "samstav/Tomorrow", "path": "tomorrow/__init__.py", "copies": "1", "size": "1110", "license": "mit", "hash": -2296204235725220400, "line_mean": 24.2272727273, "line_max": 55, "alpha_frac": 0.5306306306, "autogenerated": false, "ratio": 4.475806451612903, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5506437082212903, "avg_score": null, "num_lines": null }
from functools import wraps from concurrent.futures import ThreadPoolExecutor class Tomorrow(): def __init__(self, future, timeout): self._future = future self._timeout = timeout def __getattr__(self, name): result = self._future.result(self._timeout) return result.__getattribute__(name) def _wait(self): return self._future.result(self._timeout) def async(n, base_type, timeout=None): def decorator(f): if isinstance(n, int): pool = base_type(n) elif isinstance(n, base_type): pool = n else: raise TypeError( "Invalid type: %s" % type(base_type) ) @wraps(f) def wrapped(*args, **kwargs): return Tomorrow( pool.submit(f, *args, **kwargs), timeout=timeout ) return wrapped return decorator def threads(n, timeout=None): return async(n, ThreadPoolExecutor, timeout)
{ "repo_name": "DOTOCA/Tomorrow", "path": "tomorrow/tomorrow.py", "copies": "1", "size": "1031", "license": "mit", "hash": -618548139918180500, "line_mean": 23.5476190476, "line_max": 51, "alpha_frac": 0.5480116392, "autogenerated": false, "ratio": 4.331932773109243, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5379944412309243, "avg_score": null, "num_lines": null }
from functools import wraps from corehq.apps.userreports.exceptions import BadSpecError def equal(input, reference): return input == reference def not_equal(input, reference): return input != reference def in_multiselect(input, reference): return reference in (input or '').split(' ') def any_in_multiselect(input, reference): return any([subval in (input or '').split(' ') for subval in reference]) def less_than(input, reference): return input < reference def less_than_equal(input, reference): return input <= reference def greater_than(input, reference): return input > reference def greater_than_equal(input, reference): return input >= reference def in_(input, reference): return input in reference OPERATORS = { 'eq': equal, 'not_eq': not_equal, 'in': in_, 'in_multi': in_multiselect, 'any_in_multi': any_in_multiselect, 'lt': less_than, 'lte': less_than_equal, 'gt': greater_than, 'gte': greater_than_equal, } def get_operator(slug): def _get_safe_operator(fn): @wraps(fn) def _safe_operator(input, reference): try: return fn(input, reference) except TypeError: return False return _safe_operator try: return _get_safe_operator(OPERATORS[slug.lower()]) except KeyError: raise BadSpecError('{0} is not a valid operator. Choices are {1}'.format( slug, ', '.join(OPERATORS.keys()), ))
{ "repo_name": "qedsoftware/commcare-hq", "path": "corehq/apps/userreports/operators.py", "copies": "1", "size": "1525", "license": "bsd-3-clause", "hash": 5396227295519320000, "line_mean": 20.7857142857, "line_max": 81, "alpha_frac": 0.6249180328, "autogenerated": false, "ratio": 3.7841191066997517, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4909037139499751, "avg_score": null, "num_lines": null }
from functools import wraps from .core import Sort, Attribute from .exceptions import ArgumentError, RewritingError class Strategy(Sort): pass def set_operation(fn): @wraps(fn) def wrapper(self, terms): if not isinstance(terms, (set, frozenset)): terms = set([terms]) rv = set() for term in terms: term = fn(self, term) if isinstance(term, (set, frozenset)): rv |= term else: rv.add(term) return rv return wrapper def make_strategy(fn): def __call__(self, term): if fn(term) is None: print(fn) return fn(term) return type(fn.__name__, (Strategy,), {'__call__': set_operation(__call__)})() identity = type('identity', (Strategy,), {'__call__': set_operation(lambda self, term: term)})() class union(Strategy): left = Attribute(domain=Strategy) right = Attribute(domain=Strategy) def __init__(self, *operands): if len(operands) < 2: raise ArgumentError('%s requires at least 2 operands.' % self.__class__.__name__) elif len(operands) == 2: super().__init__(left=operands[0], right=operands[1]) else: super().__init__(left=operands[0], right=union(*operands[1:])) def __call__(self, terms): if not isinstance(terms, (set, frozenset)): terms = set([terms]) return self.left(terms) | self.right(terms) class fixpoint(Strategy): f = Attribute(domain=Strategy) def __call__(self, terms): if not isinstance(terms, (set, frozenset)): terms = set([terms]) rv = self.f(terms) while rv != terms: terms = rv rv = self.f(terms) return rv class try_(Strategy): f = Attribute(domain=Strategy) def __call__(self, terms): if not isinstance(terms, (set, frozenset)): terms = set([terms]) rv = set() for term in terms: try: rv |= self.f(term) except RewritingError: rv.add(term) return rv try: return self.f(terms) except RewritingError: return terms
{ "repo_name": "kyouko-taiga/stew", "path": "stew/strategies.py", "copies": "1", "size": "2251", "license": "apache-2.0", "hash": 1766211907181539800, "line_mean": 22.9468085106, "line_max": 96, "alpha_frac": 0.5375388716, "autogenerated": false, "ratio": 4.100182149362477, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5137721020962477, "avg_score": null, "num_lines": null }
from functools import wraps from defer import inline_callbacks, defer, return_value from pycloudia.rest.consts import SPEC_ATTRIBUTE_NAME, METHOD, RENDERER from pycloudia.rest.spec import Spec from pycloudia.utils.decorators import generate_list, generate_dict __all__ = ['rest', 'jsonify'] def get_or_create_spec(func): """ :rtype: L{pycloudia.rest.spec.Spec} """ if not hasattr(func, SPEC_ATTRIBUTE_NAME): setattr(func, SPEC_ATTRIBUTE_NAME, Spec()) return getattr(func, SPEC_ATTRIBUTE_NAME) class Rest(object): class Error(object): @staticmethod def http(exception_cls, status_code, message=None): """ :type exception_cls: C{type} :type status_code: C{int} :type message: C{basestring} :rtype: C{Callable} """ def decorator(func): spec = get_or_create_spec(func) spec.exception_list.append((exception_cls, status_code, message)) return func return decorator @staticmethod def resolve(exception_cls, resolve_func): """ :type exception_cls: C{type} :type resolve_func: C{Callable} :rtype: C{Callable} """ def decorator(func): spec = get_or_create_spec(func) spec.exception_list.append((exception_cls, resolve_func)) return func return decorator class Handler(object): def get(self, resource): """ :type resource: C{str} :rtype: C{Callable} """ return self._create_http_method_decorator(METHOD.GET, resource) def post(self, resource): """ :type resource: C{str} :rtype: C{Callable} """ return self._create_http_method_decorator(METHOD.POST, resource) @staticmethod def _create_http_method_decorator(http_method, resource): """ :type http_method: C{str} :type resource: C{str} :rtype: C{Callable} """ def decorator(func): spec = get_or_create_spec(func) spec.http_method = http_method spec.resource = resource return func return decorator class Renderer(object): @staticmethod def jsonp(argument='jsoncallback'): """ :type argument: C{str} """ def decorator(func): spec = get_or_create_spec(func) spec.renderer = (RENDERER.JSONP, argument) return func return decorator @staticmethod def json(): def decorator(func): spec = get_or_create_spec(func) spec.renderer = (RENDERER.JSON, ) return func return decorator handler = Handler() error = Error() renderer = Renderer() class Jsonifier(object): @staticmethod def item(encode_func): """ :type encode_func: C{Callable} """ def http_jsonify_call(func): @wraps(func) @inline_callbacks def http_jsonify_decorator(*args, **kwargs): obj = yield defer(func, *args, **kwargs) return_value(encode_func(obj)) return http_jsonify_decorator return http_jsonify_call @staticmethod def list(encode_func): """ :type encode_func: C{Callable} """ @generate_list def encode_list(obj_list): for obj in obj_list: yield encode_func(obj) def http_jsonify_list_call(func): @wraps(func) @inline_callbacks def http_jsonify_list_decorator(*args, **kwargs): obj_list = yield defer(func, *args, **kwargs) return_value(encode_list(obj_list)) return http_jsonify_list_decorator return http_jsonify_list_call @staticmethod def dict(encode_func): """ :type encode_func: C{Callable} """ @generate_dict def encode_dict(obj_dict): for key, obj in obj_dict.iteritems(): yield key, encode_func(obj) def http_jsonify_dict_call(func): @wraps(func) @inline_callbacks def http_jsonify_dict_decorator(*args, **kwargs): obj_dict = yield defer(func, *args, **kwargs) return_value(encode_dict(obj_dict)) return http_jsonify_dict_decorator return http_jsonify_dict_call jsonify = Jsonifier() rest = Rest()
{ "repo_name": "cordis/pycloudia", "path": "pycloudia/rest/decorators.py", "copies": "1", "size": "4775", "license": "mit", "hash": -1029178175978256800, "line_mean": 28.475308642, "line_max": 81, "alpha_frac": 0.5331937173, "autogenerated": false, "ratio": 4.2520035618878005, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00007527853056308341, "num_lines": 162 }
from functools import wraps from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.views import redirect_to_login from django.core.exceptions import PermissionDenied, ImproperlyConfigured, FieldError from django.shortcuts import get_object_or_404 from django.utils import six from django.utils.decorators import available_attrs from django.utils.encoding import force_text try: from django.contrib.auth import mixins except ImportError: # pragma: no cover # Django < 1.9 from ..compat import access_mixins as mixins # These are made available for convenience, as well as for use in Django # versions before 1.9. For usage help see Django's docs for 1.9 or later. LoginRequiredMixin = mixins.LoginRequiredMixin UserPassesTestMixin = mixins.UserPassesTestMixin class PermissionRequiredMixin(mixins.PermissionRequiredMixin): """ CBV mixin to provide object-level permission checking to views. Best used with views that inherit from ``SingleObjectMixin`` (``DetailView``, ``UpdateView``, etc.), though not required. The single requirement is for a ``get_object`` method to be available in the view. If there's no ``get_object`` method, permission checking is model-level, that is exactly like Django's ``PermissionRequiredMixin``. """ def get_permission_object(self): """ Override this method to provide the object to check for permission against. By default uses ``self.get_object()`` as provided by ``SingleObjectMixin``. Returns None if there's no ``get_object`` method. """ try: # Requires SingleObjectMixin or equivalent ``get_object`` method return self.get_object() except AttributeError: # pragma: no cover return None def has_permission(self): obj = self.get_permission_object() perms = self.get_permission_required() return self.request.user.has_perms(perms, obj) def objectgetter(model, attr_name='pk', field_name='pk'): """ Helper that returns a function suitable for use as the ``fn`` argument to the ``permission_required`` decorator. ``model`` can be a model class, manager or queryset. ``attr_name`` is the name of the view attribute. ``field_name`` is the model's field name by which the lookup is made, eg. "id", "slug", etc. """ def _getter(request, *view_args, **view_kwargs): if attr_name not in view_kwargs: raise ImproperlyConfigured( 'Argument {0} is not available. Given arguments: [{1}]' .format(attr_name, ', '.join(view_kwargs.keys()))) try: return get_object_or_404(model, **{field_name: view_kwargs[attr_name]}) except FieldError: raise ImproperlyConfigured( 'Model {0} has no field named {1}' .format(model, field_name)) return _getter def permission_required(perm, fn=None, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME): """ View decorator that checks for the given permissions before allowing the view to execute. Use it like this:: from django.shortcuts import get_object_or_404 from rules.contrib.views import permission_required from posts.models import Post def get_post_by_pk(request, post_id): return get_object_or_404(Post, pk=post_id) @permission_required('posts.change_post', fn=get_post_by_pk) def post_update(request, post_id): # ... ``perm`` is either a permission name as a string, or a list of permission names. ``fn`` is an optional callback that receives the same arguments as those passed to the decorated view and must return the object to check permissions against. If omitted, the decorator behaves just like Django's ``permission_required`` decorator, i.e. checks for model-level permissions. ``raise_exception`` is a boolean specifying whether to raise a ``django.core.exceptions.PermissionDenied`` exception if the check fails. You will most likely want to set this argument to ``True`` if you have specified a custom 403 response handler in your urlconf. If ``False``, the user will be redirected to the URL specified by ``login_url``. ``login_url`` is an optional custom URL to redirect the user to if permissions check fails. If omitted or empty, ``settings.LOGIN_URL`` is used. """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): # Normalize to a list of permissions if isinstance(perm, six.string_types): perms = (perm,) else: perms = perm # Get the object to check permissions against if callable(fn): obj = fn(request, *args, **kwargs) else: obj = fn # Get the user user = request.user # Check for permissions and return a response if not user.has_perms(perms, obj): # User does not have a required permission if raise_exception: raise PermissionDenied() else: return _redirect_to_login(request, view_func.__name__, login_url, redirect_field_name) else: # User has all required permissions -- allow the view to execute return view_func(request, *args, **kwargs) return _wrapped_view return decorator def _redirect_to_login(request, view_name, login_url, redirect_field_name): redirect_url = login_url or settings.LOGIN_URL if not redirect_url: # pragma: no cover raise ImproperlyConfigured( 'permission_required({0}): You must either provide ' 'the "login_url" argument to the "permission_required" ' 'decorator or configure settings.LOGIN_URL'.format(view_name) ) redirect_url = force_text(redirect_url) return redirect_to_login(request.get_full_path(), redirect_url, redirect_field_name)
{ "repo_name": "smcoll/django-rules", "path": "rules/contrib/views.py", "copies": "1", "size": "6294", "license": "mit", "hash": -4405005259050757000, "line_mean": 38.835443038, "line_max": 119, "alpha_frac": 0.6480775342, "autogenerated": false, "ratio": 4.379958246346555, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0003509344068567397, "num_lines": 158 }
from functools import wraps from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponseRedirect, HttpResponseForbidden from django.shortcuts import render_to_response, get_object_or_404 from django.utils.http import urlquote from ietf.ietfauth.utils import has_role from ietf.doc.models import Document from ietf.group.models import Group, Role from ietf.meeting.models import Session from ietf.secr.utils.meeting import get_timeslot def clear_non_auth(session): """ Clears non authentication related keys from the session object """ for key in session.keys(): if not key.startswith('_auth'): del session[key] def check_for_cancel(redirect_url): """ Decorator to make a view redirect to the given url if the reuqest is a POST which contains a submit=Cancel. """ def decorator(func): @wraps(func) def inner(request, *args, **kwargs): if request.method == 'POST' and request.POST.get('submit',None) == 'Cancel': clear_non_auth(request.session) return HttpResponseRedirect(redirect_url) return func(request, *args, **kwargs) return inner return decorator def check_permissions(func): """ View decorator for checking that the user is logged in and has access to the object being requested. Expects one of the following four keyword arguments: acronym: a group acronym session_id: a session id (used for sessions of type other or plenary) meeting_id, slide_id """ def wrapper(request, *args, **kwargs): if not request.user.is_authenticated(): return HttpResponseRedirect('%s?%s=%s' % (settings.LOGIN_URL, REDIRECT_FIELD_NAME, urlquote(request.get_full_path()))) session = None # short circuit. secretariat user has full access if has_role(request.user,'Secretariat'): return func(request, *args, **kwargs) # get the parent group if 'acronym' in kwargs: acronym = kwargs['acronym'] group = get_object_or_404(Group,acronym=acronym) elif 'session_id' in kwargs: session = get_object_or_404(Session, id=kwargs['session_id']) group = session.group elif 'slide_id' in kwargs: slide = get_object_or_404(Document, name=kwargs['slide_id']) session = slide.session_set.all()[0] group = session.group try: login = request.user.person except ObjectDoesNotExist: return HttpResponseForbidden("User not authorized to access group: %s" % group.acronym) groups = [group] if group.parent: groups.append(group.parent) all_roles = Role.objects.filter(group__in=groups,name__in=('ad','chair','secr')) if login in [ r.person for r in all_roles ]: return func(request, *args, **kwargs) # if session is plenary allow ietf/iab chairs if session and get_timeslot(session).type.slug=='plenary': chair = login.role_set.filter(name='chair',group__acronym__in=('iesg','iab','ietf-trust','iaoc')) admdir = login.role_set.filter(name='admdir',group__acronym='ietf') if chair or admdir: return func(request, *args, **kwargs) # if we get here access is denied return HttpResponseForbidden("User not authorized to access group: %s" % group.acronym) return wraps(func)(wrapper) def sec_only(func): """ This decorator checks that the user making the request is a secretariat user. """ def wrapper(request, *args, **kwargs): # short circuit. secretariat user has full access if has_role(request.user, "Secretariat"): return func(request, *args, **kwargs) return render_to_response('unauthorized.html',{ 'user_name':request.user.person} ) return wraps(func)(wrapper)
{ "repo_name": "wpjesus/codematch", "path": "ietf/secr/utils/decorators.py", "copies": "1", "size": "4106", "license": "bsd-3-clause", "hash": 3047110548831974400, "line_mean": 37.7358490566, "line_max": 130, "alpha_frac": 0.6395518753, "autogenerated": false, "ratio": 3.9480769230769233, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5087628798376923, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.core.exceptions import PermissionDenied from django.shortcuts import resolve_url from django.utils import six from django.utils.decorators import available_attrs from django.utils.six.moves.urllib.parse import urlparse def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() from django.contrib.auth.views import redirect_to_login return redirect_to_login( path, resolved_login_url, redirect_field_name) return _wrapped_view return decorator def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated(), login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator def permission_required(perm, login_url=None, raise_exception=False): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised. """ def check_perms(user): if isinstance(perm, six.string_types): perms = (perm, ) else: perms = perm # First check if the user has the permission (even anon users) if user.has_perms(perms): return True # In case the 403 handler should be called raise the exception if raise_exception: raise PermissionDenied # As the last resort, show the login form return False return user_passes_test(check_perms, login_url=login_url)
{ "repo_name": "GitAngel/django", "path": "django/contrib/auth/decorators.py", "copies": "356", "size": "3049", "license": "bsd-3-clause", "hash": 1720121370879008300, "line_mean": 39.6533333333, "line_max": 91, "alpha_frac": 0.6667759921, "autogenerated": false, "ratio": 4.2703081232493, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.contrib.auth.mixins import PermissionRequiredMixin as DjangoPermissionRequiredMixin from django.contrib.auth.models import Permission from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404, resolve_url from django.utils import six from django.utils.decorators import available_attrs from django.utils.six.moves.urllib.parse import urlparse DEFAULT_403 = getattr(settings, 'DJEM_DEFAULT_403', False) def get_user_log_verbosity(): return getattr(settings, 'DJEM_PERM_LOG_VERBOSITY', 0) class ObjectPermissionsBackend(object): def authenticate(self, *args, **kwargs): return None def _get_model_permission(self, perm, user_obj): verbosity = get_user_log_verbosity() if not verbosity: access = user_obj.has_perm(perm) else: access = user_obj.logged_has_perm(perm) # Add the log from the model-level check to the log for the # object-level check, replacing the "result" line log = user_obj.get_last_log(raw=True) log.pop() log.append('Model-level Result: {}\n'.format('Granted' if access else 'Denied')) user_obj.log(*log) return access def _get_object_permission(self, perm, user_obj, obj, from_name): """ Test if a user has a permission on a specific model object. ``from_name`` can be either "user" or "group", to determine permissions using the user object itself or the groups it belongs to, respectively. """ if not user_obj.is_active: # pragma: no cover # An inactive user won't normally get this far as they would not # pass the model-level permissions check return False try: perm_cache = user_obj._olp_cache except AttributeError: # OLP cache dictionary will not exist by default if not using # OLPMixin and no permissions have yet been checked on this user # object perm_cache = user_obj._olp_cache = {} perm_cache_name = '{0}-{1}-{2}'.format(from_name, perm, obj.pk) if perm_cache_name not in perm_cache: access_fn_name = '_{0}_can_{1}'.format( from_name, perm.split('.')[-1] ) access_fn = getattr(obj, access_fn_name, None) if not access_fn: # No function defined on obj to determine access - assume # access should be granted if no explicit object-level logic # exists to determine otherwise access = None else: try: if from_name == 'user': access = access_fn(user_obj) else: access = access_fn(user_obj.groups.all()) except PermissionDenied: access = False perm_cache[perm_cache_name] = access return perm_cache[perm_cache_name] def _get_object_permissions(self, user_obj, obj, from_name=None): """ Return a set of the permissions a user has on a specific model object. ``from_name`` can be either "user" or "group", to determine permissions using the user object itself or the groups it belongs to, respectively. It can also be None to determine the users permissions from both sources. """ if not obj or not user_obj.is_active or user_obj.is_anonymous: return set() perms_for_model = Permission.objects.filter( content_type__app_label=obj._meta.app_label, content_type__model=obj._meta.model_name, ).values_list('content_type__app_label', 'codename') perms_for_model = ['{0}.{1}'.format(app, name) for app, name in perms_for_model] if user_obj.is_superuser and not getattr(settings, 'DJEM_UNIVERSAL_OLP', False): # Superusers get all permissions, regardless of obj or from_name, # unless using "universal" OLP, in which case they are subject to # the same OLP logic as regular users perms = set(perms_for_model) else: # If using any level of automated logging for permissions, create a # temporary log to act as the target for any log entries (either # automatic entries appended by this backend or any manual entries # that may be present in object-level access methods). The usual # automatic log started as part of OLPMixin.has_perm() will not # have been created, so this acts as a replacement. log_verbosity = get_user_log_verbosity() if log_verbosity: user_obj.start_log('temp-{0}'.format(obj.pk)) perms = set() for perm in perms_for_model: if not self._get_model_permission(perm, user_obj): continue user_access = None group_access = None # Check user first, unless only checking for group if from_name != 'group': user_access = self._get_object_permission(perm, user_obj, obj, 'user') # Check group if user didn't grant the permission, unless only # checking for user if not user_access and from_name != 'user': group_access = self._get_object_permission(perm, user_obj, obj, 'group') # The permission is granted if either of the user or group # checks grant it, or if neither of them have a defined # object-level access method if user_access or group_access or (user_access is None and group_access is None): perms.add(perm) # Remove the temporary log, if one was created if log_verbosity: user_obj.discard_log() return perms def get_user_permissions(self, user_obj, obj=None): return self._get_object_permissions(user_obj, obj, 'user') def get_group_permissions(self, user_obj, obj=None): return self._get_object_permissions(user_obj, obj, 'group') def get_all_permissions(self, user_obj, obj=None): return self._get_object_permissions(user_obj, obj) def has_perm(self, user_obj, perm, obj=None): if not obj: return False # not dealing with non-object permissions if not self._get_model_permission(perm, user_obj): return False user_access = self._get_object_permission(perm, user_obj, obj, 'user') group_access = None # Check group if user didn't grant the permission if not user_access: group_access = self._get_object_permission(perm, user_obj, obj, 'group') # The permission is granted if either of the user or group # checks grant it, or if neither of them have a defined # object-level access method return user_access or group_access or (user_access is None and group_access is None) def _check_perms(perms, user, view_kwargs): for perm in perms: if isinstance(perm, six.string_types): obj = None else: perm, obj_arg = perm # expand two-tuple obj_pk = view_kwargs[obj_arg] # Get the model this permission belongs to try: perm_app, perm_code = perm.split('.') perm_obj = Permission.objects.get( content_type__app_label=perm_app, codename=perm_code ) except (ValueError, Permission.DoesNotExist): # Treat malformed (missing a '.') or non-existent # permission names as permission denied raise PermissionDenied model = perm_obj.content_type.model_class() # Get the object instance using the inferred model and the # primary key passed to the view obj = get_object_or_404(model, pk=obj_pk) # Swap out the primary key with the instance itself in the view # kwargs, so the view doesn't have to query for it again view_kwargs[obj_arg] = obj if not user.has_perm(perm, obj): raise PermissionDenied def permission_required(*perms, **kwargs): """ Replacement for Django's ``permission_required`` decorator, providing support for object-level permissions. Instead of accepting either a string or an iterable of strings naming the permission/s to check, this version accepts multiple positional arguments, one for each permission to check. These arguments can be either strings or two-tuples. If two-tuples, the items should be: - a string naming the permission to check (in the <app label>.<permission code> format) - a string naming the keyword argument of the view that contains the primary key of the object to check the permission against Behaviour of the ``login_url`` and ``raise_exception`` keyword arguments is as per the original, except that the default value for ``raise_exception`` can be specified with the ``DJEM_DEFAULT_403`` setting. """ login_url = kwargs.pop('login_url', None) raise_exception = kwargs.pop('raise_exception', DEFAULT_403) def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): # First, check if the user has the permission (even anon users) try: _check_perms(perms, request.user, kwargs) except PermissionDenied: # In case the 403 handler should be called, raise the exception if raise_exception: raise else: return view_func(request, *args, **kwargs) # As the last resort, show the login form path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() from django.contrib.auth.views import redirect_to_login return redirect_to_login(path, resolved_login_url) return _wrapped_view return decorator class PermissionRequiredMixin(DjangoPermissionRequiredMixin): """ CBV mixin which verifies that the current user has all specified permissions, on the specified object where applicable. """ raise_exception = DEFAULT_403 def has_permission(self, view_kwargs): perms = self.get_permission_required() try: _check_perms(perms, self.request.user, view_kwargs) except PermissionDenied: return False else: return True # Overridden to pass kwargs to has_permission() and skip the immediate # parent's dispatch() when calling the super method (because it attempts # to call has_permission without the kwargs). def dispatch(self, request, *args, **kwargs): if not self.has_permission(kwargs): return self.handle_no_permission() return super(DjangoPermissionRequiredMixin, self).dispatch(request, *args, **kwargs)
{ "repo_name": "oogles/djem", "path": "djem/auth.py", "copies": "2", "size": "12369", "license": "bsd-3-clause", "hash": 3288527703864673000, "line_mean": 39.4215686275, "line_max": 97, "alpha_frac": 0.5821812596, "autogenerated": false, "ratio": 4.617021276595745, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6199202536195745, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models as django_models from django.db import transaction from django.utils.translation import ugettext_lazy as _ from rest_framework import response, status from waldur_core.core import models def ensure_atomic_transaction(func): @wraps(func) def wrapped(self, *args, **kwargs): if settings.WALDUR_CORE['USE_ATOMIC_TRANSACTION']: with transaction.atomic(): return func(self, *args, **kwargs) else: return func(self, *args, **kwargs) return wrapped class AsyncExecutor: async_executor = True class CreateExecutorMixin(AsyncExecutor): create_executor = NotImplemented @ensure_atomic_transaction def perform_create(self, serializer): instance = serializer.save() self.create_executor.execute(instance, is_async=self.async_executor) instance.refresh_from_db() class UpdateExecutorMixin(AsyncExecutor): update_executor = NotImplemented def get_update_executor_kwargs(self, serializer): return {} @ensure_atomic_transaction def perform_update(self, serializer): instance = self.get_object() # Save all instance fields before update. # To avoid additional DB queries - store foreign keys as ids. # Warning! M2M fields will be ignored. before_update_fields = { f: getattr(instance, f.attname) for f in instance._meta.fields } super(UpdateExecutorMixin, self).perform_update(serializer) instance.refresh_from_db() updated_fields = { f.name for f, v in before_update_fields.items() if v != getattr(instance, f.attname) } kwargs = self.get_update_executor_kwargs(serializer) self.update_executor.execute( instance, is_async=self.async_executor, updated_fields=updated_fields, **kwargs ) serializer.instance.refresh_from_db() class DeleteExecutorMixin(AsyncExecutor): delete_executor = NotImplemented @ensure_atomic_transaction def destroy(self, request, *args, **kwargs): instance = self.get_object() self.delete_executor.execute( instance, is_async=self.async_executor, force=instance.state == models.StateMixin.States.ERRED, ) return response.Response( {'detail': _('Deletion was scheduled.')}, status=status.HTTP_202_ACCEPTED ) class ExecutorMixin(CreateExecutorMixin, UpdateExecutorMixin, DeleteExecutorMixin): """ Execute create/update/delete operation with executor """ pass class EagerLoadMixin: """ Reduce number of requests to DB. Serializer should implement static method "eager_load", that selects objects that are necessary for serialization. """ def get_queryset(self): queryset = super(EagerLoadMixin, self).get_queryset() serializer_class = self.get_serializer_class() if self.action in ('list', 'retrieve') and hasattr( serializer_class, 'eager_load' ): queryset = serializer_class.eager_load(queryset, self.request) return queryset class ScopeMixin(django_models.Model): class Meta: abstract = True content_type = django_models.ForeignKey( to=ContentType, on_delete=django_models.CASCADE, null=True, blank=True, related_name='+', ) object_id = django_models.PositiveIntegerField(null=True, blank=True) scope = GenericForeignKey('content_type', 'object_id')
{ "repo_name": "opennode/waldur-mastermind", "path": "src/waldur_core/core/mixins.py", "copies": "2", "size": "3807", "license": "mit", "hash": 3942699631682705000, "line_mean": 29.7016129032, "line_max": 85, "alpha_frac": 0.6593117941, "autogenerated": false, "ratio": 4.3508571428571425, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00018977958775408138, "num_lines": 124 }
from functools import wraps from django.conf import settings from django.core.cache import cache from django.db import DatabaseError from bedrock.events.models import Event CACHE_TIMEOUT = getattr(settings, 'EVENTS_CACHE_TIMEOUT', 15 * 60) def cache_memoized(obj): """ Uses the django default cache backend to memoize results from function, method, or class calls. Decorated function will accept a 'force_cache_refresh' kwarg which will do exactly that if True. Results must be pickleable. Caches results unique to args, but *not* to kwargs. """ @wraps(obj) def wrapped(*args, **kwargs): # NOTE: this ignores kwargs for caching purposes cache_key = ':'.join([__name__, obj.__name__] + [str(a) for a in args]) force_cache_refresh = kwargs.pop('force_cache_refresh', False) if not force_cache_refresh: cached = cache.get(cache_key) if cached is not None: return cached result = obj(*args, **kwargs) cache.set(cache_key, result, timeout=CACHE_TIMEOUT) return result return wrapped @cache_memoized def current_and_future_event_count(): try: return Event.objects.current_and_future().count() except DatabaseError: return 0 @cache_memoized def current_and_future_events(): try: return list(Event.objects.current_and_future()) except DatabaseError: return [] @cache_memoized def future_event_count(): try: return Event.objects.future().count() except DatabaseError: return 0 @cache_memoized def future_events(): try: return list(Event.objects.future()) except DatabaseError: return [] @cache_memoized def next_few_events(count): try: return list(Event.objects.future()[:count]) except DatabaseError: return [] def next_event(): # If there is no next event we want to return None, which # is not cacheable, but next_few_events will cache an empty list # for us in that case. events = next_few_events(1) return events[0] if events else None
{ "repo_name": "sylvestre/bedrock", "path": "bedrock/events/utils.py", "copies": "13", "size": "2122", "license": "mpl-2.0", "hash": -7289391493525333000, "line_mean": 25.525, "line_max": 82, "alpha_frac": 0.6573986805, "autogenerated": false, "ratio": 3.9812382739212007, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00015060240963855423, "num_lines": 80 }
from functools import wraps from django.conf import settings from django.core.cache import cache from django.template.response import ContentNotRenderedError def cache_view(view_func): @wraps(view_func) def _wrapped_view_func(view: 'CachedApiView', *args, **kwargs): request = view.request cache_key = view.get_cache_key() if not cache_key: cache_key = request.get_full_path() if view.add_language_code: try: language_code = request.LANGUAGE_CODE except AttributeError: language_code = settings.LANGUAGE_CODE cache_key += ':%s' % language_code cached_response = cache.get(cache_key) if cached_response and not request.user.is_authenticated: return cached_response response = view_func(view, *args, **kwargs) if response.status_code == 200 and not request.user.is_authenticated: try: set_cache_after_rendering(cache_key, response, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) except ContentNotRenderedError: response.add_post_render_callback( lambda r: set_cache_after_rendering(cache_key, r, settings.DJANGOCMS_SPA_CACHE_TIMEOUT) ) return response return _wrapped_view_func def set_cache_after_rendering(cache_key, response, timeout): cache.set(cache_key, response, timeout)
{ "repo_name": "dreipol/djangocms-spa", "path": "djangocms_spa/decorators.py", "copies": "1", "size": "1453", "license": "mit", "hash": 6800751179321883000, "line_mean": 31.2888888889, "line_max": 107, "alpha_frac": 0.6338609773, "autogenerated": false, "ratio": 4.081460674157303, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.000425783319072648, "num_lines": 45 }
from functools import wraps from django.conf import settings from django.core.cache import cache from bedrock.events.models import Event CACHE_TIMEOUT = getattr(settings, 'EVENTS_CACHE_TIMEOUT', 15 * 60) def cache_memoized(obj): """ Uses the django default cache backend to memoize results from function, method, or class calls. Decorated function will accept a 'force_cache_refresh' kwarg which will do exactly that if True. Results must be pickleable. Caches results unique to args, but *not* to kwargs. """ @wraps(obj) def wrapped(*args, **kwargs): # NOTE: this ignores kwargs for caching purposes cache_key = ':'.join([__name__, obj.__name__] + [str(a) for a in args]) force_cache_refresh = kwargs.pop('force_cache_refresh', False) if not force_cache_refresh: cached = cache.get(cache_key) if cached is not None: return cached result = obj(*args, **kwargs) cache.set(cache_key, result, timeout=CACHE_TIMEOUT) return result return wrapped @cache_memoized def current_and_future_event_count(): return Event.objects.current_and_future().count() @cache_memoized def current_and_future_events(): return list(Event.objects.current_and_future()) @cache_memoized def future_event_count(): return Event.objects.future().count() @cache_memoized def future_events(): return list(Event.objects.future()) @cache_memoized def next_few_events(count): return list(Event.objects.future()[:count]) def next_event(): # If there is no next event we want to return None, which # is not cacheable, but next_few_events will cache an empty list # for us in that case. events = next_few_events(1) return events[0] if events else None
{ "repo_name": "jpetto/bedrock", "path": "bedrock/events/utils.py", "copies": "6", "size": "1803", "license": "mpl-2.0", "hash": 7782512981520071000, "line_mean": 27.171875, "line_max": 82, "alpha_frac": 0.6777592901, "autogenerated": false, "ratio": 3.78781512605042, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.746557441615042, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.core.exceptions import ValidationError from django.http import HttpResponse import django.views.decorators.csrf import yaml from canvas import url_util from canvas.exceptions import ServiceError, DeactivatedUserError from canvas.shortcuts import r2r_jinja from canvas.util import ArgSpec, simple_decorator, loads, client_dumps, JSONDecodeError api_functions = set() def ServiceResponse(request, response, **kwargs): """ Serializes the response to primarily JSON, but you can force it to produce YAML by sending a format=yaml request variable. """ formatted_response = client_dumps(response, viewer=request.user) def get_yaml(): return yaml.safe_dump(loads(formatted_response), default_flow_style=False) if request.POST.get('format') == 'yaml': formatted_response = get_yaml() elif request.POST.get('format') == 'html': return r2r_jinja('api_response.html', {'yaml': get_yaml()}) # Allows us to force a mimetype in a request arg. mimetype = request.POST.get('force_mimetype', 'application/json') return HttpResponse(formatted_response, mimetype, **kwargs) def JSONPResponse(request, response, **kwargs): callback = request.GET.get('callback', 'callback') if not callback.replace('_', '').isalnum(): raise ServiceError() return HttpResponse('%s(%s);' % (callback, client_dumps(response, viewer=request.user)), mimetype='application/javascript', **kwargs) def json_response(view): @wraps(view) def view_wrapper(request, *args, **kwargs): return _handle_json_response(view, ServiceResponse, request, *args, **kwargs) return view_wrapper def _handle_json_response(view, json_response_processor, request, *args, **kwargs): status_code = None try: response = view(request, *args, **kwargs) except (ServiceError, ValidationError, DeactivatedUserError,), se: response = se.to_json() status_code = getattr(se, 'status_code', None) else: if response is None: response = {} if isinstance(response, dict): response['success'] = True # If the response is not a dict, we're not going to serialize it as JSON since our JSON # services expect a "success" key. # # This is primarily so that we can handle returning an HTTP response from the view, for # redirects and the like. if isinstance(response, dict): response_kwargs = {} if status_code: response_kwargs['status_code'] = status_code return json_response_processor(request, response, **response_kwargs) return response def _bad_json_view(*args, **kwargs): raise ServiceError("malformed json") def _json_service_wrapper(json_response_processor, view): def view_wrapper(request, *args, **kwargs): try: body = request.body request.JSON = loads(body) if body else {} except JSONDecodeError as e: temp_view = _bad_json_view else: temp_view = view return _handle_json_response(temp_view, json_response_processor, request, *args, **kwargs) return view_wrapper #TODO use functools.wraps instead of simple_decorator @simple_decorator def json_service(view): return _json_service_wrapper(ServiceResponse, view) #TODO use functools.wraps def public_jsonp_service(view): """ More explicitly named to call attention to the extra little p """ return _json_service_wrapper(JSONPResponse, view) def is_api(view): return getattr(view, 'is_api', False) def api_response_wrapper(public_jsonp=False): return public_jsonp_service if public_jsonp else json_service def inner_api(url_decorator, force_csrf_exempt=True): def api(url, public_jsonp=False, skip_javascript=False, async=True, csrf_exempt=False): """ `url` is a static URL endpoint, not a regex pattern. Requires JSON payloads in the request's raw POST data (which doesn't need to be used by the view, but the POST headers can't be used for anything else.) `request.GET` is still usable (for when it makes XSS easier), but this decorator doesn't help with that by generating anything in canvas_api.js for it, as it does for the JSON parameters. This also doesn't support *args or **kwargs inside the API view's arguments yet (i.e. it won't generate anything in the JS API for these.) It does support explicitly named args and kwargs though. The kwargs are used to provide default values to optional params (or simply to make them optional without a default). The order of args in an API view's arg list doesn't actually matter (besides `request` being first), since the JS API sends everything as a JSON dictionary of arg name, value pairs (which is unordered.) If `public_jsonp` is True, this will return a JSONP response, and will work with GET. This is False by default -- the response is serialized into JSON, not JSONP, and POST is required. NOTE: This *must* be the first (outermost) decorator on the view. """ response_wrapper = api_response_wrapper(public_jsonp=public_jsonp) csrf_wrapper = django.views.decorators.csrf.csrf_exempt if (csrf_exempt or force_csrf_exempt or settings.API_CSRF_EXEMPT) else lambda f: f def decorator(func): try: func.url_name = u'api-{0}-{1}'.format(func.__module__, func.__name__) except AttributeError: func.url_name = None # We assume the function's arg specs don't change at runtime. Seems to be a reasonable assumption. If we # couldn't assume that, then our JS API could diverge from the actual function signatures. We can't have # that happening. So we just precompute it here. if not getattr(func, 'arg_spec', None): func.arg_spec = ArgSpec(func) if not public_jsonp: from canvas.view_guards import require_POST func = require_POST(func) # Mark it as an API. func.is_api = True func.async = async if not skip_javascript: api_functions.add((func.__name__, func)) @url_decorator(r'^' + url + r'$', name=func.url_name) @response_wrapper @csrf_wrapper @wraps(func) def wrapped_view(request): # JSON or REQUEST. The latter is to support the API console. payload = request.JSON if not payload: try: payload = request.REQUEST except AttributeError: pass args, kwargs = [], {} # Skip the `request` arg. for arg_name in func.arg_spec.args[1:]: try: args.append(payload[arg_name]) except KeyError: raise ServiceError("Request payload is missing a required parameter: " + arg_name) for kwarg_name in func.arg_spec.kwargs.iterkeys(): if kwarg_name in payload: kwargs[kwarg_name] = payload[kwarg_name] return func(request, *args, **kwargs) return wrapped_view return decorator return api def api_decorator(urls): """ Returns an API decorator for the given URL space. """ url_decorator = url_util.url_decorator(urls) return inner_api(url_decorator)
{ "repo_name": "drawquest/drawquest-web", "path": "website/canvas/api_decorators.py", "copies": "1", "size": "7676", "license": "bsd-3-clause", "hash": -6151146079242919000, "line_mean": 39.6137566138, "line_max": 146, "alpha_frac": 0.6377019281, "autogenerated": false, "ratio": 4.243228302929795, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5380930231029795, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.core import mail from django.test.utils import override_settings from mock import MagicMock, patch from nose.tools import eq_ from fjord.base.tests import TestCase, skip_if from fjord.translations import gengo_utils from fjord.translations.models import ( GengoHumanTranslator, GengoJob, GengoOrder, SuperModel ) from fjord.translations.tests import has_gengo_creds from fjord.translations.utils import translate @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class BaseGengoTestCase(TestCase): def setUp(self): gengo_utils.GENGO_LANGUAGE_CACHE = ( {u'opstat': u'ok', u'response': [ {u'unit_type': u'word', u'localized_name': u'Espa\xf1ol', u'lc': u'es', u'language': u'Spanish (Spain)'}, {u'unit_type': u'word', u'localized_name': u'Deutsch', u'lc': u'de', u'language': u'German'}, {u'unit_type': u'word', u'localized_name': u'English', u'lc': u'en', u'language': u'English'} ]}, (u'es', u'de', u'en') ) gengo_utils.GENGO_LANGUAGE_PAIRS_CACHE = [ (u'es', u'en'), (u'en', u'es-la'), (u'de', u'pl') ] super(BaseGengoTestCase, self).setUp() def account_balance(bal): def account_balance_handler(fun): @wraps(fun) def _account_balance_handler(*args, **kwargs): patcher = patch('fjord.translations.gengo_utils.Gengo') mocker = patcher.start() instance = mocker.return_value instance.getAccountBalance.return_value = { u'opstat': u'ok', u'response': { u'credits': str(bal), u'currency': u'USD' } } try: return fun(*args, **kwargs) finally: patcher.stop() return _account_balance_handler return account_balance_handler def guess_language(lang): def guess_language_handler(fun): @wraps(fun) def _guess_language_handler(*args, **kwargs): patcher = patch('fjord.translations.gengo_utils.requests') mocker = patcher.start() post_return = MagicMock() ret = { u'text_bytes_found': 10, u'opstat': u'ok', u'is_reliable': True, } if lang == 'un': ret.update({ u'detected_lang_code': u'un', u'details': [], u'detected_lang_name': u'Unknown' }) elif lang == 'es': ret.update({ u'detected_lang_code': u'es', u'details': [ [u'SPANISH', u'es', 62, 46.728971962616825], [u'ITALIAN', u'it', 38, 9.237875288683602] ], u'detected_lang_name': u'SPANISH' }) elif lang == 'el': ret.update({ u'detected_lang_code': u'el', u'details': [ [u'GREEK', u'el', 62, 46.728971962616825], [u'ITALIAN', u'it', 38, 9.237875288683602] ], u'detected_lang_name': u'GREEK' }) elif lang == 'en': ret.update({ u'detected_lang_code': u'en', u'details': [ [u'ENGLISH', u'en', 62, 46.728971962616825], [u'ITALIAN', u'it', 38, 9.237875288683602] ], u'detected_lang_name': u'ENGLISH' }) post_return.json.return_value = ret mocker.post.return_value = post_return try: return fun(*args, **kwargs) finally: patcher.stop() return _guess_language_handler return guess_language_handler @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class GuessLanguageTest(BaseGengoTestCase): @guess_language('un') def test_guess_language_throws_error(self): gengo_api = gengo_utils.FjordGengo() self.assertRaises( gengo_utils.GengoUnknownLanguage, gengo_api.guess_language, u'Muy lento', ) @guess_language('es') def test_guess_language_returns_language(self): gengo_api = gengo_utils.FjordGengo() text = u'Facebook no se puede enlazar con peru' eq_(gengo_api.guess_language(text), u'es') @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class GetLanguagesTestCase(BaseGengoTestCase): def test_get_languages(self): response = { u'opstat': u'ok', u'response': [ {u'unit_type': u'word', u'localized_name': u'Espa\xf1ol', u'lc': u'es', u'language': u'Spanish (Spain)'} ] } gengo_utils.GENGO_LANGUAGE_CACHE = None with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: instance = GengoMock.return_value instance.getServiceLanguages.return_value = response # Make sure the cache is empty eq_(gengo_utils.GENGO_LANGUAGE_CACHE, None) # Test that we generate a list based on what we think the # response is. gengo_api = gengo_utils.FjordGengo() eq_(gengo_api.get_languages(), (u'es',)) # Test that the new list is cached. eq_(gengo_utils.GENGO_LANGUAGE_CACHE, (response, (u'es',))) @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class GetLanguagePairsTestCase(BaseGengoTestCase): def test_get_language_pairs(self): resp = { u'opstat': u'ok', u'response': [ {u'tier': u'standard', u'lc_tgt': u'es-la', u'lc_src': u'en', u'unit_price': u'0.05', u'currency': u'USD'}, {u'tier': u'ultra', u'lc_tgt': u'ar', u'lc_src': u'en', u'unit_price': u'0.15', u'currency': u'USD'}, {u'tier': u'pro', u'lc_tgt': u'ar', u'lc_src': u'en', u'unit_price': u'0.10', u'currency': u'USD'}, {u'tier': u'ultra', u'lc_tgt': u'es', u'lc_src': u'en', u'unit_price': u'0.15', u'currency': u'USD'}, {u'tier': u'standard', u'lc_tgt': u'pl', u'lc_src': u'de', u'unit_price': u'0.05', u'currency': u'USD'} ] } gengo_utils.GENGO_LANGUAGE_PAIRS_CACHE = None with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: instance = GengoMock.return_value instance.getServiceLanguagePairs.return_value = resp # Make sure the cache is empty eq_(gengo_utils.GENGO_LANGUAGE_PAIRS_CACHE, None) # Test that we generate a list based on what we think the # response is. gengo_api = gengo_utils.FjordGengo() eq_(gengo_api.get_language_pairs(), [(u'en', u'es-la'), (u'de', u'pl')]) # Test that the new list is cached. eq_(gengo_utils.GENGO_LANGUAGE_PAIRS_CACHE, [(u'en', u'es-la'), (u'de', u'pl')]) @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class GetBalanceTestCase(BaseGengoTestCase): @account_balance(20.0) def test_get_balance(self): gengo_api = gengo_utils.FjordGengo() eq_(gengo_api.get_balance(), 20.0) @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class MachineTranslateTestCase(BaseGengoTestCase): def test_machine_translate(self): with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: # Note: We're mocking with "Muy lento" because it's # short, but the Gengo language guesser actually can't # figure out what language that is. instance = GengoMock.return_value instance.postTranslationJobs.return_value = { u'opstat': u'ok', u'response': { u'jobs': { u'job_1': { u'status': u'approved', u'job_id': u'NULL', u'credits': 0, u'unit_count': 7, u'body_src': u'Muy lento', u'mt': 1, u'eta': -1, u'custom_data': u'10101', u'tier': u'machine', u'lc_tgt': u'en', u'lc_src': u'es', u'body_tgt': u'Very slow', u'slug': u'Input machine translation', u'ctime': u'2014-05-21 15:09:50.361847' } } } } gengo_api = gengo_utils.FjordGengo() text = u'Muy lento' eq_(gengo_api.machine_translate(1010, 'es', 'en', text), u'Very slow') def test_machine_translate_unsupported_lc_src(self): with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: gengo_api = gengo_utils.FjordGengo() self.assertRaises( gengo_utils.GengoUnsupportedLanguage, gengo_api.machine_translate, 1010, 'zh-tw', 'en', 'whatevs' ) eq_(GengoMock.return_value.postTranslationJobs.mock_calls, []) @guess_language('es') def test_translate_gengo_machine(self): with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: # Note: We're mocking with "Muy lento" because it's # short, but the Gengo language guesser actually can't # figure out what language that is. instance = GengoMock.return_value instance.postTranslationJobs.return_value = { u'opstat': u'ok', u'response': { u'jobs': { u'job_1': { u'status': u'approved', u'job_id': u'NULL', u'credits': 0, u'unit_count': 7, u'body_src': u'Muy lento', u'mt': 1, u'eta': -1, u'custom_data': u'10101', u'tier': u'machine', u'lc_tgt': u'en', u'lc_src': u'es', u'body_tgt': u'Very slow', u'slug': u'Input machine translation', u'ctime': u'2014-05-21 15:09:50.361847' } } } } obj = SuperModel(locale='es', desc=u'Muy lento') obj.save() eq_(obj.trans_desc, u'') translate(obj, 'gengo_machine', 'es', 'desc', 'en', 'trans_desc') eq_(obj.trans_desc, u'Very slow') @guess_language('un') def test_translate_gengo_machine_unknown_language(self): """Translation should handle unknown languages without erroring""" with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: gengo_mock_instance = GengoMock.return_value obj = SuperModel(locale='es', desc=u'Muy lento') obj.save() eq_(obj.trans_desc, u'') translate(obj, 'gengo_machine', 'es', 'desc', 'en', 'trans_desc') eq_(obj.trans_desc, u'') # Make sure we don't call postTranslationJobs(). eq_(gengo_mock_instance.postTranslationJobs.call_count, 0) @guess_language('es') def test_translate_gengo_machine_unsupported_language(self): """Translation should handle unsupported languages without erroring""" gengo_utils.GENGO_LANGUAGE_CACHE = ( {u'opstat': u'ok', u'response': [ {u'unit_type': u'word', u'localized_name': u'Deutsch', u'lc': u'de', u'language': u'German'} ]}, (u'de',) ) with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: gengo_mock_instance = GengoMock.return_value obj = SuperModel(locale='es', desc=u'Muy lento') obj.save() eq_(obj.trans_desc, u'') translate(obj, 'gengo_machine', 'es', 'desc', 'en', 'trans_desc') eq_(obj.trans_desc, u'') # Make sure we don't call postTranslationJobs(). eq_(gengo_mock_instance.postTranslationJobs.call_count, 0) @guess_language('en') def test_translate_gengo_machine_english_copy_over(self): """If the guesser guesses english, we copy it over""" with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: gengo_mock_instance = GengoMock.return_value obj = SuperModel(locale='es', desc=u'This is English.') obj.save() eq_(obj.trans_desc, u'') translate(obj, 'gengo_machine', 'es', 'desc', 'en', 'trans_desc') eq_(obj.trans_desc, u'This is English.') # Make sure we don't call postTranslationJobs(). eq_(gengo_mock_instance.postTranslationJobs.call_count, 0) @guess_language('es') def test_no_translate_if_disabled(self): """No GengoAPI calls if gengosystem switch is disabled""" with patch('fjord.translations.models.waffle') as waffle_mock: waffle_mock.switch_is_active.return_value = False with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: obj = SuperModel(locale='es', desc=u'Muy lento') obj.save() eq_(obj.trans_desc, u'') translate(obj, 'gengo_machine', 'es', 'desc', 'en', 'trans_desc') eq_(obj.trans_desc, u'') # We should not have used the API at all. eq_(GengoMock.called, False) @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class HumanTranslationTestCase(BaseGengoTestCase): @guess_language('es') def test_translate_gengo_human(self): # Note: This just sets up the GengoJob--it doesn't create any # Gengo human translation jobs. obj = SuperModel( locale='es', desc=u'Facebook no se puede enlazar con peru' ) obj.save() eq_(obj.trans_desc, u'') translate(obj, 'gengo_human', 'es', 'desc', 'en', 'trans_desc') # Nothing should be translated eq_(obj.trans_desc, u'') eq_(len(GengoJob.objects.all()), 1) @guess_language('es') def test_no_translate_if_disabled(self): """No GengoAPI calls if gengosystem switch is disabled""" with patch('fjord.translations.models.waffle') as waffle_mock: waffle_mock.switch_is_active.return_value = False with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: # Note: This just sets up the GengoJob--it doesn't # create any Gengo human translation jobs. obj = SuperModel( locale='es', desc=u'Facebook no se puede enlazar con peru' ) obj.save() eq_(obj.trans_desc, u'') translate(obj, 'gengo_human', 'es', 'desc', 'en', 'trans_desc') eq_(obj.trans_desc, u'') # Verify no jobs were created eq_(len(GengoJob.objects.all()), 0) # Verify we didn't call the API at all. eq_(GengoMock.called, False) @guess_language('en') def test_translate_gengo_human_english_copy_over(self): obj = SuperModel( locale='es', desc=u'This is English.' ) obj.save() eq_(obj.trans_desc, u'') translate(obj, 'gengo_human', 'es', 'desc', 'en', 'trans_desc') # If the guesser guesses English, then we just copy it over. eq_(obj.trans_desc, u'This is English.') @guess_language('el') def test_translate_gengo_human_unsupported_pair(self): obj = SuperModel( locale='el', desc=u'This is really greek.' ) obj.save() eq_(obj.trans_desc, u'') translate(obj, 'gengo_human', 'el', 'desc', 'en', 'trans_desc') # el -> en is not a supported pair, so it shouldn't get translated. eq_(obj.trans_desc, u'') @override_settings( ADMINS=(('Jimmy Discotheque', 'jimmy@example.com'),), GENGO_ACCOUNT_BALANCE_THRESHOLD=20.0 ) @account_balance(0.0) def test_push_translations_low_balance_mails_admin(self): """Tests that a low balance sends email and does nothing else""" # Verify nothing is in the outbox eq_(len(mail.outbox), 0) # Call push_translation which should balk and email the # admin ght = GengoHumanTranslator() ght.push_translations() # Verify an email got sent and no jobs were created eq_(len(mail.outbox), 1) eq_(GengoJob.objects.count(), 0) @override_settings(GENGO_ACCOUNT_BALANCE_THRESHOLD=20.0) def test_gengo_push_translations(self): """Tests GengoOrders get created""" ght = GengoHumanTranslator() # Create a few jobs covering multiple languages descs = [ ('es', u'Facebook no se puede enlazar con peru'), ('es', u'No es compatible con whatsap'), ('de', u'Absturze und langsam unter Android'), ] for lang, desc in descs: obj = SuperModel(locale=lang, desc=desc) obj.save() job = GengoJob( content_object=obj, src_field='desc', dst_field='trans_desc', src_lang=lang, dst_lang='en' ) job.save() with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: # FIXME: This returns the same thing both times, but to # make the test "more kosher" we'd have this return two # different order_id values. mocker = GengoMock.return_value mocker.getAccountBalance.return_value = { u'opstat': u'ok', u'response': { u'credits': '400.00', u'currency': u'USD' } } mocker.postTranslationJobs.return_value = { u'opstat': u'ok', u'response': { u'order_id': u'1337', u'job_count': 2, u'credits_used': u'0.35', u'currency': u'USD' } } ght.push_translations() eq_(GengoOrder.objects.count(), 2) order_by_id = dict( [(order.id, order) for order in GengoOrder.objects.all()] ) jobs = GengoJob.objects.all() for job in jobs: assert job.order_id in order_by_id @override_settings( ADMINS=(('Jimmy Discotheque', 'jimmy@example.com'),), GENGO_ACCOUNT_BALANCE_THRESHOLD=20.0 ) def test_gengo_push_translations_not_enough_balance(self): """Tests enough balance for one order, but not both""" ght = GengoHumanTranslator() # Create a few jobs covering multiple languages descs = [ ('es', u'Facebook no se puede enlazar con peru'), ('de', u'Absturze und langsam unter Android'), ] for lang, desc in descs: obj = SuperModel(locale=lang, desc=desc) obj.save() job = GengoJob( content_object=obj, src_field='desc', dst_field='trans_desc', src_lang=lang, dst_lang='en' ) job.save() with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: # FIXME: This returns the same thing both times, but to # make the test "more kosher" we'd have this return two # different order_id values. mocker = GengoMock.return_value mocker.getAccountBalance.return_value = { u'opstat': u'ok', u'response': { # Enough for one order, but dips below threshold # for the second one. u'credits': '20.30', u'currency': u'USD' } } mocker.postTranslationJobs.return_value = { u'opstat': u'ok', u'response': { u'order_id': u'1337', u'job_count': 2, u'credits_used': u'0.35', u'currency': u'USD' } } ght.push_translations() eq_(GengoOrder.objects.count(), 1) # The "it's too low" email only. eq_(len(mail.outbox), 1) with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: # FIXME: This returns the same thing both times, but to # make the test "more kosher" we'd have this return two # different order_id values. mocker = GengoMock.return_value mocker.getAccountBalance.return_value = { u'opstat': u'ok', u'response': { # This is the balance after one order. u'credits': '19.95', u'currency': u'USD' } } mocker.postTranslationJobs.return_value = { u'opstat': u'ok', u'response': { u'order_id': u'1337', u'job_count': 2, u'credits_used': u'0.35', u'currency': u'USD' } } # The next time push_translations runs, it shouldn't # create any new jobs, but should send an email. ght.push_translations() eq_(GengoOrder.objects.count(), 1) # This generates one more email. eq_(len(mail.outbox), 2) @override_settings( ADMINS=(('Jimmy Discotheque', 'jimmy@example.com'),), GENGO_ACCOUNT_BALANCE_THRESHOLD=20.0 ) def test_gengo_daily_activities_warning(self): """Tests warning email is sent""" ght = GengoHumanTranslator() with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: # FIXME: This returns the same thing both times, but to # make the test "more kosher" we'd have this return two # different order_id values. mocker = GengoMock.return_value mocker.getAccountBalance.return_value = { u'opstat': u'ok', u'response': { # Enough for one order, but dips below threshold # for the second one. u'credits': '30.00', u'currency': u'USD' } } ght.run_daily_activities() # The "balance is low warning" email only. eq_(len(mail.outbox), 1) @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class CompletedJobsForOrderTestCase(BaseGengoTestCase): def test_no_approved_jobs(self): gtoj_resp = { u'opstat': u'ok', u'response': { u'order': { u'jobs_pending': [u'746197'], u'jobs_revising': [], u'as_group': 0, u'order_id': u'263413', u'jobs_queued': u'0', u'total_credits': u'0.35', u'currency': u'USD', u'total_units': u'7', u'jobs_approved': [], u'jobs_reviewable': [], u'jobs_available': [], u'total_jobs': u'1' } } } with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: instance = GengoMock.return_value instance.getTranslationOrderJobs.return_value = gtoj_resp gengo_api = gengo_utils.FjordGengo() jobs = gengo_api.completed_jobs_for_order('263413') eq_(jobs, []) def test_approved_jobs(self): gtoj_resp = { u'opstat': u'ok', u'response': { u'order': { u'jobs_pending': [], u'jobs_revising': [], u'as_group': 0, u'order_id': u'263413', u'jobs_queued': u'0', u'total_credits': u'0.35', u'currency': u'USD', u'total_units': u'7', u'jobs_approved': [u'746197'], u'jobs_reviewable': [], u'jobs_available': [], u'total_jobs': u'1' } } } gtjb_resp = { u'opstat': u'ok', u'response': { u'jobs': [ { u'status': u'approved', u'job_id': u'746197', u'currency': u'USD', u'order_id': u'263413', u'body_tgt': u'Facebook can bind with peru', u'body_src': u'Facebook no se puede enlazar con peru', u'credits': u'0.35', u'eta': -1, u'custom_data': u'localhost||GengoJob||7', u'tier': u'standard', u'lc_tgt': u'en', u'lc_src': u'es', u'auto_approve': u'1', u'unit_count': u'7', u'slug': u'Mozilla Input feedback response', u'ctime': 1403296006 } ] } } with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: instance = GengoMock.return_value instance.getTranslationOrderJobs.return_value = gtoj_resp instance.getTranslationJobBatch.return_value = gtjb_resp gengo_api = gengo_utils.FjordGengo() jobs = gengo_api.completed_jobs_for_order('263413') eq_([item['custom_data'] for item in jobs], [u'localhost||GengoJob||7']) def test_pull_translations(self): ght = GengoHumanTranslator() obj = SuperModel(locale='es', desc=u'No es compatible con whatsap') obj.save() gj = GengoJob( content_object=obj, src_field='desc', dst_field='trans_desc', src_lang='es', dst_lang='en' ) gj.save() order = GengoOrder(order_id=u'263413') order.save() gj.assign_to_order(order) gtoj_resp = { u'opstat': u'ok', u'response': { u'order': { u'jobs_pending': [], u'jobs_revising': [], u'as_group': 0, u'order_id': u'263413', u'jobs_queued': u'0', u'total_credits': u'0.35', u'currency': u'USD', u'total_units': u'7', u'jobs_approved': [u'746197'], u'jobs_reviewable': [], u'jobs_available': [], u'total_jobs': u'1' } } } gtjb_resp = { u'opstat': u'ok', u'response': { u'jobs': [ { u'status': u'approved', u'job_id': u'746197', u'currency': u'USD', u'order_id': u'263413', u'body_tgt': u'No es compatible con whatsap', u'body_src': u'Not compatible with whatsap', u'credits': u'0.35', u'eta': -1, u'custom_data': u'localhost||GengoJob||{0}'.format( gj.id), u'tier': u'standard', u'lc_tgt': u'en', u'lc_src': u'es', u'auto_approve': u'1', u'unit_count': u'7', u'slug': u'Mozilla Input feedback response', u'ctime': 1403296006 } ] } } with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: instance = GengoMock.return_value instance.getTranslationOrderJobs.return_value = gtoj_resp instance.getTranslationJobBatch.return_value = gtjb_resp ght.pull_translations() jobs = GengoJob.objects.all() eq_(len(jobs), 1) eq_(jobs[0].status, 'complete') orders = GengoOrder.objects.all() eq_(len(orders), 1) eq_(orders[0].status, 'complete') def use_sandbox(fun): """Decorator to force the use of the sandbox This forces the test to use ths Gengo sandbox. This requires that you have GENGO_SANDBOX_PUBLIC_KEY and GENGO_SANDBOX_PRIVATE_KEY set up. If you don't, then they're made blank and the tests will fail and we will all freeze in an ice storm of biblical proportions! """ public_key = getattr(settings, 'GENGO_SANDBOX_PUBLIC_KEY', '') private_key = getattr(settings, 'GENGO_SANDBOX_PRIVATE_KEY', '') return override_settings( GENGO_PUBLIC_KEY=public_key, GENGO_PRIVATE_KEY=private_key, GENGO_USE_SANDBOX=True )(fun) @skip_if(lambda: not has_gengo_creds()) class LiveGengoTestCase(TestCase): """These are tests that execute calls against the real live Gengo API These tests require GENGO_PUBLIC_KEY and GENGO_PRIVATE_KEY to be valid values in your settings_local.py file. These tests will use the sandbox where possible, but otherwise use the real live Gengo API. Please don't fake the credentials since then you'll just get API authentication errors. These tests should be minimal end-to-end tests. """ def setUp(self): # Wipe out the caches gengo_utils.GENGO_LANGUAGE_CACHE = None gengo_utils.GENGO_LANGUAGE_PAIRS_CACHE = None super(LiveGengoTestCase, self).setUp() def test_get_language(self): text = u'Facebook no se puede enlazar con peru' gengo_api = gengo_utils.FjordGengo() eq_(gengo_api.guess_language(text), u'es') @skip_if(lambda: getattr(settings, 'GENGO_USE_SANDBOX', True)) def test_gengo_machine_translation(self): # Note: This doesn't work in the sandbox, so we skip it if # we're in sandbox mode. That is some happy horseshit, but so # it goes. # Note: This test might be brittle since it's calling out to # Gengo to do a machine translation and it's entirely possible # that they might return a different translation some day. obj = SuperModel( locale='es', desc=u'Facebook no se puede enlazar con peru' ) obj.save() eq_(obj.trans_desc, u'') translate(obj, 'gengo_machine', 'es', 'desc', 'en', 'trans_desc') eq_(obj.trans_desc, u'Facebook can bind with peru')
{ "repo_name": "DESHRAJ/fjord", "path": "fjord/translations/tests/test_gengo.py", "copies": "1", "size": "32253", "license": "bsd-3-clause", "hash": -2115790827020943000, "line_mean": 35.5266138165, "line_max": 79, "alpha_frac": 0.4988683223, "autogenerated": false, "ratio": 3.8097094259390505, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48085777482390507, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.core.urlresolvers import reverse from django.http import Http404 from social.utils import setting_name, module_member from social.exceptions import MissingBackend from social.strategies.utils import get_strategy BACKENDS = settings.AUTHENTICATION_BACKENDS STRATEGY = getattr(settings, setting_name('STRATEGY'), 'social.strategies.django_strategy.DjangoStrategy') STORAGE = getattr(settings, setting_name('STORAGE'), 'social.apps.django_app.default.models.DjangoStorage') Strategy = module_member(STRATEGY) Storage = module_member(STORAGE) def load_strategy(*args, **kwargs): return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs) def strategy(redirect_uri=None, load_strategy=load_strategy): def decorator(func): @wraps(func) def wrapper(request, backend, *args, **kwargs): uri = redirect_uri if uri and not uri.startswith('/'): uri = reverse(redirect_uri, args=(backend,)) try: request.social_strategy = load_strategy( request=request, backend=backend, redirect_uri=uri, *args, **kwargs ) except MissingBackend: raise Http404('Backend not found') # backward compatibility in attribute name, only if not already # defined if not hasattr(request, 'strategy'): request.strategy = request.social_strategy return func(request, backend, *args, **kwargs) return wrapper return decorator def setting(name, default=None): try: return getattr(settings, setting_name(name)) except AttributeError: return getattr(settings, name, default)
{ "repo_name": "imsparsh/python-social-auth", "path": "social/apps/django_app/utils.py", "copies": "2", "size": "1836", "license": "bsd-3-clause", "hash": 6424553586760583000, "line_mean": 33, "line_max": 75, "alpha_frac": 0.651416122, "autogenerated": false, "ratio": 4.511056511056511, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6162472633056512, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.core.urlresolvers import reverse from saml_service_provider import views as samlviews from .settings import LastPassServiceProviderSettings def proxy_port(f): ''' Patch saml_service_provider port setting saml_service_provider trusts too much in X-Forwarded-Port header and sets server port to local port if the header is missing. onelogin.saml2 explicitly sets the port eagerly. This results in some proxies being missed. This peeks common de facto reverse proxy headers and guesses the public port accordingly. ''' @wraps(f) def wrapped(self, request, *f_args, **f_kwargs): if 'HTTP_X_FORWARDED_PORT' not in request.META: proto = request.META.get('HTTP_X_FORWARDED_PROTO', None) if 'HTTP_X_FORWARDED_FOR' in request.META: request.META['HTTP_X_FORWARDED_PORT'] = '80' if proto == 'https': request.META['HTTP_X_FORWARDED_PORT'] = '443' if proto == 'http': request.META['HTTP_X_FORWARDED_PORT'] = '80' if 'HTTP_X_FORWARDED_HOST' in request.META: try: fwd_host = request.META['HTTP_X_FORWARDED_HOST'] port = int(fwd_host.rsplit(':', 1)) request.META['HTTP_X_FORWARDED_PORT'] = port except (ValueError, IndexError): pass return f(self, request, *f_args, **f_kwargs) return wrapped class SettingsMixin(object): def get_onelogin_settings(self): conf = dict() conf['onelogin_connector_id'] = settings.LASTPASS_CONNECTOR_ID if hasattr(settings, 'LASTPASS_CERTIFICATE'): conf['onelogin_x509_cert'] = settings.LASTPASS_CERTIFICATE elif hasattr(settings, 'LASTPASS_CERTIFICATE_FILE'): with open(settings.LASTPASS_CERTIFICATE_FILE, 'rb') as cert: conf['onelogin_x509_cert'] = cert.read() else: conf['onelogin_x509_fingerprint'] = settings.LASTPASS_FINGERPRINT hostname = getattr(settings, 'LASTPASS_HOSTNAME', 'http://localhost:8000') conf['sp_metadata_url'] = hostname + reverse('saml_metadata') conf['sp_login_url'] = hostname + reverse('saml_login_complete') conf['sp_logout_url'] = hostname + reverse('logout') conf['debug'] = settings.DEBUG conf['strict'] = not settings.DEBUG if hasattr(settings, 'SAML_SP_CERTIFICATE'): conf['sp_x509cert'] = settings.SAML_SP_CERTIFICATE else: with open(settings.SAML_SP_CERTIFICATE_FILE, 'rb') as cert: conf['sp_x509cert'] = cert.read() if hasattr(settings, 'SAML_SP_KEY'): conf['sp_private_key'] = settings.SAML_SP_KEY else: with open(settings.SAML_SP_KEY_FILE, 'rb') as key: conf['sp_private_key'] = key.read() if hasattr(settings, 'SAML_SP_CONTACT_INFO'): conf['contact_info'] = settings.SAML_SP_CONTACT_INFO if hasattr(settings, 'SAML_SP_ORGANIZATION_INFO'): conf['organization_info'] = settings.SAML_SP_ORGANIZATION_INFO return LastPassServiceProviderSettings(**conf).settings class InitiateAuthenticationView(SettingsMixin, samlviews.InitiateAuthenticationView): @proxy_port def get(self, request, *args, **kwargs): return super(InitiateAuthenticationView, self).get(request, *args, **kwargs) class CompleteAuthenticationView(SettingsMixin, samlviews.CompleteAuthenticationView): @proxy_port def post(self, request, *args, **kwargs): return super(CompleteAuthenticationView, self).post(request, *args, **kwargs) class MetadataView(SettingsMixin, samlviews.MetadataView): @proxy_port def get(self, request, *args, **kwargs): return super(MetadataView, self).get(request, *args, **kwargs)
{ "repo_name": "codetry/lpsp", "path": "lpsp/views.py", "copies": "1", "size": "4043", "license": "mit", "hash": 7315921980774983000, "line_mean": 36.4351851852, "line_max": 85, "alpha_frac": 0.6215681425, "autogenerated": false, "ratio": 3.959843290891283, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5081411433391283, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.core.urlresolvers import reverse from social.utils import setting_name, module_member from social.strategies.utils import get_strategy BACKENDS = settings.AUTHENTICATION_BACKENDS STRATEGY = getattr(settings, setting_name('STRATEGY'), 'social.strategies.django_strategy.DjangoStrategy') STORAGE = getattr(settings, setting_name('STORAGE'), 'social.apps.django_app.default.models.DjangoStorage') Strategy = module_member(STRATEGY) Storage = module_member(STORAGE) def load_strategy(*args, **kwargs): return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs) def strategy(redirect_uri=None, load_strategy=load_strategy): def decorator(func): @wraps(func) def wrapper(request, backend, *args, **kwargs): uri = redirect_uri if uri and not uri.startswith('/'): uri = reverse(redirect_uri, args=(backend,)) request.strategy = load_strategy(request=request, backend=backend, redirect_uri=uri, *args, **kwargs) return func(request, backend, *args, **kwargs) return wrapper return decorator def setting(name, default=None): try: return getattr(settings, setting_name(name)) except AttributeError: return getattr(settings, name, default) class BackendWrapper(object): def get_user(self, user_id): return Strategy(storage=Storage).get_user(user_id)
{ "repo_name": "nvbn/python-social-auth", "path": "social/apps/django_app/utils.py", "copies": "1", "size": "1548", "license": "bsd-3-clause", "hash": 6341045033286452000, "line_mean": 32.652173913, "line_max": 79, "alpha_frac": 0.6698966408, "autogenerated": false, "ratio": 4.161290322580645, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 46 }
from functools import wraps from django.conf import settings from django.db import transaction from django.shortcuts import get_object_or_404, redirect from prices import Money, TaxedMoney from ..account.utils import store_user_address from ..checkout import AddressType from ..core.utils.taxes import ( ZERO_MONEY, get_tax_rate_by_name, get_taxes_for_address) from ..core.weight import zero_weight from ..dashboard.order.utils import get_voucher_discount_for_order from ..discount.models import NotApplicable from ..order import FulfillmentStatus, OrderStatus, emails from ..order.models import Fulfillment, FulfillmentLine, Order, OrderLine from ..payment import ChargeStatus from ..payment.utils import gateway_refund, gateway_void from ..product.utils import ( allocate_stock, deallocate_stock, decrease_stock, increase_stock) from ..product.utils.digital_products import ( get_default_digital_content_settings) def order_line_needs_automatic_fulfillment(line: OrderLine) -> bool: """Check if given line is digital and should be automatically fulfilled""" digital_content_settings = get_default_digital_content_settings() default_automatic_fulfillment = ( digital_content_settings['automatic_fulfillment']) content = line.variant.digital_content if default_automatic_fulfillment and content.use_default_settings: return True if content.automatic_fulfillment: return True return False def order_needs_automatic_fullfilment(order: Order) -> bool: """Check if order has digital products which should be automatically fulfilled""" for line in order.lines.digital(): if order_line_needs_automatic_fulfillment(line): return True return False def fulfill_order_line(order_line, quantity): """Fulfill order line with given quantity.""" if order_line.variant and order_line.variant.track_inventory: decrease_stock(order_line.variant, quantity) order_line.quantity_fulfilled += quantity order_line.save(update_fields=['quantity_fulfilled']) def automatically_fulfill_digital_lines(order: Order): """Fulfill all digital lines which have enabled automatic fulfillment setting and send confirmation email.""" digital_lines = order.lines.filter( is_shipping_required=False, variant__digital_content__isnull=False) digital_lines = digital_lines.prefetch_related('variant__digital_content') if not digital_lines: return fulfillment, _ = Fulfillment.objects.get_or_create(order=order) for line in digital_lines: if not order_line_needs_automatic_fulfillment(line): continue digital_content = line.variant.digital_content digital_content.urls.create(line=line) quantity = line.quantity FulfillmentLine.objects.create( fulfillment=fulfillment, order_line=line, quantity=quantity) fulfill_order_line(order_line=line, quantity=quantity) emails.send_fulfillment_confirmation.delay(order.pk, fulfillment.pk) def check_order_status(func): """Check if order meets preconditions of payment process. Order can not have draft status or be fully paid. Billing address must be provided. If not, redirect to order details page. """ # pylint: disable=cyclic-import from .models import Order @wraps(func) def decorator(*args, **kwargs): token = kwargs.pop('token') order = get_object_or_404(Order.objects.confirmed(), token=token) if not order.billing_address or order.is_fully_paid(): return redirect('order:details', token=order.token) kwargs['order'] = order return func(*args, **kwargs) return decorator def update_voucher_discount(func): """Recalculate order discount amount based on order voucher.""" @wraps(func) def decorator(*args, **kwargs): if kwargs.pop('update_voucher_discount', True): order = args[0] try: discount_amount = get_voucher_discount_for_order(order) except NotApplicable: discount_amount = ZERO_MONEY order.discount_amount = discount_amount return func(*args, **kwargs) return decorator @update_voucher_discount def recalculate_order(order, **kwargs): """Recalculate and assign total price of order. Total price is a sum of items in order and order shipping price minus discount amount. Voucher discount amount is recalculated by default. To avoid this, pass update_voucher_discount argument set to False. """ # avoid using prefetched order lines lines = [OrderLine.objects.get(pk=line.pk) for line in order] prices = [line.get_total() for line in lines] total = sum(prices, order.shipping_price) # discount amount can't be greater than order total order.discount_amount = min(order.discount_amount, total.gross) if order.discount_amount: total -= order.discount_amount order.total = total order.save() recalculate_order_weight(order) def recalculate_order_weight(order): """Recalculate order weights.""" weight = zero_weight() for line in order: if line.variant: weight += line.variant.get_weight() * line.quantity order.weight = weight order.save(update_fields=['weight']) def update_order_prices(order, discounts): """Update prices in order with given discounts and proper taxes.""" taxes = get_taxes_for_address(order.shipping_address) for line in order: if line.variant: line.unit_price = line.variant.get_price(discounts, taxes) line.tax_rate = get_tax_rate_by_name( line.variant.product.tax_rate, taxes) line.save() if order.shipping_method: order.shipping_price = order.shipping_method.get_total(taxes) order.save() recalculate_order(order) def cancel_order(order, restock): """Cancel order and associated fulfillments. Return products to corresponding stocks if restock is set to True. """ if restock: restock_order_lines(order) for fulfillment in order.fulfillments.all(): fulfillment.status = FulfillmentStatus.CANCELED fulfillment.save(update_fields=['status']) order.status = OrderStatus.CANCELED order.save(update_fields=['status']) payments = order.payments.filter(is_active=True).exclude( charge_status=ChargeStatus.FULLY_REFUNDED) for payment in payments: if payment.can_refund(): gateway_refund(payment) elif payment.can_void(): gateway_void(payment) def update_order_status(order): """Update order status depending on fulfillments.""" quantity_fulfilled = order.quantity_fulfilled total_quantity = order.get_total_quantity() if quantity_fulfilled <= 0: status = OrderStatus.UNFULFILLED elif quantity_fulfilled < total_quantity: status = OrderStatus.PARTIALLY_FULFILLED else: status = OrderStatus.FULFILLED if status != order.status: order.status = status order.save(update_fields=['status']) def cancel_fulfillment(fulfillment, restock): """Cancel fulfillment. Return products to corresponding stocks if restock is set to True. """ if restock: restock_fulfillment_lines(fulfillment) for line in fulfillment: order_line = line.order_line order_line.quantity_fulfilled -= line.quantity order_line.save(update_fields=['quantity_fulfilled']) fulfillment.status = FulfillmentStatus.CANCELED fulfillment.save(update_fields=['status']) update_order_status(fulfillment.order) def attach_order_to_user(order, user): """Associate existing order with user account.""" order.user = user store_user_address(user, order.billing_address, AddressType.BILLING) if order.shipping_address: store_user_address(user, order.shipping_address, AddressType.SHIPPING) order.save(update_fields=['user']) @transaction.atomic def add_variant_to_order( order, variant, quantity, discounts=None, taxes=None, allow_overselling=False, track_inventory=True): """Add total_quantity of variant to order. Returns an order line the variant was added to. By default, raises InsufficientStock exception if quantity could not be fulfilled. This can be disabled by setting `allow_overselling` to True. """ if not allow_overselling: variant.check_quantity(quantity) try: line = order.lines.get(variant=variant) line.quantity += quantity line.save(update_fields=['quantity']) except OrderLine.DoesNotExist: product_name = variant.display_product() translated_product_name = variant.display_product(translated=True) if translated_product_name == product_name: translated_product_name = '' line = order.lines.create( product_name=product_name, translated_product_name=translated_product_name, product_sku=variant.sku, is_shipping_required=variant.is_shipping_required(), quantity=quantity, variant=variant, unit_price=variant.get_price(discounts, taxes), tax_rate=get_tax_rate_by_name(variant.product.tax_rate, taxes)) if variant.track_inventory and track_inventory: allocate_stock(variant, quantity) return line def change_order_line_quantity(line, new_quantity): """Change the quantity of ordered items in a order line.""" if new_quantity: line.quantity = new_quantity line.save(update_fields=['quantity']) else: delete_order_line(line) def delete_order_line(line): """Delete an order line from an order.""" line.delete() def restock_order_lines(order): """Return ordered products to corresponding stocks.""" for line in order: if line.variant and line.variant.track_inventory: if line.quantity_unfulfilled > 0: deallocate_stock(line.variant, line.quantity_unfulfilled) if line.quantity_fulfilled > 0: increase_stock(line.variant, line.quantity_fulfilled) if line.quantity_fulfilled > 0: line.quantity_fulfilled = 0 line.save(update_fields=['quantity_fulfilled']) def restock_fulfillment_lines(fulfillment): """Return fulfilled products to corresponding stocks.""" for line in fulfillment: if line.order_line.variant and line.order_line.variant.track_inventory: increase_stock( line.order_line.variant, line.quantity, allocate=True) def sum_order_totals(qs): zero = Money(0, currency=settings.DEFAULT_CURRENCY) taxed_zero = TaxedMoney(zero, zero) return sum([order.total for order in qs], taxed_zero)
{ "repo_name": "UITools/saleor", "path": "saleor/order/utils.py", "copies": "1", "size": "10953", "license": "bsd-3-clause", "hash": 3260131095289705500, "line_mean": 33.7714285714, "line_max": 79, "alpha_frac": 0.6831918196, "autogenerated": false, "ratio": 3.9370956146657083, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5120287434265708, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.db import transaction from django.utils import timezone from django.utils.translation import pgettext from prices import Money, TaxedMoney from ..core.taxes import zero_money from ..core.weight import zero_weight from ..discount.models import NotApplicable, Voucher, VoucherType from ..discount.utils import get_products_voucher_discount, validate_voucher_in_order from ..extensions.manager import get_extensions_manager from ..order import OrderStatus from ..order.models import Order, OrderLine from ..product.utils import allocate_stock, deallocate_stock, increase_stock from ..product.utils.digital_products import get_default_digital_content_settings from ..shipping.models import ShippingMethod from . import events def order_line_needs_automatic_fulfillment(line: OrderLine) -> bool: """Check if given line is digital and should be automatically fulfilled.""" digital_content_settings = get_default_digital_content_settings() default_automatic_fulfillment = digital_content_settings["automatic_fulfillment"] content = line.variant.digital_content if default_automatic_fulfillment and content.use_default_settings: return True if content.automatic_fulfillment: return True return False def order_needs_automatic_fullfilment(order: Order) -> bool: """Check if order has digital products which should be automatically fulfilled.""" for line in order.lines.digital(): if order_line_needs_automatic_fulfillment(line): return True return False def update_voucher_discount(func): """Recalculate order discount amount based on order voucher.""" @wraps(func) def decorator(*args, **kwargs): if kwargs.pop("update_voucher_discount", True): order = args[0] try: discount = get_voucher_discount_for_order(order) except NotApplicable: discount = zero_money(order.currency) order.discount = discount return func(*args, **kwargs) return decorator @update_voucher_discount def recalculate_order(order: Order, **kwargs): """Recalculate and assign total price of order. Total price is a sum of items in order and order shipping price minus discount amount. Voucher discount amount is recalculated by default. To avoid this, pass update_voucher_discount argument set to False. """ # avoid using prefetched order lines lines = [OrderLine.objects.get(pk=line.pk) for line in order] prices = [line.get_total() for line in lines] total = sum(prices, order.shipping_price) # discount amount can't be greater than order total order.discount_amount = min(order.discount_amount, total.gross.amount) if order.discount: total -= order.discount order.total = total order.save( update_fields=[ "discount_amount", "total_net_amount", "total_gross_amount", "currency", ] ) recalculate_order_weight(order) def recalculate_order_weight(order): """Recalculate order weights.""" weight = zero_weight() for line in order: if line.variant: weight += line.variant.get_weight() * line.quantity order.weight = weight order.save(update_fields=["weight"]) def update_order_prices(order, discounts): """Update prices in order with given discounts and proper taxes.""" manager = get_extensions_manager() for line in order: # type: OrderLine if line.variant: unit_price = line.variant.get_price(discounts) unit_price = TaxedMoney(unit_price, unit_price) line.unit_price = unit_price line.save( update_fields=[ "currency", "unit_price_net_amount", "unit_price_gross_amount", ] ) price = manager.calculate_order_line_unit(line) if price != line.unit_price: line.unit_price = price if price.tax and price.net: line.tax_rate = price.tax / price.net line.save() if order.shipping_method: order.shipping_price = manager.calculate_order_shipping(order) order.save( update_fields=[ "shipping_price_net_amount", "shipping_price_gross_amount", "currency", ] ) recalculate_order(order) def update_order_status(order): """Update order status depending on fulfillments.""" quantity_fulfilled = order.quantity_fulfilled total_quantity = order.get_total_quantity() if quantity_fulfilled <= 0: status = OrderStatus.UNFULFILLED elif quantity_fulfilled < total_quantity: status = OrderStatus.PARTIALLY_FULFILLED else: status = OrderStatus.FULFILLED if status != order.status: order.status = status order.save(update_fields=["status"]) @transaction.atomic def add_variant_to_order( order, variant, quantity, discounts=None, allow_overselling=False, track_inventory=True, ): """Add total_quantity of variant to order. Returns an order line the variant was added to. By default, raises InsufficientStock exception if quantity could not be fulfilled. This can be disabled by setting `allow_overselling` to True. """ if not allow_overselling: variant.check_quantity(quantity) try: line = order.lines.get(variant=variant) line.quantity += quantity line.save(update_fields=["quantity"]) except OrderLine.DoesNotExist: unit_price = variant.get_price(discounts) unit_price = TaxedMoney(net=unit_price, gross=unit_price) product = variant.product product_name = str(product) variant_name = str(variant) translated_product_name = str(product.translated) translated_variant_name = str(variant.translated) if translated_product_name == product_name: translated_product_name = "" if translated_variant_name == variant_name: translated_variant_name = "" line = order.lines.create( product_name=product_name, variant_name=variant_name, translated_product_name=translated_product_name, translated_variant_name=translated_variant_name, product_sku=variant.sku, is_shipping_required=variant.is_shipping_required(), quantity=quantity, unit_price=unit_price, variant=variant, ) manager = get_extensions_manager() unit_price = manager.calculate_order_line_unit(line) line.unit_price = unit_price line.tax_rate = unit_price.tax / unit_price.net line.save( update_fields=[ "currency", "unit_price_net_amount", "unit_price_gross_amount", "tax_rate", ] ) if variant.track_inventory and track_inventory: allocate_stock(variant, quantity) return line def add_gift_card_to_order(order, gift_card, total_price_left): """Add gift card to order. Return a total price left after applying the gift cards. """ if total_price_left > zero_money(total_price_left.currency): order.gift_cards.add(gift_card) if total_price_left < gift_card.current_balance: gift_card.current_balance = gift_card.current_balance - total_price_left total_price_left = zero_money(total_price_left.currency) else: total_price_left = total_price_left - gift_card.current_balance gift_card.current_balance_amount = 0 gift_card.last_used_on = timezone.now() gift_card.save(update_fields=["current_balance_amount", "last_used_on"]) return total_price_left def change_order_line_quantity(user, line, old_quantity, new_quantity): """Change the quantity of ordered items in a order line.""" if new_quantity: line.quantity = new_quantity line.save(update_fields=["quantity"]) else: delete_order_line(line) quantity_diff = old_quantity - new_quantity # Create the removal event if quantity_diff > 0: events.draft_order_removed_products_event( order=line.order, user=user, order_lines=[(quantity_diff, line)] ) elif quantity_diff < 0: events.draft_order_added_products_event( order=line.order, user=user, order_lines=[(quantity_diff * -1, line)] ) def delete_order_line(line): """Delete an order line from an order.""" line.delete() def restock_order_lines(order): """Return ordered products to corresponding stocks.""" for line in order: if line.variant and line.variant.track_inventory: if line.quantity_unfulfilled > 0: deallocate_stock(line.variant, line.quantity_unfulfilled) if line.quantity_fulfilled > 0: increase_stock(line.variant, line.quantity_fulfilled) if line.quantity_fulfilled > 0: line.quantity_fulfilled = 0 line.save(update_fields=["quantity_fulfilled"]) def restock_fulfillment_lines(fulfillment): """Return fulfilled products to corresponding stocks.""" for line in fulfillment: if line.order_line.variant and line.order_line.variant.track_inventory: increase_stock(line.order_line.variant, line.quantity, allocate=True) def sum_order_totals(qs): zero = Money(0, currency=settings.DEFAULT_CURRENCY) taxed_zero = TaxedMoney(zero, zero) return sum([order.total for order in qs], taxed_zero) def get_valid_shipping_methods_for_order(order: Order): return ShippingMethod.objects.applicable_shipping_methods_for_instance( order, price=order.get_subtotal().gross ) def get_products_voucher_discount_for_order(voucher: Voucher) -> Money: """Calculate products discount value for a voucher, depending on its type.""" prices = None if not prices: msg = pgettext( "Voucher not applicable", "This offer is only valid for selected items." ) raise NotApplicable(msg) return get_products_voucher_discount(voucher, prices) def get_voucher_discount_for_order(order: Order) -> Money: """Calculate discount value depending on voucher and discount types. Raise NotApplicable if voucher of given type cannot be applied. """ if not order.voucher: return zero_money(order.currency) validate_voucher_in_order(order) subtotal = order.get_subtotal() if order.voucher.type == VoucherType.ENTIRE_ORDER: return order.voucher.get_discount_amount_for(subtotal.gross) if order.voucher.type == VoucherType.SHIPPING: return order.voucher.get_discount_amount_for(order.shipping_price) if order.voucher.type == VoucherType.SPECIFIC_PRODUCT: return get_products_voucher_discount_for_order(order.voucher) raise NotImplementedError("Unknown discount type")
{ "repo_name": "maferelo/saleor", "path": "saleor/order/utils.py", "copies": "1", "size": "11213", "license": "bsd-3-clause", "hash": -3411526262572477400, "line_mean": 34.1504702194, "line_max": 86, "alpha_frac": 0.654418978, "autogenerated": false, "ratio": 3.99607982893799, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.515049880693799, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.http import Http404, HttpResponse, HttpResponseForbidden from django.utils import simplejson __all__ = ( 'ajax_only', 'ajax_login_required', 'ajax_template', 'auth_user_only', 'debug_only', 'render_to_json_response', 'super_user_only', ) _JSON_MIME_TYPE = 'application/json' def ajax_login_required(view_func): def wrap(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) else: json = simplejson.dumps({'login_required': True}) return HttpResponseForbidden(json, mimetype=_JSON_MIME_TYPE) return wrap def ajax_only(view_func): """ Ensure that all requests made to a view are made as AJAX requests. Non-AJAX requests will recieve a 400 (Bad Request) response. """ @wraps(view_func) def wrapper(request, *args, **kwargs): if not request.is_ajax(): from django.http import HttpResponseBadResponse return HttpResponseBadResponse() return view_func(request, *args, **kwargs) return wrapper def ajax_template(template_name): def internal(view_func): def wrap(request, *args, **kwargs): if request.is_ajax() and template_name: kwargs.update({'template_name': template_name}) return view_func(request, *args, **kwargs) return wrap return internal def auth_user_only(view_func): def wrap(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) else: raise Http404 return wrap def debug_only(handler): def wrap(request, *args, **kw): if not (settings.DEBUG or getattr(request.user, 'is_superuser', None)): raise Http404 return handler(request, *args, **kw) wrap.__name__ = handler.__name__ return wrap def message_if(test_func, message): """ Drop a message before view_func run if test_func returns True. """ def internal(view_func): def wrap(request, *args, **kwargs): if test_func(request): from django.contrib import messages if callable(message): text = message(request) else: text = message if text: messages.warning(request, text) return view_func(request, *args, **kwargs) return wrap return internal def render_to_json_response(*fn, **jsonargs): """ Render response as JSON. :param encoder: custom `JSONEncoder` subclass to serialize additional types. This argument is an alias to `cls` argument for `json.dump`. :param jsonargs: arguments suitable to pass to `json.dump` function. :returns: `HttpResponse` object with JSON mime type. Usage:: @render_to_json_response def json_view(request): return { 'foo': 'bar' } @render_to_json_response(indent=4) def json_view(request): return { 'foo': 'bar' } """ def internal(view_func): @wraps(view_func) def wrapper(request, *args, **kwargs): response = view_func(request, *args, **kwargs) or {} status_code = kwargs.pop('status', None) if isinstance(response, HttpResponse): response.mimetype = _JSON_MIME_TYPE if status_code: response.status_code = status_code return response ret = HttpResponse(mimetype=_JSON_MIME_TYPE) if status_code: ret.status_code = status_code encoder = jsonargs.pop('encoder', None) ret.write(simplejson.dumps(response, cls=encoder, **jsonargs)) return ret return wrapper if len(fn) > 0 and callable(fn[0]): return internal(fn[0]) return internal def super_user_only(view_func): def wrap(request, *args, **kwargs): if request.user.is_authenticated() and request.user.is_superuser: return view_func(request, *args, **kwargs) else: raise Http404 return wrap
{ "repo_name": "sprymak/metacorus-django-utils", "path": "mcutils/django/decorators.py", "copies": "1", "size": "4293", "license": "mit", "hash": 7719613405355558000, "line_mean": 31.7709923664, "line_max": 79, "alpha_frac": 0.5923596553, "autogenerated": false, "ratio": 4.167961165048544, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5260320820348544, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.http import HttpRequest, HttpResponse, HttpResponseForbidden, HttpResponseNotAllowed from django.views.decorators.csrf import csrf_exempt from twilio.request_validator import RequestValidator from twilio.rest import Client from site_config.models import ConfigurationError, SiteConfiguration def get_twilio_client(): twilio_settings = SiteConfiguration.get_twilio_settings() return Client(twilio_settings["sid"], twilio_settings["auth_token"]) def twilio_view(f): """ Copied from: https://github.com/rdegges/django-twilio/blob/master/django_twilio/decorators.py This decorator provides several helpful shortcuts for writing Twilio views. - It ensures that only requests from Twilio are passed through. This helps protect you from forged requests. - It ensures your view is exempt from CSRF checks via Django's @csrf_exempt decorator. This is necessary for any view that accepts POST requests from outside the local domain (eg: Twilio's servers). - It allows your view to (optionally) return TwiML to pass back to Twilio's servers instead of building an ``HttpResponse`` object manually. .. note:: The forgery protection checks ONLY happen if ``settings.DEBUG = False`` (aka, your site is in production). Usage:: from twilio import twiml @twilio_view def my_view(request): r = twiml.Response() r.message('Thanks for the SMS message!') return r """ @csrf_exempt @wraps(f) def decorator(request_or_self, *args, **kwargs): class_based_view = not isinstance(request_or_self, HttpRequest) if not class_based_view: request = request_or_self else: assert len(args) >= 1 request = args[0] # Turn off Twilio authentication when explicitly requested, or # in debug mode. Otherwise things do not work properly. For # more information, see the docs. use_forgery_protection = getattr(settings, "DJANGO_TWILIO_FORGERY_PROTECTION", not settings.DEBUG) if use_forgery_protection: if request.method not in ["GET", "POST"]: return HttpResponseNotAllowed(request.method) # Forgery check try: twilio_settings = SiteConfiguration.get_twilio_settings() validator = RequestValidator(twilio_settings["auth_token"]) url = request.build_absolute_uri() signature = request.META["HTTP_X_TWILIO_SIGNATURE"] except (AttributeError, KeyError, ConfigurationError): return HttpResponseForbidden() if request.method == "POST": if not validator.validate(url, request.POST, signature): return HttpResponseForbidden() if request.method == "GET": if not validator.validate(url, request.GET, signature): return HttpResponseForbidden() response = f(request_or_self, *args, **kwargs) return response return decorator
{ "repo_name": "monty5811/apostello", "path": "apostello/twilio.py", "copies": "1", "size": "3240", "license": "mit", "hash": 4085001207252195000, "line_mean": 35, "line_max": 106, "alpha_frac": 0.6450617284, "autogenerated": false, "ratio": 4.53781512605042, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.568287685445042, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.http.response import Http404 from django.utils.safestring import mark_safe from django.utils.translation import ugettext from django.utils.encoding import force_text from django.urls import NoReverseMatch from pyston.conf import settings as pyston_settings from pyston.forms import rest_modelform_factory from pyston.exception import (RESTException, MimerDataException, NotAllowedException, UnsupportedMediaTypeException, ResourceNotFoundException, NotAllowedMethodException, DuplicateEntryException, ConflictException, DataInvalidException, UnauthorizedException) from pyston.resource import BaseResource, BaseModelResource, DefaultRESTModelResource from pyston.response import RESTErrorResponse, RESTErrorsResponse from pyston.utils import rfs from chamber.shortcuts import get_object_or_none from chamber.utils import transaction from is_core.auth.permissions import ( PermissionsSet, IsAuthenticated, CoreAllowed, CoreReadAllowed, CoreUpdateAllowed, CoreDeleteAllowed, CoreCreateAllowed, AllowAny, DEFAULT_PERMISSION ) from is_core.auth.views import FieldPermissionViewMixin from is_core.config import settings from is_core.exceptions.response import (HTTPBadRequestResponseException, HTTPUnsupportedMediaTypeResponseException, HTTPMethodNotAllowedResponseException, HTTPDuplicateResponseException, HTTPForbiddenResponseException) from is_core.forms.models import smartmodelform_factory from is_core.patterns import RESTPattern, patterns from is_core.utils import get_field_label_from_path, METHOD_OBJ_STR_NAME, LOOKUP_SEP class RESTPermissionsMixin: permission = IsAuthenticated() csrf_exempt = False def has_get_permission(self, **kwargs): return ( self.permission.has_permission('get', self.request, self, obj=kwargs.get('obj')) and super().has_get_permission(**kwargs) ) def has_post_permission(self, **kwargs): return ( self.permission.has_permission('post', self.request, self, obj=kwargs.get('obj')) and super().has_post_permission(**kwargs) ) def has_put_permission(self, **kwargs): return ( self.permission.has_permission('put', self.request, self, obj=kwargs.get('obj')) and super().has_put_permission(**kwargs) ) def has_patch_permission(self, **kwargs): return ( self.permission.has_permission('patch', self.request, self, obj=kwargs.get('obj')) and super().has_patch_permission(**kwargs) ) def has_delete_permission(self, **kwargs): return ( self.permission.has_permission('delete', self.request, self, obj=kwargs.get('obj')) and super().has_delete_permission(**kwargs) ) def has_options_permission(self, **kwargs): return ( self._is_cors_options_request() or ( self.permission.has_permission('options', self.request, self, obj=kwargs.get('obj')) and super().has_options_permission(**kwargs) ) ) def has_head_permission(self, **kwargs): return ( self.permission.has_permission('head', self.request, self, obj=kwargs.get('obj')) and super().has_head_permission(**kwargs) ) def _check_permission(self, name, *args, **kwargs): try: super()._check_permission(name, *args, **kwargs) except NotAllowedException: if not hasattr(self.request, 'user') or not self.request.user or not self.request.user.is_authenticated: raise UnauthorizedException else: raise class RESTObjectPermissionsMixin(RESTPermissionsMixin): can_create_obj = True can_read_obj = True can_update_obj = True can_delete_obj = True def has_create_obj_permission(self, obj=None, **kwargs): return ( self.permission.has_permission('create_obj', self.request, self, obj=obj) and super().has_create_obj_permission(obj=obj, **kwargs) ) def has_read_obj_permission(self, obj=None, **kwargs): return ( self.permission.has_permission('read_obj', self.request, self, obj=obj) and super().has_read_obj_permission(obj=obj, **kwargs) ) def has_update_obj_permission(self, obj=None, **kwargs): return ( self.permission.has_permission('update_obj', self.request, self, obj=obj) and super().has_update_obj_permission(obj=obj, **kwargs) ) def has_delete_obj_permission(self, obj=None, **kwargs): return ( self.permission.has_permission('delete_obj', self.request, self, obj=obj) and super().has_delete_obj_permission(obj=obj, **kwargs) ) class RESTResourceMixin: register = False abstract = True def dispatch(self, request, *args, **kwargs): if hasattr(self, 'core'): self.core.init_rest_request(request) return super(RESTResourceMixin, self).dispatch(request, *args, **kwargs) @classmethod def __init_core__(cls, core, pattern): cls.core = core cls.pattern = pattern def _get_error_response(self, exception): """ Trasform pyston exceptions to Is-core exceptions and raise it """ response_exceptions = { MimerDataException: HTTPBadRequestResponseException, NotAllowedException: HTTPForbiddenResponseException, UnsupportedMediaTypeException: HTTPUnsupportedMediaTypeResponseException, Http404: Http404, ResourceNotFoundException: Http404, NotAllowedMethodException: HTTPMethodNotAllowedResponseException, DuplicateEntryException: HTTPDuplicateResponseException, ConflictException: HTTPDuplicateResponseException, } response_exception = response_exceptions.get(type(exception)) if response_exception: raise response_exception return super(RESTResourceMixin, self)._get_error_response(exception) @classmethod def get_method_returning_field_value(cls, field_name): """ Field values can be obtained from resource or core. """ method = super().get_method_returning_field_value(field_name) if method: return method core_method = cls.core.get_method_returning_field_value(field_name) if core_method: @wraps(core_method) def core_method_wrapper(self, **kwargs): return core_method(self.core, **kwargs) return core_method_wrapper return None class RESTModelCoreResourcePermissionsMixin(RESTObjectPermissionsMixin): pk_name = 'pk' permission = PermissionsSet( # HTTP permissions head=CoreReadAllowed(), options=CoreReadAllowed(), post=CoreCreateAllowed(), get=CoreReadAllowed(), put=CoreUpdateAllowed(), patch=CoreUpdateAllowed(), delete=CoreDeleteAllowed(), # Serializer permissions create_obj=CoreCreateAllowed(), read_obj=CoreReadAllowed(), update_obj=CoreUpdateAllowed(), delete_obj=CoreDeleteAllowed(), # Other permissions **{ DEFAULT_PERMISSION: CoreAllowed(), } ) def _get_perm_obj_or_none(self, pk=None): pk = pk or self.kwargs.get(self.pk_name) if pk: return get_object_or_none(self.core.model, pk=pk) else: return None class RESTModelCoreMixin(RESTModelCoreResourcePermissionsMixin): def _get_queryset(self): return self.core.get_queryset(self.request) def _get_pk(self): return self.kwargs.get(self.pk_name) def _get_obj_or_none(self, pk=None): if pk or self._get_pk(): return get_object_or_none(self._get_queryset(), pk=(pk or self._get_pk())) else: return None def _get_obj_or_404(self, pk=None): obj = self._get_obj_or_none(pk) if not obj: raise Http404 return obj class RESTResource(RESTPermissionsMixin, RESTResourceMixin, BaseResource): pass class EntryPointResource(RESTResource): allowed_methods = ('get', 'head', 'options') permission = AllowAny() def get(self): out = {} for pattern_name, pattern in patterns.items(): if isinstance(pattern, RESTPattern): try: url = pattern.get_url_string(self.request) allowed_methods = pattern.get_allowed_methods(self.request, None) if allowed_methods: out[pattern_name] = {'url': url, 'methods': allowed_methods} except NoReverseMatch: pass return out class RESTModelResource(FieldPermissionViewMixin, RESTModelCoreMixin, RESTResourceMixin, BaseModelResource): form_class = None field_labels = None abstract = True filters = {} default_fields_extension = None DEFAULT_REST_CONTEXT_MAPPING = { **BaseResource.DEFAULT_REST_CONTEXT_MAPPING, 'request_count': ('HTTP_X_REQUEST_COUNT', '_request_count'), } def get_allowed_fields_rfs(self, obj=None): return super().get_allowed_fields_rfs().subtract(self._get_disallowed_fields_from_permissions(obj=obj)) def get_field_labels(self): return ( self.field_labels if self.field_labels is not None else self.core.get_rest_field_labels(self.request) ) def get_field_label(self, field_name): return get_field_label_from_path( self.model, ( field_name[:-len(LOOKUP_SEP + METHOD_OBJ_STR_NAME)] if field_name.endswith(LOOKUP_SEP + METHOD_OBJ_STR_NAME) else field_name ), field_labels=self.get_field_labels() ) def get_fields(self, obj=None): fields = super(DefaultRESTModelResource, self).get_fields(obj=obj) return self.core.get_rest_fields(self.request, obj=None) if fields is None else fields def get_detailed_fields(self, obj=None): detailed_fields = super(DefaultRESTModelResource, self).get_detailed_fields(obj=obj) return self.core.get_rest_detailed_fields(self.request, obj=obj) if detailed_fields is None else detailed_fields def get_general_fields(self, obj=None): general_fields = super(DefaultRESTModelResource, self).get_general_fields(obj=obj) return self.core.get_rest_general_fields(self.request, obj=obj) if general_fields is None else general_fields def get_guest_fields(self, obj=None): guest_fields = super(DefaultRESTModelResource, self).get_guest_fields(obj=obj) return self.core.get_rest_guest_fields(self.request, obj=obj) if guest_fields is None else guest_fields def get_extra_fields(self, obj=None): extra_fields = super(DefaultRESTModelResource, self).get_extra_fields(obj=obj) return self.core.get_rest_extra_fields(self.request) if extra_fields is None else extra_fields def get_default_fields(self, obj=None): default_fields = super(DefaultRESTModelResource, self).get_default_fields(obj=obj) return self.core.get_rest_default_fields(self.request, obj=None) if default_fields is None else default_fields def get_extra_filter_fields(self): extra_filter_fields = super(DefaultRESTModelResource, self).get_extra_filter_fields() return self.core.get_rest_extra_filter_fields(self.request) if extra_filter_fields is None else extra_filter_fields def get_filter_fields(self): filter_fields = super(DefaultRESTModelResource, self).get_filter_fields() return self.core.get_rest_filter_fields(self.request) if filter_fields is None else filter_fields def get_extra_order_fields(self): extra_order_fields = super(DefaultRESTModelResource, self).get_extra_order_fields() return self.core.get_rest_extra_order_fields(self.request) if extra_order_fields is None else extra_order_fields def get_order_fields(self): order_fields = super(DefaultRESTModelResource, self).get_order_fields() return self.core.get_rest_order_fields(self.request) if order_fields is None else order_fields def get_default_fields_rfs(self, obj=None): return super(RESTModelResource, self).get_default_fields_rfs(obj=obj).join( rfs(self.get_default_fields_extension(obj)) ) def get_default_fields_extension(self, obj=None): return ( self.core.get_rest_default_fields_extension(self.request, obj=None) if self.default_fields_extension is None else self.default_fields_extension ) def get_queryset(self): return self.core.get_queryset(self.request) def _get_headers_queryset_context_mapping(self): mapping = super(RESTModelResource, self)._get_headers_queryset_context_mapping() mapping.update({ 'direction': ('HTTP_X_DIRECTION', '_direction'), 'order': ('HTTP_X_ORDER', '_order') }) return mapping def _preload_queryset(self, qs): return self.core.preload_queryset(self.request, qs) def _get_exclude(self, obj=None): return ( list(self.core.get_rest_form_exclude(self.request, obj)) + list(self._get_readonly_fields_from_permissions(obj)) ) def _get_form_fields(self, obj=None): return self.core.get_rest_form_fields(self.request, obj) def _get_form_class(self, obj=None): return ( self.form_class or ( self.core.get_rest_form_edit_class(self.request, obj) if obj else self.core.get_rest_form_add_class(self.request, obj) ) ) def _get_form_initial(self, obj): return {'_request': self.request, '_user': self.request.user} def _pre_save_obj(self, obj, form, change): self.core.pre_save_model(self.request, obj, form, change) def _save_obj(self, obj, form, change): self.core.save_model(self.request, obj, form, change) def _post_save_obj(self, obj, form, change): self.core.post_save_model(self.request, obj, form, change) def _pre_delete_obj(self, obj): self.core.pre_delete_model(self.request, obj) def _delete_obj(self, obj): self.core.delete_model(self.request, obj) def _post_delete_obj(self, obj): self.core.post_delete_model(self.request, obj) def _generate_form_class(self, inst, exclude=[]): form_class = self._get_form_class(inst) exclude = list(self._get_exclude(inst)) + exclude fields = self._get_form_fields(inst) if hasattr(form_class, '_meta') and form_class._meta.exclude: exclude.extend(form_class._meta.exclude) return rest_modelform_factory(self.model, form=form_class, form_factory=smartmodelform_factory, auto_related_direct_fields=pyston_settings.AUTO_RELATED_DIRECT_FIELDS, auto_related_reverse_fields=pyston_settings.AUTO_RELATED_REVERSE_FIELDS, request=self.request, exclude=exclude, fields=fields, labels=self.get_field_labels()) def put(self): # TODO: backward compatibility for bulk update should be used only patch return super(RESTModelResource, self).put() if self.kwargs.get(self.pk_name) else self.update_bulk() def patch(self): return super(RESTModelResource, self).patch() if self.kwargs.get(self.pk_name) else self.update_bulk() @transaction.atomic def update_bulk(self): qs = self._filter_queryset(self._get_queryset()) BULK_CHANGE_LIMIT = getattr(settings, 'BULK_CHANGE_LIMIT', 200) if qs.count() > BULK_CHANGE_LIMIT: return RESTErrorResponse( msg=ugettext('Only %s objects can be changed by one request').format(BULK_CHANGE_LIMIT), code=413) data = self.get_dict_data() objects, errors = zip(*(self._update_obj(obj, data) for obj in qs)) compact_errors = tuple(err for err in errors if err) return RESTErrorsResponse(compact_errors) if len(compact_errors) > 0 else objects def _update_obj(self, obj, data): try: return ( self._create_or_update({ self.pk_field_name: obj.pk, **data, }, partial_update=True), None ) except DataInvalidException as ex: return (None, self._format_message(obj, ex)) except (ConflictException, NotAllowedException): raise except RESTException as ex: return (None, self._format_message(obj, ex)) def _extract_message(self, ex): return '\n'.join([force_text(v) for v in ex.errors.values()]) if hasattr(ex, 'errors') else ex.message def _format_message(self, obj, ex): return { 'id': obj.pk, 'errors': {k: mark_safe(force_text(v)) for k, v in ex.errors.items()} if hasattr(ex, 'errors') else {}, '_obj_name': force_text(obj), }
{ "repo_name": "matllubos/django-is-core", "path": "is_core/rest/resource.py", "copies": "1", "size": "17557", "license": "bsd-3-clause", "hash": -5545740911404321000, "line_mean": 37.5868131868, "line_max": 123, "alpha_frac": 0.6388335137, "autogenerated": false, "ratio": 3.9993166287015947, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.001773779410543729, "num_lines": 455 }
from functools import wraps from django.conf import settings from django.shortcuts import render def short_circuit_middlewares(view_func): """ Marks a view function as wanting to short circuit middlewares. """ # Based on Django's csrf_exempt # We could just do view_func.short_circuit_middlewares = True, but # decorators are nicer if they don't have side-effects, so we return # a new function. def wrapped_view(*args, **kwargs): return view_func(*args, **kwargs) wrapped_view.short_circuit_middlewares = True return wraps(view_func)(wrapped_view) def require_ldap_auth(view_func): """Marks a view as requiring auth using LDAP.""" def wrapped_view(request, *args, **kwargs): if request.ldap: return view_func(request, *args, **kwargs) response = render(request, 'base/401.html', status=401) if settings.BASIC_AUTH_ENABLED: response['WWW-Authenticate'] = 'Basic realm="Morgoth"' return response return wraps(view_func)(wrapped_view)
{ "repo_name": "rehandalal/morgoth", "path": "morgoth/base/decorators.py", "copies": "1", "size": "1058", "license": "mpl-2.0", "hash": 5191686070378484000, "line_mean": 30.1176470588, "line_max": 72, "alpha_frac": 0.6720226843, "autogenerated": false, "ratio": 3.847272727272727, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5019295411572727, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.forms import SetPasswordForm from django.contrib.auth import update_session_auth_hash, views as auth_views from django.http import Http404 from django.utils.translation import ugettext as _ from django.views.decorators.debug import sensitive_post_parameters from django.views.decorators.cache import never_cache from wagtail.wagtailadmin import forms from wagtail.wagtailusers.forms import NotificationPreferencesForm from wagtail.wagtailusers.models import UserProfile from wagtail.wagtailcore.models import UserPagePermissionsProxy # Helper functions to check password management settings to enable/disable views as appropriate. # These are functions rather than class-level constants so that they can be overridden in tests # by override_settings def password_management_enabled(): return getattr(settings, 'WAGTAIL_PASSWORD_MANAGEMENT_ENABLED', True) def password_reset_enabled(): return getattr(settings, 'WAGTAIL_PASSWORD_RESET_ENABLED', password_management_enabled()) # Views def account(request): user_perms = UserPagePermissionsProxy(request.user) show_notification_preferences = user_perms.can_edit_pages() or user_perms.can_publish_pages() return render(request, 'wagtailadmin/account/account.html', { 'show_change_password': password_management_enabled() and request.user.has_usable_password(), 'show_notification_preferences': show_notification_preferences }) def change_password(request): if not password_management_enabled(): raise Http404 can_change_password = request.user.has_usable_password() if can_change_password: if request.POST: form = SetPasswordForm(request.user, request.POST) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) messages.success(request, _("Your password has been changed successfully!")) return redirect('wagtailadmin_account') else: form = SetPasswordForm(request.user) else: form = None return render(request, 'wagtailadmin/account/change_password.html', { 'form': form, 'can_change_password': can_change_password, }) def _wrap_password_reset_view(view_func): @wraps(view_func) def wrapper(*args, **kwargs): if not password_reset_enabled(): raise Http404 return view_func(*args, **kwargs) return wrapper password_reset = _wrap_password_reset_view(auth_views.password_reset) password_reset_done = _wrap_password_reset_view(auth_views.password_reset_done) password_reset_confirm = _wrap_password_reset_view(auth_views.password_reset_confirm) password_reset_complete = _wrap_password_reset_view(auth_views.password_reset_complete) def notification_preferences(request): if request.POST: form = NotificationPreferencesForm(request.POST, instance=UserProfile.get_for_user(request.user)) if form.is_valid(): form.save() messages.success(request, _("Your preferences have been updated successfully!")) return redirect('wagtailadmin_account') else: form = NotificationPreferencesForm(instance=UserProfile.get_for_user(request.user)) # quick-and-dirty catch-all in case the form has been rendered with no # fields, as the user has no customisable permissions if not form.fields: return redirect('wagtailadmin_account') return render(request, 'wagtailadmin/account/notification_preferences.html', { 'form': form, }) @sensitive_post_parameters() @never_cache def login(request): if request.user.is_authenticated() and request.user.has_perm('wagtailadmin.access_admin'): return redirect('wagtailadmin_home') else: from django.contrib.auth import get_user_model return auth_views.login(request, template_name='wagtailadmin/login.html', authentication_form=forms.LoginForm, extra_context={ 'show_password_reset': password_reset_enabled(), 'username_field': get_user_model().USERNAME_FIELD, }, ) def logout(request): response = auth_views.logout(request, next_page='wagtailadmin_login') # By default, logging out will generate a fresh sessionid cookie. We want to use the # absence of sessionid as an indication that front-end pages are being viewed by a # non-logged-in user and are therefore cacheable, so we forcibly delete the cookie here. response.delete_cookie(settings.SESSION_COOKIE_NAME, domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH) # HACK: pretend that the session hasn't been modified, so that SessionMiddleware # won't override the above and write a new cookie. request.session.modified = False return response
{ "repo_name": "Tivix/wagtail", "path": "wagtail/wagtailadmin/views/account.py", "copies": "1", "size": "5038", "license": "bsd-3-clause", "hash": 7791695660118980000, "line_mean": 36.0441176471, "line_max": 105, "alpha_frac": 0.7137753077, "autogenerated": false, "ratio": 4.226510067114094, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5440285374814094, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.template.loader import render_to_string from django.utils import six from .utils import get_tag_id, set_lazy_tag_data def _get_func_name(func): if six.PY2: return func.func_name else: return func.__name__ def lazy_tag(func=None): @wraps(func) def wrapper(*args, **kwargs): render_tag = kwargs.pop('render_tag', False) if render_tag: return func(*args, **kwargs) else: # Set render_tag in the kwargs so the tag will be rendered next # time this is called tag_lib = func.__module__.partition('templatetags.')[-1] tag_name = _get_func_name(func) tag = tag_lib + '.' + tag_name kwargs['render_tag'] = True tag_id = get_tag_id() set_lazy_tag_data(tag_id, tag, args, kwargs) return render_to_string('lazy_tags/lazy_tag.html', { 'tag_id': tag_id, 'STATIC_URL': settings.STATIC_URL, }) return wrapper
{ "repo_name": "grantmcconnaughey/django-lazy-tags", "path": "lazy_tags/decorators.py", "copies": "1", "size": "1098", "license": "mit", "hash": -3510234422876530700, "line_mean": 27.8947368421, "line_max": 75, "alpha_frac": 0.5701275046, "autogenerated": false, "ratio": 3.7094594594594597, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47795869640594596, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.utils import translation class classproperty(property): def __get__(self, cls, owner): return self.fget.__get__(None, owner)() def singleton(klass): """ Create singleton from class """ instances = {} def getinstance(*args, **kwargs): if klass not in instances: instances[klass] = klass(*args, **kwargs) return instances[klass] return wraps(klass)(getinstance) def translation_activate_block(function=None, language=None): """ Activate language only for one method or function """ def _translation_activate_block(function): def _decorator(*args, **kwargs): tmp_language = translation.get_language() try: translation.activate(language or settings.LANGUAGE_CODE) return function(*args, **kwargs) finally: translation.activate(tmp_language) return wraps(function)(_decorator) if function: return _translation_activate_block(function) else: return _translation_activate_block
{ "repo_name": "druids/django-chamber", "path": "chamber/utils/decorators.py", "copies": "1", "size": "1159", "license": "bsd-3-clause", "hash": -7803607456464232000, "line_mean": 25.3409090909, "line_max": 72, "alpha_frac": 0.6307161346, "autogenerated": false, "ratio": 4.617529880478088, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5748246015078088, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from rest_framework import status from rest_framework.response import Response SETTINGS = getattr(settings, 'DJANGO_REST_PARAMS', {}) TRUE_VALUES = SETTINGS.get('TRUE_VALUES', ('1', 'true')) FALSE_VALUES = SETTINGS.get('FALSE_VALUES', ('0', 'false')) def params(**kwargs): """ Request fn decorator that builds up a list of params and automatically returns a 400 if they are invalid. The validated params are passed to the wrapped function as kwargs. """ # Types that we'll all for as 'tuple' params TUPLE_TYPES = tuple, set, frozenset, list VALID_TYPES = int, float, str, unicode, bool class ParamValidator(object): # name param_name = None # the name of the param in the request, e.g. 'user_id' (even if we pass 'user' to the Fn) # type param_type = None # method - explicitly allow a certain method. If both are false we'll use defaults allow_GET = False allow_POST = False # value validators gt = None gte = None lt = None lte = None eq = None # optional optional = False default = None # multiple vals many = False # django models only deferred = True field = 'id' def __init__(self, arg_name, **kwargs): self.param_name = arg_name for k, v in kwargs.items(): setattr(self, k, v) def check_type(self, param): """ Check that the type of param is valid, or raise an Exception. This doesn't take self.many into account. """ valid_type = True if isinstance(self.param_type, TUPLE_TYPES): if not param in self.param_type: raise Exception('invalid option "%s": Must be one of: %s' % (param, self.param_type)) else: if self.param_type == int: param = int(param) elif self.param_type == float: param = float(param) elif self.param_type == str: assert(isinstance(param, (str, unicode))) param = unicode(param) elif self.param_type == bool: param = str(param).lower() # bool isn't case sensitive if param in TRUE_VALUES: param = True elif param in FALSE_VALUES: param = False else: raise Exception('%s is not a valid bool: must be one of: %s', param, TRUE_VALUES + FALSE_VALUES) elif hasattr(self.param_type, '_default_manager'): # isinstance(django.models.Model) doesn't seem to work, but this is a good tell query_set = self.param_type.objects if self.deferred: query_set = query_set.only('id') param = query_set.get(**{self.field: param}) else: valid_type = False if not valid_type: raise Exception("Invalid param type: %s" % self.param_type.____name__) return param def check_value(self, param): """ Check that a single value is lt/gt/etc. Doesn't take self.many into account. """ val = None if self.param_type == int or self.param_type == float: val = param elif self.param_type == str: val = len(param) if val: try: if self.eq and val != self.eq: raise Exception("must be less than %s!" % self.eq) else: if self.lt and val >= self.lt: raise Exception("must be less than %s!" % self.lt) if self.lte and val > self.lte: raise Exception("must be less than or equal to %s!" % self.lte) if self.gt and val <= self.gt: raise Exception("must be greater than %s!" % self.gt) if self.gte and val < self.gte: raise Exception("must be greater than or equal to %s!" % self.gte) except Exception as e: msg = str(e) msg = ("Length " if self.param_type == str else 'Value ') + msg raise Exception(msg) validators = {} for k, v in kwargs.items(): parts = k.split('__') param_key = parts[0] if not param_key in validators: validators[param_key] = ParamValidator(param_key) obj = validators[param_key] if (len(parts) == 1): # set type if not hasattr(v, '_default_manager'): # django model if not isinstance(v, TUPLE_TYPES) and not v in VALID_TYPES: raise Exception("Invalid type for %s: %s is not a valid type" % (k, v)) obj.param_type = v else: # we only are interested in the last part, since the only thing that can be multipart is __length__eq (etc) and 'length' is not important last_part = parts[-1] if last_part == 'method': if isinstance(v, TUPLE_TYPES): for method in v: if method == 'GET': obj.allow_GET = True elif method == 'POST': obj.allow_POST = True else: raise Exception('Invalid value for __method: "%s"' % method) else: if v == 'GET': obj.allow_GET = True elif v == 'POST': obj.allow_POST = True else: raise Exception('Invalid value for __method: "%s"' % v) continue if last_part == 'name': obj.param_name = v continue BOOL_PARTS = 'deferred', 'optional', 'many' if last_part in BOOL_PARTS: assert(isinstance(v, bool)) setattr(obj, last_part, v) continue NUM_PARTS = 'gt', 'gte', 'lt', 'lte', 'eq' if last_part in NUM_PARTS: assert(isinstance(v, int) or isinstance(v, float)) setattr(obj, last_part, v) continue if last_part == 'default': obj.optional = True obj.default = v continue if last_part == 'field': assert(isinstance(last_part, str)) obj.field = v continue raise Exception("Invalid option: '__%s' in param '%s'" % (last_part, k)) def _params(fn): @wraps(fn) def wrapped_request_fn(first_arg, *args, **kwargs): if len(args) == 0: request = first_arg # request function is a top-level function else: request = args[0] # request fn is a method, first_arg is 'self' request_method = request.META['REQUEST_METHOD'] default_param_method = 'POST' if request_method == 'POST' or request_method == 'PUT' else 'GET' # Validate the params for arg_name, validator in validators.items(): param_name = validator.param_name # what methods are allowed? use_default_methods = not validator.allow_GET and not validator.allow_POST allow_GET = (default_param_method == 'GET') if use_default_methods else validator.allow_GET allow_POST = (default_param_method == 'POST') if use_default_methods else validator.allow_POST # find the param param = None if allow_POST: param = request.DATA.get(param_name, None) param_type = 'POST' if not param and allow_GET: param = request.GET.get(param_name, None) param_type = 'GET' try: # optional/default if param is None: # but not False, because that's a valid boolean param if not validator.optional: raise Exception('Param is missing') else: kwargs[arg_name] = validator.default continue # check type, value if validator.many: if param_type == 'GET': params = str(param).split(',') else: params = param if isinstance(param, list) else (param,) params = [validator.check_type(p) for p in params] [validator.check_value(p) for p in params] else: param = validator.check_type(param) validator.check_value(param) except Exception as e: return Response({'error': 'Invalid param "%s": %s' % (param_name, str(e))}, status=status.HTTP_400_BAD_REQUEST) kwargs[arg_name] = params if validator.many else param return fn(first_arg, *args, **kwargs) return wrapped_request_fn return _params
{ "repo_name": "pombredanne/django-rest-params", "path": "django_rest_params/decorators.py", "copies": "1", "size": "9621", "license": "bsd-3-clause", "hash": 2564168134608042000, "line_mean": 39.4243697479, "line_max": 149, "alpha_frac": 0.4867477393, "autogenerated": false, "ratio": 4.629932627526467, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5616680366826468, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings import json import requests from gengo import Gengo, GengoError # Cache of supported languages from Gengo. Theoretically, these don't # change often, so the first time we request it, we cache it and then # keep that until the next deployment. GENGO_LANGUAGE_CACHE = None # Cache of supported language pairs. GENGO_LANGUAGE_PAIRS_CACHE = None # List of unsupported source languages. Theoretically, these don't # change often and there's no way to discover them via the Gengo API # that I can see, so we're going to manually curate them. If this # turns out to be problematic, we can change how we do things then. GENGO_MACHINE_UNSUPPORTED = ['zh-cn', 'zh-tw'] # The comment we send to Gengo with the jobs to give some context for # the job. GENGO_COMMENT = """\ This is a response from the Mozilla Input feedback system. It was submitted by an anonymous user in a non-English language. The feedback is used in aggregate to determine general user sentiment about Mozilla products and its features. This translation job was created by an automated system, so we're unable to respond to translator comments. If the response is nonsensical or junk text, then write "spam". """ GENGO_DETECT_LANGUAGE_API = 'https://api.gengo.com/service/detect_language' class FjordGengoError(Exception): """Superclass for all Gengo translation errors""" pass class GengoConfigurationError(FjordGengoError): """Raised when the Gengo-centric keys aren't set in settings""" class GengoUnknownLanguage(FjordGengoError): """Raised when the guesser can't guess the language""" class GengoUnsupportedLanguage(FjordGengoError): """Raised when the guesser guesses a language Gengo doesn't support .. Note:: If you buy me a beer, I'll happily tell you how I feel about this. """ class GengoAPIFailure(FjordGengoError): """Raised when the api kicks up an error""" class GengoMachineTranslationFailure(FjordGengoError): """Raised when machine translation didn't work""" class GengoHumanTranslationFailure(FjordGengoError): """Raised when human translation didn't work""" def requires_keys(fun): """Throw GengoConfigurationError if keys aren't set""" @wraps(fun) def _requires_keys(self, *args, **kwargs): if not self.gengo_api: raise GengoConfigurationError() return fun(self, *args, **kwargs) return _requires_keys class FjordGengo(object): def __init__(self): """Constructs a FjordGengo wrapper around the Gengo class We do this to make using the API a little easier in the context for Fjord as it includes the business logic around specific use cases we have. Also, having all the Gengo API stuff in one place makes it easier for mocking when testing. """ if settings.GENGO_PUBLIC_KEY and settings.GENGO_PRIVATE_KEY: gengo_api = Gengo( public_key=settings.GENGO_PUBLIC_KEY, private_key=settings.GENGO_PRIVATE_KEY, sandbox=getattr(settings, 'GENGO_USE_SANDBOX', True) ) else: gengo_api = None self.gengo_api = gengo_api def is_configured(self): """Returns whether Gengo is configured for Gengo API requests""" return not (self.gengo_api is None) @requires_keys def get_balance(self): """Returns the account balance as a float""" balance = self.gengo_api.getAccountBalance() return float(balance['response']['credits']) @requires_keys def get_languages(self, raw=False): """Returns the list of supported language targets :arg raw: True if you want the whole response, False if you want just the list of languages .. Note:: This is cached until the next deployment. """ global GENGO_LANGUAGE_CACHE if not GENGO_LANGUAGE_CACHE: resp = self.gengo_api.getServiceLanguages() GENGO_LANGUAGE_CACHE = ( resp, tuple([item['lc'] for item in resp['response']]) ) if raw: return GENGO_LANGUAGE_CACHE[0] else: return GENGO_LANGUAGE_CACHE[1] @requires_keys def get_language_pairs(self): """Returns the list of supported language pairs .. Note:: This is cached until the next deployment. """ global GENGO_LANGUAGE_PAIRS_CACHE if not GENGO_LANGUAGE_PAIRS_CACHE: resp = self.gengo_api.getServiceLanguagePairs() # NB: This looks specifically at the standard tier because # that's what we're using. It ignores the other tiers. pairs = [(item['lc_src'], item['lc_tgt']) for item in resp['response'] if item['tier'] == u'standard'] GENGO_LANGUAGE_PAIRS_CACHE = pairs return GENGO_LANGUAGE_PAIRS_CACHE @requires_keys def get_job(self, job_id): """Returns data for a specified job :arg job_id: the job_id for the job we want data for :returns: dict of job data """ resp = self.gengo_api.getTranslationJob(id=str(job_id)) if resp['opstat'] != 'ok': raise GengoAPIFailure( 'opstat: {0}, response: {1}'.format(resp['opstat'], resp)) return resp['response']['job'] def guess_language(self, text): """Guesses the language of the text :arg text: text to guess the language of :raises GengoUnknownLanguage: if the request wasn't successful or the guesser can't figure out which language the text is """ # get_language is a "private API" thing Gengo has, so it's not # included in the gengo library and we have to do it manually. resp = requests.post( GENGO_DETECT_LANGUAGE_API, data=json.dumps({'text': text.encode('utf-8')}), headers={ 'Content-Type': 'application/json', 'Accept': 'application/json' }) try: resp_json = resp.json() except ValueError: # If it's not JSON, then I don't really know what it is, # so I want to see it in an error email. Chances are it's # some ephemeral problem. # # FIXME: Figure out a better thing to do here. raise GengoAPIFailure( u'ValueError: non-json response: {0} {1}'.format( resp.status_code, resp.text)) if 'detected_lang_code' in resp_json: lang = resp_json['detected_lang_code'] if lang == 'un': raise GengoUnknownLanguage('unknown language') return lang raise GengoUnknownLanguage('request failure: {0}'.format(resp.content)) @requires_keys def machine_translate(self, id_, lc_src, lc_dst, text): """Performs a machine translation through Gengo This method is synchronous--it creates the request, posts it, waits for it to finish and then returns the translated text. :arg id_: instance id :arg lc_src: source language :arg lc_dst: destination language :arg text: the text to translate :returns: text :raises GengoUnsupportedLanguage: if the guesser guesses a language that Gengo doesn't support :raises GengoMachineTranslationFailure: if calling machine translation fails """ if lc_src in GENGO_MACHINE_UNSUPPORTED: raise GengoUnsupportedLanguage( 'unsupported language (translater; hc)): {0} -> {1}'.format( lc_src, lc_dst)) data = { 'jobs': { 'job_1': { 'custom_data': str(id_), 'body_src': text, 'lc_src': lc_src, 'lc_tgt': lc_dst, 'tier': 'machine', 'type': 'text', 'slug': 'Mozilla Input feedback response', } } } try: resp = self.gengo_api.postTranslationJobs(jobs=data) except GengoError as ge: # It's possible for the guesser to guess a language that's # in the list of supported languages, but for some reason # it's not actually supported which can throw a 1551 # GengoError. In that case, we treat it as an unsupported # language. if ge.error_code == 1551: raise GengoUnsupportedLanguage( 'unsupported language (translater)): {0} -> {1}'.format( lc_src, lc_dst)) raise if resp['opstat'] == 'ok': job = resp['response']['jobs']['job_1'] if 'body_tgt' not in job: raise GengoMachineTranslationFailure( 'no body_tgt: {0} -> {1}'.format(lc_src, lc_dst)) return job['body_tgt'] raise GengoAPIFailure( 'opstat: {0}, response: {1}'.format(resp['opstat'], resp)) @requires_keys def human_translate_bulk(self, jobs): """Performs human translation through Gengo on multiple jobs This method is asynchronous--it creates the request, posts it, and returns the order information. :arg jobs: a list of dicts with ``id``, ``lc_src``, ``lc_dst`` ``text`` and (optional) ``unique_id`` keys Response dict includes: * job_count: number of jobs processed * order_id: the order id * group_id: I have no idea what this is * credits_used: the number of credits used * currency: the currency the credits are in """ payload = {} for job in jobs: payload['job_{0}'.format(job['id'])] = { 'body_src': job['text'], 'lc_src': job['lc_src'], 'lc_tgt': job['lc_dst'], 'tier': 'standard', 'type': 'text', 'slug': 'Mozilla Input feedback response', 'force': 1, 'comment': GENGO_COMMENT, 'purpose': 'Online content', 'tone': 'informal', 'use_preferred': 0, 'auto_approve': 1, 'custom_data': job.get('unique_id', job['id']) } resp = self.gengo_api.postTranslationJobs(jobs=payload) if resp['opstat'] != 'ok': raise GengoAPIFailure( 'opstat: {0}, response: {1}'.format(resp['opstat'], resp)) return resp['response'] @requires_keys def completed_jobs_for_order(self, order_id): """Returns jobs for an order which are completed Gengo uses the status "approved" for jobs that have been translated and approved and are completed. :arg order_id: the order_id for the jobs we want to look at :returns: list of job data dicts; interesting fields being ``custom_data`` and ``body_tgt`` """ resp = self.gengo_api.getTranslationOrderJobs(id=str(order_id)) if resp['opstat'] != 'ok': raise GengoAPIFailure( 'opstat: {0}, response: {1}'.format(resp['opstat'], resp)) job_ids = resp['response']['order']['jobs_approved'] if not job_ids: return [] job_ids = ','.join(job_ids) resp = self.gengo_api.getTranslationJobBatch(id=job_ids) if resp['opstat'] != 'ok': raise GengoAPIFailure( 'opstat: {0}, response: {1}'.format(resp['opstat'], resp)) return resp['response']['jobs']
{ "repo_name": "rlr/fjord", "path": "fjord/translations/gengo_utils.py", "copies": "1", "size": "11859", "license": "bsd-3-clause", "hash": 3328444559626982400, "line_mean": 31.9416666667, "line_max": 79, "alpha_frac": 0.5861371111, "autogenerated": false, "ratio": 4.159593125219222, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 360 }
from functools import wraps from django.conf import settings import json import requests from gengo import Gengo, GengoError # noqa # Cache of supported languages from Gengo. Theoretically, these don't # change often, so the first time we request it, we cache it and then # keep that until the next deployment. GENGO_LANGUAGE_CACHE = None # Cache of supported language pairs. GENGO_LANGUAGE_PAIRS_CACHE = None # List of manually-curated languages that don't work for machine # translation src # Note: Gengo doesn't have an API that tells us these, so we have # to add them as we hit them. :( GENGO_UNSUPPORTED_MACHINE_LC_SRC = [ 'ar', 'cs', 'da', 'el', 'fi', 'hu', 'id', 'ms', 'no', 'ro', 'sk', 'sv', 'th', 'tr', 'uk', 'vi', ] # The comment we send to Gengo with the jobs to give some context for # the job. GENGO_COMMENT = """\ This is a response from the Mozilla Input feedback system. It was submitted by an anonymous user in a non-English language. The feedback is used in aggregate to determine general user sentiment about Mozilla products and its features. This translation job was created by an automated system, so we're unable to respond to translator comments. If the response is nonsensical or junk text, then write "spam". """ GENGO_DETECT_LANGUAGE_API = 'https://api.gengo.com/service/detect_language' class FjordGengoError(Exception): """Superclass for all Gengo translation errors""" pass class GengoConfigurationError(FjordGengoError): """Raised when the Gengo-centric keys aren't set in settings""" class GengoUnknownLanguage(FjordGengoError): """Raised when the guesser can't guess the language""" class GengoUnsupportedLanguage(FjordGengoError): """Raised when the guesser guesses a language Gengo doesn't support .. Note:: If you buy me a beer, I'll happily tell you how I feel about this. """ class GengoAPIFailure(FjordGengoError): """Raised when the api kicks up an error""" class GengoMachineTranslationFailure(FjordGengoError): """Raised when machine translation didn't work""" class GengoHumanTranslationFailure(FjordGengoError): """Raised when human translation didn't work""" def requires_keys(fun): """Throw GengoConfigurationError if keys aren't set""" @wraps(fun) def _requires_keys(self, *args, **kwargs): if not self.gengo_api: raise GengoConfigurationError() return fun(self, *args, **kwargs) return _requires_keys class FjordGengo(object): def __init__(self): """Constructs a FjordGengo wrapper around the Gengo class We do this to make using the API a little easier in the context for Fjord as it includes the business logic around specific use cases we have. Also, having all the Gengo API stuff in one place makes it easier for mocking when testing. """ if settings.GENGO_PUBLIC_KEY and settings.GENGO_PRIVATE_KEY: gengo_api = Gengo( public_key=settings.GENGO_PUBLIC_KEY, private_key=settings.GENGO_PRIVATE_KEY, sandbox=getattr(settings, 'GENGO_USE_SANDBOX', True) ) else: gengo_api = None self.gengo_api = gengo_api def is_configured(self): """Returns whether Gengo is configured for Gengo API requests""" return not (self.gengo_api is None) @requires_keys def get_balance(self): """Returns the account balance as a float""" balance = self.gengo_api.getAccountBalance() return float(balance['response']['credits']) @requires_keys def get_languages(self, raw=False): """Returns the list of supported language targets :arg raw: True if you want the whole response, False if you want just the list of languages .. Note:: This is cached until the next deployment. """ global GENGO_LANGUAGE_CACHE if not GENGO_LANGUAGE_CACHE: resp = self.gengo_api.getServiceLanguages() GENGO_LANGUAGE_CACHE = ( resp, tuple([item['lc'] for item in resp['response']]) ) if raw: return GENGO_LANGUAGE_CACHE[0] else: return GENGO_LANGUAGE_CACHE[1] @requires_keys def get_language_pairs(self): """Returns the list of supported language pairs for human translation .. Note:: This is cached until the next deployment. """ global GENGO_LANGUAGE_PAIRS_CACHE if not GENGO_LANGUAGE_PAIRS_CACHE: resp = self.gengo_api.getServiceLanguagePairs() # NB: This looks specifically at the standard tier because # that's what we're using. It ignores the other tiers. pairs = [(item['lc_src'], item['lc_tgt']) for item in resp['response'] if item['tier'] == u'standard'] GENGO_LANGUAGE_PAIRS_CACHE = pairs return GENGO_LANGUAGE_PAIRS_CACHE @requires_keys def get_job(self, job_id): """Returns data for a specified job :arg job_id: the job_id for the job we want data for :returns: dict of job data """ resp = self.gengo_api.getTranslationJob(id=str(job_id)) if resp['opstat'] != 'ok': raise GengoAPIFailure( 'opstat: {0}, response: {1}'.format(resp['opstat'], resp)) return resp['response']['job'] def guess_language(self, text): """Guesses the language of the text :arg text: text to guess the language of :raises GengoUnknownLanguage: if the request wasn't successful or the guesser can't figure out which language the text is """ # get_language is a "private API" thing Gengo has, so it's not # included in the gengo library and we have to do it manually. resp = requests.post( GENGO_DETECT_LANGUAGE_API, data=json.dumps({'text': text.encode('utf-8')}), headers={ 'Content-Type': 'application/json', 'Accept': 'application/json' }) try: resp_json = resp.json() except ValueError: # If it's not JSON, then I don't really know what it is, # so I want to see it in an error email. Chances are it's # some ephemeral problem. # # FIXME: Figure out a better thing to do here. raise GengoAPIFailure( u'ValueError: non-json response: {0} {1}'.format( resp.status_code, resp.text)) if 'detected_lang_code' in resp_json: lang = resp_json['detected_lang_code'] if lang == 'un': raise GengoUnknownLanguage('unknown language') return lang raise GengoUnknownLanguage('request failure: {0}'.format(resp.content)) @requires_keys def translate_bulk(self, jobs): """Performs translation through Gengo on multiple jobs Translation is asynchronous--this method posts the translation jobs and then returns the order information for those jobs to be polled at a later time. :arg jobs: a list of dicts with ``id``, ``lc_src``, ``lc_dst`` ``tier``, ``text`` and (optional) ``unique_id`` keys Response dict includes: * job_count: number of jobs processed * order_id: the order id * group_id: I have no idea what this is * credits_used: the number of credits used * currency: the currency the credits are in """ payload = {} for job in jobs: payload['job_{0}'.format(job['id'])] = { 'body_src': job['text'], 'lc_src': job['lc_src'], 'lc_tgt': job['lc_dst'], 'tier': job['tier'], 'type': 'text', 'slug': 'Mozilla Input feedback response', 'force': 1, 'comment': GENGO_COMMENT, 'purpose': 'Online content', 'tone': 'informal', 'use_preferred': 0, 'auto_approve': 1, 'custom_data': job.get('unique_id', job['id']) } resp = self.gengo_api.postTranslationJobs(jobs=payload) if resp['opstat'] != 'ok': raise GengoAPIFailure( 'opstat: {0}, response: {1}'.format(resp['opstat'], resp)) return resp['response'] @requires_keys def completed_jobs_for_order(self, order_id): """Returns jobs for an order which are completed Gengo uses the status "approved" for jobs that have been translated and approved and are completed. :arg order_id: the order_id for the jobs we want to look at :returns: list of job data dicts; interesting fields being ``custom_data`` and ``body_tgt`` """ resp = self.gengo_api.getTranslationOrderJobs(id=str(order_id)) if resp['opstat'] != 'ok': raise GengoAPIFailure( 'opstat: {0}, response: {1}'.format(resp['opstat'], resp)) job_ids = resp['response']['order']['jobs_approved'] if not job_ids: return [] job_ids = ','.join(job_ids) resp = self.gengo_api.getTranslationJobBatch(id=job_ids) if resp['opstat'] != 'ok': raise GengoAPIFailure( 'opstat: {0}, response: {1}'.format(resp['opstat'], resp)) return resp['response']['jobs']
{ "repo_name": "mozilla/fjord", "path": "fjord/translations/gengo_utils.py", "copies": "5", "size": "9701", "license": "bsd-3-clause", "hash": -4133347542340424700, "line_mean": 29.9936102236, "line_max": 79, "alpha_frac": 0.5958148644, "autogenerated": false, "ratio": 4.052213868003341, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7148028732403342, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf.urls import url from django.views.decorators.csrf import csrf_exempt from oslo_utils import importutils methods={} def register(path): def decorate(func): # print(path,func,name or func.__qualname__) methods[path]=func @wraps(func) def wrapper(*args,**kwargs): result=func(*args,**kwargs) return result return wrapper return decorate def get_view(func): qualname=func.__qualname__ module_name=func.__module__ cls=None if "." in qualname: class_name,_=qualname.split(".") cls=importutils.import_class("%s.%s"%(module_name,class_name)) @csrf_exempt def view(request,*args,**kwargs): obj=cls() obj.request=request obj.args=args obj.kwargs=kwargs return func(obj,*args,**kwargs) else: def view(request,*args,**kwargs): return func(request,*args,**kwargs) return view def get_urlpatterns(): get_name=lambda f:"%s.%s"%(f.__module__,f.__qualname__) return [url(path,get_view(func),name=get_name(func)) for path,func in methods.items()]
{ "repo_name": "hikelee/launcher", "path": "launcher/views/bases/register.py", "copies": "1", "size": "1092", "license": "mit", "hash": -1306226507628266200, "line_mean": 22.7391304348, "line_max": 88, "alpha_frac": 0.6611721612, "autogenerated": false, "ratio": 3.52258064516129, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.468375280636129, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib.auth.decorators import login_required from django.contrib import messages from django.urls import reverse from django.http.response import HttpResponseForbidden, HttpResponseRedirect from django.shortcuts import get_object_or_404, redirect, render from django.utils.translation import ugettext, ugettext_lazy as _ from comments.utils import get_comments_context from gallery.utils import get_gallery_context from .forms import FruitForm, FruitDeleteForm from .models import Fruit, Kind def _get_fruit(pk): return get_object_or_404(Fruit.objects.select_related('user', 'kind'), pk=pk) def detail(request, fruit_id): fruit = _get_fruit(fruit_id) context = { 'kinds': Kind.objects.valid(), 'fruit': fruit, } context.update(get_comments_context( request, container=fruit, with_complaints=True, complaint_label=_('Send comment as a complaint'), )) context.update(get_gallery_context( request, container=fruit, )) return render(request, 'fruit/detail.html', context) def add(request): if not request.user.is_authenticated: messages.warning(request, ugettext('To add markers, please first sign in.')) redir = '{}?next={}'.format(reverse('account_login'), reverse('fruit:add')) return HttpResponseRedirect(redir) if request.method == 'POST': form = FruitForm(request.POST) if form.is_valid(): data = dict(user=request.user) data.update(form.cleaned_data) fruit = Fruit(**data) fruit.save() messages.success(request, ugettext('Thank you, the marker has been added.')) return redirect(fruit) else: form = FruitForm() context = { 'kinds': Kind.objects.valid(), 'form': form, } return render(request, 'fruit/add.html', context) def _editor(func): @wraps(func) def test(request, fruit_id): fruit = _get_fruit(fruit_id) if not (fruit.user.id == request.user.id): return HttpResponseForbidden(_('Only the owner is allowed edit her marker.')) if fruit.is_deleted: return HttpResponseForbidden(_('This marker has been deleted and cannot be edited.')) return func(request, fruit) return test @login_required @_editor def edit(request, fruit): form = FruitForm(request.POST or None, instance=fruit) if form.is_valid(): form.save() messages.success(request, ugettext('Thank you, your changes have been saved.')) return redirect(fruit) context = { 'kinds': Kind.objects.valid(), 'fruit': fruit, 'form': form, } return render(request, 'fruit/edit.html', context) @login_required @_editor def delete(request, fruit): if request.method == 'POST': form = FruitDeleteForm(request.POST) if form.is_valid(): fruit.deleted = True fruit.why_deleted = form.cleaned_data['reason'] fruit.save() messages.success(request, ugettext('The marker has been deleted.')) return redirect(fruit) else: form = FruitDeleteForm() context = { 'form': form, } return render(request, 'fruit/delete.html', context)
{ "repo_name": "jsmesami/naovoce", "path": "src/fruit/views.py", "copies": "1", "size": "3348", "license": "bsd-3-clause", "hash": 5914304660239898000, "line_mean": 27.1344537815, "line_max": 97, "alpha_frac": 0.6367980884, "autogenerated": false, "ratio": 3.800227014755959, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4937025103155959, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib.auth.decorators import login_required, permission_required, user_passes_test from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse, HttpRequest from django.utils.decorators import method_decorator from django.utils.functional import allow_lazy, lazy, memoize from django.utils.unittest import TestCase from django.views.decorators.http import require_http_methods, require_GET, require_POST from django.views.decorators.vary import vary_on_headers, vary_on_cookie from django.views.decorators.cache import cache_page, never_cache, cache_control def fully_decorated(request): """Expected __doc__""" return HttpResponse('<html><body>dummy</body></html>') fully_decorated.anything = "Expected __dict__" # django.views.decorators.http fully_decorated = require_http_methods(["GET"])(fully_decorated) fully_decorated = require_GET(fully_decorated) fully_decorated = require_POST(fully_decorated) # django.views.decorators.vary fully_decorated = vary_on_headers('Accept-language')(fully_decorated) fully_decorated = vary_on_cookie(fully_decorated) # django.views.decorators.cache fully_decorated = cache_page(60*15)(fully_decorated) fully_decorated = cache_control(private=True)(fully_decorated) fully_decorated = never_cache(fully_decorated) # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 fully_decorated = user_passes_test(lambda u:True)(fully_decorated) fully_decorated = login_required(fully_decorated) fully_decorated = permission_required('change_world')(fully_decorated) # django.contrib.admin.views.decorators fully_decorated = staff_member_required(fully_decorated) # django.utils.functional fully_decorated = memoize(fully_decorated, {}, 1) fully_decorated = allow_lazy(fully_decorated) fully_decorated = lazy(fully_decorated) class DecoratorsTest(TestCase): def test_attributes(self): """ Tests that django decorators set certain attributes of the wrapped function. """ self.assertEqual(fully_decorated.__name__, 'fully_decorated') self.assertEqual(fully_decorated.__doc__, 'Expected __doc__') self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__') def test_user_passes_test_composition(self): """ Test that the user_passes_test decorator can be applied multiple times (#9474). """ def test1(user): user.decorators_applied.append('test1') return True def test2(user): user.decorators_applied.append('test2') return True def callback(request): return request.user.decorators_applied callback = user_passes_test(test1)(callback) callback = user_passes_test(test2)(callback) class DummyUser(object): pass class DummyRequest(object): pass request = DummyRequest() request.user = DummyUser() request.user.decorators_applied = [] response = callback(request) self.assertEqual(response, ['test2', 'test1']) def test_cache_page_new_style(self): """ Test that we can call cache_page the new way """ def my_view(request): return "response" my_view_cached = cache_page(123)(my_view) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = cache_page(123, key_prefix="test")(my_view) self.assertEqual(my_view_cached2(HttpRequest()), "response") def test_cache_page_old_style(self): """ Test that we can call cache_page the old way """ def my_view(request): return "response" my_view_cached = cache_page(my_view, 123) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = cache_page(my_view, 123, key_prefix="test") self.assertEqual(my_view_cached2(HttpRequest()), "response") my_view_cached3 = cache_page(my_view) self.assertEqual(my_view_cached3(HttpRequest()), "response") my_view_cached4 = cache_page()(my_view) self.assertEqual(my_view_cached4(HttpRequest()), "response") # For testing method_decorator, a decorator that assumes a single argument. # We will get type arguments if there is a mismatch in the number of arguments. def simple_dec(func): def wrapper(arg): return func("test:" + arg) return wraps(func)(wrapper) simple_dec_m = method_decorator(simple_dec) # For testing method_decorator, two decorators that add an attribute to the function def myattr_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr = True return wraps(func)(wrapper) myattr_dec_m = method_decorator(myattr_dec) def myattr2_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr2 = True return wraps(func)(wrapper) myattr2_dec_m = method_decorator(myattr2_dec) class MethodDecoratorTests(TestCase): """ Tests for method_decorator """ def test_preserve_signature(self): class Test(object): @simple_dec_m def say(self, arg): return arg self.assertEqual("test:hello", Test().say("hello")) def test_preserve_attributes(self): # Sanity check myattr_dec and myattr2_dec @myattr_dec @myattr2_dec def func(): pass self.assertEqual(getattr(func, 'myattr', False), True) self.assertEqual(getattr(func, 'myattr2', False), True) # Now check method_decorator class Test(object): @myattr_dec_m @myattr2_dec_m def method(self): "A method" pass self.assertEqual(getattr(Test().method, 'myattr', False), True) self.assertEqual(getattr(Test().method, 'myattr2', False), True) self.assertEqual(getattr(Test.method, 'myattr', False), True) self.assertEqual(getattr(Test.method, 'myattr2', False), True) self.assertEqual(Test.method.__doc__, 'A method') self.assertEqual(Test.method.im_func.__name__, 'method')
{ "repo_name": "jamespacileo/django-france", "path": "tests/regressiontests/decorators/tests.py", "copies": "2", "size": "6249", "license": "bsd-3-clause", "hash": 8930933596405351000, "line_mean": 33.5248618785, "line_max": 96, "alpha_frac": 0.6682669227, "autogenerated": false, "ratio": 3.9080675422138835, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0011694036372962224, "num_lines": 181 }
from functools import wraps from django.contrib.auth.decorators import user_passes_test from .conf import settings def trusted_agent_required(view=None, redirect_field_name='next', login_url=None): """ Similar to :func:`~django.contrib.auth.decorators.login_required`, but requires ``request.agent.is_trusted`` to be true. This will frequently be used in conjunction with login_required, unless you're allowing trusted agents to bypass authentication. The default value for ``login_url`` is :setting:`AGENT_LOGIN_URL`. """ def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): enforcer = user_passes_test(lambda u: request.agent.is_trusted, redirect_field_name=redirect_field_name, login_url=(login_url or settings.AGENT_LOGIN_URL) ) return enforcer(view_func)(request, *args, **kwargs) return _wrapped_view return decorator(view) if (view is not None) else decorator
{ "repo_name": "hany55/django-agent-trust", "path": "django_agent_trust/decorators.py", "copies": "1", "size": "1039", "license": "bsd-2-clause", "hash": -8533121744416887000, "line_mean": 34.8275862069, "line_max": 82, "alpha_frac": 0.6737247353, "autogenerated": false, "ratio": 3.9656488549618323, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5139373590261832, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib.auth import authenticate from django.contrib.auth.models import AnonymousUser def basic_authentication(view_method): '''This decorator performs Basic Authentication when an HTTP_AUTHORIZATION header is set in the request. If no credentials are present or authentication fails, the user on the request object passed to the view method will be an instance of Django's :class:`django.contrib.auth.models.AnonymousUser`. Intended for views that are accessed programmatically. ''' # based in part on http://djangosnippets.org/snippets/243/ # also based on authentication example from p. 361 of _RESTful Web Services_ @wraps(view_method) def view_decorator(request, *args, **kwargs): auth_info = request.META.get('HTTP_AUTHORIZATION', None) basic = 'Basic ' if auth_info and auth_info.startswith(basic): basic_info = auth_info[len(basic):] u, p = basic_info.decode('base64').split(':') request.user = authenticate(username=u, password=p) else: request.user = None # if authentication failed or credentials were not passed, user will be None if request.user is None: request.user = AnonymousUser() # convert to django's anonymous user return view_method(request, *args, **kwargs) return view_decorator
{ "repo_name": "emory-libraries/pidman", "path": "pidman/rest_api/decorators.py", "copies": "1", "size": "1410", "license": "apache-2.0", "hash": -3406749494854870500, "line_mean": 43.09375, "line_max": 84, "alpha_frac": 0.690070922, "autogenerated": false, "ratio": 4.37888198757764, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5568952909577639, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import user_passes_test from django.http import HttpResponseForbidden, Http404 from django.shortcuts import get_object_or_404, redirect as django_redirect from .security import detect_permissions, GlobalContext def login_required(login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): # FIXME: Ugly hack to extract process when django's user_passes_test. return user_passes_test( lambda u: False, login_url=login_url, redirect_field_name=redirect_field_name, )(lambda r: "dummy") def permission_denied(request, *args, **kwargs): return HttpResponseForbidden() def not_found(request, *args, **kwargs): """ Hide page as 404 * User accessed private contents but not permitted. """ raise Http404 def redirect(name): """ Redirect to 'name' page * Redirect to "Buy Now" page """ def _redirect(request, *args, **kwargs): return django_redirect(name) return _redirect def keeper(permission, model=None, mapper=None, factory=None, on_fail=permission_denied): def dec(f): @wraps(f) def _wrapped(request, *args, **kwargs): if mapper: model_kwargs = mapper(request, *args, **kwargs) context = get_object_or_404(model, **model_kwargs) elif factory: context = factory(request, *args, **kwargs) else: context = GlobalContext() permissions = detect_permissions(context, request) request.k_context = context request.k_permissions = permissions if permission in permissions: return f(request, *args, **kwargs) else: return on_fail(request, *args, **kwargs) return _wrapped return dec class SingleObjectPermissionMixin: """ Mixin to check permission for get_object method. This Mixin can be used with DetailView, UpdateView, DeleteView and so on. ``` class MyUpdateView(SingleObjectPermissionMixin, UpdateView): permission = 'edit' on_fail = not_found ... ``` """ permission = None on_fail = permission_denied class KeeperCBVPermissionDenied(Exception): pass def dispatch(self, request, *args, **kwargs): try: return super().dispatch(request, *args, **kwargs) except self.KeeperCBVPermissionDenied: return self.on_fail(request, *args, **kwargs) def get_object(self): obj = super().get_object() permissions = detect_permissions(obj, self.request) if self.permission not in permissions: raise self.KeeperCBVPermissionDenied self.k_permissions = permissions return obj class KeeperDRFPermission: """ View peermission class for Django Rest Framework ``` class MyViewset(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, GenericViewset): permission_classes = (KeeperDRFPermission,) model_permission = 'manage' ... ``` """ def has_permission(self, request, view): perm = getattr(view, 'global_permission', None) if perm is None: return True ctx = GlobalContext() permissions = detect_permissions(ctx, request) return perm in permissions def has_object_permission(self, request, view, obj): perm = getattr(view, 'model_permission', None) if perm is None: return True permissions = detect_permissions(obj, request) return perm in permissions
{ "repo_name": "hirokiky/django-keeper", "path": "keeper/views.py", "copies": "1", "size": "3764", "license": "mit", "hash": -8115164274362194000, "line_mean": 27.9538461538, "line_max": 77, "alpha_frac": 0.6235387885, "autogenerated": false, "ratio": 4.31651376146789, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 130 }
from functools import wraps from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import user_passes_test from django.shortcuts import render from django.contrib import messages from django.contrib.auth.views import redirect_to_login from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from oscar.core.compat import urlparse def staff_member_required(view_func, login_url=None): """ Ensure that the user is a logged-in staff member. * If not authenticated, redirect to a specified login URL. * If not staff, show a 403 page This decorator is based on the decorator with the same name from django.contrib.admin.views.decorators. This one is superior as it allows a redirect URL to be specified. """ if login_url is None: login_url = reverse_lazy('customer:login') @wraps(view_func) def _checklogin(request, *args, **kwargs): if request.user.is_active and request.user.is_staff: return view_func(request, *args, **kwargs) # If user is not logged in, redirect to login page if not request.user.is_authenticated(): # If the login url is the same scheme and net location then just # use the path as the "next" url. path = request.build_absolute_uri() login_scheme, login_netloc = urlparse.urlparse(login_url)[:2] current_scheme, current_netloc = urlparse.urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() messages.warning(request, _("You must log in to access this page")) return redirect_to_login(path, login_url, REDIRECT_FIELD_NAME) else: # User does not have permission to view this page raise PermissionDenied return _checklogin def check_permissions(user, permissions): """ Permissions can be a list or a tuple of lists. If it is a tuple, every permission list will be evaluated and the outcome will be checked for truthiness. Each item of the list(s) must be either a valid Django permission name (model.codename) or an attribute on the User model (e.g. 'is_active', 'is_superuser'). Example usage: - permissions_required(['is_staff', ]) would replace staff_member_required - permissions_required(['is_anonymous', ]) would replace login_forbidden - permissions_required((['is_staff',], ['partner.dashboard_access'])) allows both staff users and users with the above permission """ def _check_one_permission_list(perms): regular_permissions = [perm for perm in perms if '.' in perm] conditions = [perm for perm in perms if '.' not in perm] if conditions and ['is_active', 'is_anonymous'] not in conditions: # always check for is_active where appropriate conditions.append('is_active') passes_conditions = all([getattr(user, perm) for perm in conditions]) return passes_conditions and user.has_perms(regular_permissions) if permissions is None: return True elif isinstance(permissions, list): return _check_one_permission_list(permissions) else: return any(_check_one_permission_list(perm) for perm in permissions) def permissions_required(permissions, login_url=None): """ Decorator that checks if a user has the given permissions. Accepts a list or tuple of lists of permissions (see check_permissions documentation). If the user is not logged in and the test fails, she is redirected to a login page. If the user is logged in, she gets a HTTP 403 Permission Denied message, analogous to Django's permission_required decorator. """ if login_url is None: login_url = reverse_lazy('customer:login') def _check_permissions(user): outcome = check_permissions(user, permissions) if not outcome and user.is_authenticated(): raise PermissionDenied else: return outcome return user_passes_test(_check_permissions, login_url=login_url) def login_forbidden(view_func, template_name='login_forbidden.html', status=403): """ Only allow anonymous users to access this view. """ @wraps(view_func) def _checklogin(request, *args, **kwargs): if not request.user.is_authenticated(): return view_func(request, *args, **kwargs) return render(request, template_name, status=status) return _checklogin
{ "repo_name": "MrReN/django-oscar", "path": "oscar/views/decorators.py", "copies": "3", "size": "4759", "license": "bsd-3-clause", "hash": -9005110938301099000, "line_mean": 38.3305785124, "line_max": 79, "alpha_frac": 0.6743013238, "autogenerated": false, "ratio": 4.299006323396568, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 121 }
from functools import wraps from django.contrib.auth import REDIRECT_FIELD_NAME from django.shortcuts import redirect, resolve_url from django.utils.decorators import available_attrs from django.utils.encoding import force_str from django.utils.six.moves.urllib.parse import urlparse def user_passes_test(function=None, test_func=None, redirect_field_name=REDIRECT_FIELD_NAME, fail_url=None): """Similar to user_passes_test in django.contrib.auth except this one can be used like this: f = user_passes_test(f) Decorator for views that checks that the user passes the given test, redirecting to `fail_url` for failures. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() # urlparse chokes on lazy objects in Python 3, force to str resolved_fail_url = force_str(resolve_url(fail_url)) # If the fail url is the same scheme and net location then just # use the path as the "next" url. fail_scheme, fail_netloc = urlparse(resolved_fail_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not fail_scheme or fail_scheme == current_scheme) and (not fail_netloc or fail_netloc == current_netloc)): path = request.get_full_path() return redirect(fail_url) return _wrapped_view if function: return decorator(function) return decorator
{ "repo_name": "AASHE/django-bulletin", "path": "bulletin/decorators.py", "copies": "1", "size": "1832", "license": "mit", "hash": -2528940185856585700, "line_mean": 41.6046511628, "line_max": 75, "alpha_frac": 0.643558952, "autogenerated": false, "ratio": 4.211494252873563, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0003370407819346141, "num_lines": 43 }
from functools import wraps from django.contrib.auth.mixins import AccessMixin, LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.shortcuts import redirect def sales_access_required(function): """ this function is a decorator used to authorize if a user has sales access """ def wrap(request, *args, **kwargs): if ( request.user.role == "ADMIN" or request.user.is_superuser or request.user.has_sales_access ): return function(request, *args, **kwargs) else: raise PermissionDenied return wrap def marketing_access_required(function): """ this function is a decorator used to authorize if a user has marketing access """ def wrap(request, *args, **kwargs): if ( request.user.role == "ADMIN" or request.user.is_superuser or request.user.has_marketing_access ): return function(request, *args, **kwargs) else: raise PermissionDenied return wrap class SalesAccessRequiredMixin(AccessMixin): """ Mixin used to authorize if a user has sales access """ def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return self.handle_no_permission() self.raise_exception = True if ( request.user.role == "ADMIN" or request.user.is_superuser or request.user.has_sales_access ): return super(SalesAccessRequiredMixin, self).dispatch( request, *args, **kwargs ) else: return self.handle_no_permission() class MarketingAccessRequiredMixin(AccessMixin): """ Mixin used to authorize if a user has marketing access """ def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return self.handle_no_permission() self.raise_exception = True if ( request.user.role == "ADMIN" or request.user.is_superuser or request.user.has_marketing_access ): return super(MarketingAccessRequiredMixin, self).dispatch( request, *args, **kwargs ) else: return self.handle_no_permission() def admin_login_required(function): """ this function is a decorator used to authorize if a user is admin """ def wrap(request, *args, **kwargs): if request.user.role == "ADMIN" or request.user.is_superuser: return function(request, *args, **kwargs) else: raise PermissionDenied return wrap
{ "repo_name": "MicroPyramid/Django-CRM", "path": "common/access_decorators_mixins.py", "copies": "1", "size": "2689", "license": "mit", "hash": 6570156226098466000, "line_mean": 29.908045977, "line_max": 89, "alpha_frac": 0.6110078096, "autogenerated": false, "ratio": 4.511744966442953, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5622752776042954, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib.auth.models import Group, Permission, User from django.test import TestCase from django.urls import reverse from wagtail.core.models import GroupPagePermission, Page from wagtail.tests.utils import WagtailTestUtils from tests.app.models import NewsIndex, NewsItem, SecondaryNewsIndex def p(permission_string): app_label, codename = permission_string.split('.', 1) return Permission.objects.get(content_type__app_label=app_label, codename=codename) def grant_permissions(perms): def decorator(fn): @wraps(fn) def method(self): self.user.user_permissions.add(*[p(perm) for perm in perms]) self.user.save() return fn(self) return method return decorator class WithNewsIndexTestCase(TestCase): def setUp(self): super(WithNewsIndexTestCase, self).setUp() root_page = Page.objects.get(pk=2) self.index = NewsIndex( title='News', slug='news') root_page.add_child(instance=self.index) class WithNewsItemTestCase(WithNewsIndexTestCase): def setUp(self): super(WithNewsItemTestCase, self).setUp() self.newsitem = NewsItem.objects.create( newsindex=self.index, title='News item') class PermissionTestCase(TestCase, WagtailTestUtils): def setUp(self): super(PermissionTestCase, self).setUp() # Create a group with permission to edit pages # Required to enable page searching self.group = Group.objects.create(name='Test group') GroupPagePermission.objects.create( group=self.group, page=Page.objects.get(pk=1), permission_type='add') self.user = self.create_test_user() self.client.login(username='test@email.com', password='password') def create_test_user(self): """ Create a normal boring user, not a super user. This user has no news related permissions by default. """ user = User.objects.create_user( username='test@email.com', password='password') user.groups.add(self.group) user.user_permissions.add(p('wagtailadmin.access_admin')) user.save() return user def assertStatusCode(self, url, status_code, msg=None): response = self.client.get(url) self.assertEqual(response.status_code, status_code, msg=msg) class TestChooseNewsIndex(PermissionTestCase): @grant_permissions(['app.add_newsitem', 'app.change_newsitem']) def test_chooser_multiple_choices(self): """ Test the chooser when there are multiple valid choices, and some missing due to lack of permissions. """ root_page = Page.objects.get(pk=2) news1 = root_page.add_child(instance=NewsIndex( title='Normal News 1', slug='news-1')) news2 = root_page.add_child(instance=NewsIndex( title='Normal News 2', slug='news-2')) secondary_news = root_page.add_child(instance=SecondaryNewsIndex( title='Secondary News', slug='secondary-news')) response = self.client.get(reverse('wagtailnews:choose')) self.assertContains(response, news1.title) self.assertContains(response, news2.title) self.assertNotContains(response, secondary_news.title) @grant_permissions(['app.add_newsitem', 'app.change_newsitem']) def test_chooser_one_choice(self): """ Test the chooser when there is a single valid choice, and some missing due to lack of permissions. """ root_page = Page.objects.get(pk=2) news = root_page.add_child(instance=NewsIndex( title='News', slug='news')) root_page.add_child(instance=SecondaryNewsIndex( title='Secondary News', slug='secondary-news')) response = self.client.get(reverse('wagtailnews:choose')) self.assertRedirects(response, reverse('wagtailnews:index', kwargs={ 'pk': news.pk})) def test_chooser_no_perms(self): """ Test the chooser when there are no valid choices. """ root_page = Page.objects.get(pk=2) root_page.add_child(instance=NewsIndex( title='News', slug='news')) root_page.add_child(instance=SecondaryNewsIndex( title='Secondary News', slug='secondary-news')) response = self.client.get(reverse('wagtailnews:choose')) self.assertEqual(response.status_code, 403) @grant_permissions(['app.add_newsitem', 'app.change_newsitem']) def test_chooser_has_perms_no_news(self): """ Test the chooser when there are no news items, but the user has relevant permissions. """ response = self.client.get(reverse('wagtailnews:choose')) self.assertEqual(response.status_code, 200) class TestNewsIndex(WithNewsIndexTestCase, PermissionTestCase): def setUp(self): super(TestNewsIndex, self).setUp() self.url = reverse('wagtailnews:index', kwargs={'pk': self.index.pk}) @grant_permissions(['app.add_newsitem', 'app.change_newsitem']) def test_news_index_has_perm(self): """ Check the user is allowed to access the news index list """ self.assertStatusCode(self.url, 200) def test_news_index_no_perm(self): """ Check the user is denied access to the news index list """ self.assertStatusCode(self.url, 403) class TestCreateNewsItem(WithNewsIndexTestCase, PermissionTestCase): def setUp(self): super(TestCreateNewsItem, self).setUp() self.url = reverse('wagtailnews:create', kwargs={'pk': self.index.pk}) @grant_permissions(['app.add_newsitem', 'app.change_newsitem']) def test_has_permission(self): """ Test users can create NewsItems """ self.assertStatusCode(self.url, 200) @grant_permissions(['app.add_newsitem']) def test_only_add_perm(self): """ Users need both add and edit. Add is not sufficient """ self.assertStatusCode(self.url, 403) @grant_permissions(['app.change_newsitem']) def test_only_edit_perm(self): """ Users need both add and edit. Edit is not sufficient """ self.assertStatusCode(self.url, 403) def test_no_permission(self): """ Test user can not create without permission """ self.assertStatusCode(self.url, 403) @grant_permissions(['app.add_newsitem', 'app.change_newsitem']) def test_add_button_appears(self): """Test that the add button appears""" response = self.client.get(reverse('wagtailnews:index', kwargs={ 'pk': self.index.pk})) self.assertContains(response, self.url) @grant_permissions(['app.change_newsitem']) def test_no_add_button_appears(self): """Test that the add button does not appear""" response = self.client.get(reverse('wagtailnews:index', kwargs={ 'pk': self.index.pk})) self.assertNotContains(response, self.url) class TestEditNewsItem(WithNewsItemTestCase, PermissionTestCase): def setUp(self): super(TestEditNewsItem, self).setUp() self.url = reverse('wagtailnews:edit', kwargs={ 'pk': self.index.pk, 'newsitem_pk': self.newsitem.pk}) @grant_permissions(['app.change_newsitem']) def test_has_permission(self): """ Test users can create NewsItems """ self.assertStatusCode(self.url, 200) def test_no_permission(self): """ Test user can not edit without permission """ self.assertStatusCode(self.url, 403) @grant_permissions(['app.change_newsitem']) def test_edit_button_appears(self): """Test that the edit button appears""" response = self.client.get(reverse('wagtailnews:index', kwargs={ 'pk': self.index.pk})) self.assertContains(response, self.url) @grant_permissions(['app.delete_newsitem']) def test_no_edit_button_appears(self): """Test that the edit button does not appear""" response = self.client.get(reverse('wagtailnews:index', kwargs={ 'pk': self.index.pk})) self.assertNotContains(response, self.url) class TestUnpublishNewsItem(WithNewsItemTestCase, PermissionTestCase): def setUp(self): super(TestUnpublishNewsItem, self).setUp() self.url = reverse('wagtailnews:unpublish', kwargs={ 'pk': self.index.pk, 'newsitem_pk': self.newsitem.pk}) @grant_permissions(['app.change_newsitem']) def test_has_permission(self): """ Test users can unpublish NewsItems """ self.assertStatusCode(self.url, 200) def test_no_permission(self): """ Test user can not unpublish without permission """ self.assertStatusCode(self.url, 403) @grant_permissions(['app.change_newsitem']) def test_unpublish_button_appears(self): """Test that the unpublish button appears""" response = self.client.get(reverse('wagtailnews:index', kwargs={ 'pk': self.index.pk})) self.assertContains(response, self.url) @grant_permissions(['app.delete_newsitem']) def test_no_unpublish_button_appears(self): """Test that the unpublish button does not appear""" response = self.client.get(reverse('wagtailnews:index', kwargs={ 'pk': self.index.pk})) self.assertNotContains(response, self.url) class TestDeleteNewsItem(WithNewsItemTestCase, PermissionTestCase): def setUp(self): super(TestDeleteNewsItem, self).setUp() self.url = reverse('wagtailnews:delete', kwargs={ 'pk': self.index.pk, 'newsitem_pk': self.newsitem.pk}) @grant_permissions(['app.delete_newsitem']) def test_has_permission(self): """ Test users can delete NewsItems """ self.assertStatusCode(self.url, 200) def test_no_permission(self): """ Test user can not delete without permission """ self.assertStatusCode(self.url, 403) @grant_permissions(['app.delete_newsitem']) def test_delete_button_appears_index(self): """Test that the delete button appears on the index page""" response = self.client.get(reverse('wagtailnews:index', kwargs={ 'pk': self.index.pk})) self.assertContains(response, self.url) @grant_permissions(['app.change_newsitem']) def test_no_delete_button_appears_index(self): """Test that the delete button does not appear on the index page""" response = self.client.get(reverse('wagtailnews:index', kwargs={ 'pk': self.index.pk})) self.assertNotContains(response, self.url) @grant_permissions(['app.change_newsitem', 'app.delete_newsitem']) def test_delete_button_appears_edit(self): """Test that the delete button appears on the edit page""" response = self.client.get(reverse('wagtailnews:edit', kwargs={ 'pk': self.index.pk, 'newsitem_pk': self.newsitem.pk})) self.assertContains(response, self.url) @grant_permissions(['app.change_newsitem']) def test_no_delete_button_appears_edit(self): """Test that the delete button does not appear on the edit page""" response = self.client.get(reverse('wagtailnews:edit', kwargs={ 'pk': self.index.pk, 'newsitem_pk': self.newsitem.pk})) self.assertNotContains(response, self.url) class TestSearchNewsItem(WithNewsItemTestCase, PermissionTestCase): def setUp(self): super(TestSearchNewsItem, self).setUp() self.url = reverse('wagtailnews:search') self.search_url = reverse('wagtailadmin_pages:search') + '?q=hello' @grant_permissions(['app.change_newsitem']) def test_has_permission(self): self.assertStatusCode(self.url, 200) def test_no_permission(self): self.assertStatusCode(self.url, 403) @grant_permissions(['app.add_newsitem', 'app.change_newsitem']) def test_search_area_appears_permission(self): response = self.client.get(self.search_url) self.assertContains(response, self.url) def test_search_area_hidden_no_permission(self): response = self.client.get(self.search_url) self.assertNotContains(response, 'News') self.assertNotContains(response, self.url)
{ "repo_name": "takeflight/wagtailnews", "path": "tests/test_permissions.py", "copies": "1", "size": "12351", "license": "bsd-2-clause", "hash": -2225936659990687500, "line_mean": 36.8865030675, "line_max": 78, "alpha_frac": 0.6517690875, "autogenerated": false, "ratio": 3.9036030341340076, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5055372121634008, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib.auth.models import User from django.core.urlresolvers import reverse_lazy from django.http import JsonResponse from django.views.generic.edit import UpdateView as BaseUpdateView, CreateView as BaseCreateView, DeleteView as BaseDeleteView from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.views.generic import TemplateView from django.shortcuts import get_object_or_404 from onadata.apps.fieldsight.models import Organization, Project, Site from onadata.apps.users.models import UserProfile from .helpers import json_from_object class DeleteView(BaseDeleteView): def get(self, *args, **kwargs): return self.post(*args, **kwargs) def post(self, request, *args, **kwargs): response = super(DeleteView, self).post(request, *args, **kwargs) # messages.success(request, ('%s %s' % (self.object.__class__._meta.verbose_name.title(), _('successfully deleted!')))) return response class LoginRequiredMixin(object): @classmethod def as_view(cls, **kwargs): view = super(LoginRequiredMixin, cls).as_view(**kwargs) return login_required(view) class OrganizationOrProjectRequiredMixin(LoginRequiredMixin): def dispatch(self, request, *args, **kwargs): if not request.organization and not request.project: raise PermissionDenied() if hasattr(self, 'check'): if not getattr(request.organization, self.check)() or not getattr(request.organization, self.check)(): raise PermissionDenied() return super(OrganizationOrProjectRequiredMixin, self).dispatch(request, *args, **kwargs) class OrganizationRequiredMixin(LoginRequiredMixin): def dispatch(self, request, *args, **kwargs): if not request.organization: raise PermissionDenied() if hasattr(self, 'check'): if not getattr(request.organization, self.check)(): raise PermissionDenied() return super(OrganizationRequiredMixin, self).dispatch(request, *args, **kwargs) class ProjectRequiredMixin(LoginRequiredMixin): def dispatch(self, request, *args, **kwargs): if not request.project: raise PermissionDenied() if hasattr(self, 'check'): if not getattr(request.project, self.check)(): raise PermissionDenied() return super(ProjectRequiredMixin, self).dispatch(request, *args, **kwargs) class SiteRequiredMixin(LoginRequiredMixin): def dispatch(self, request, *args, **kwargs): if not request.site: raise PermissionDenied() if hasattr(self, 'check'): if not getattr(request.project, self.check)(): raise PermissionDenied() return super(SiteRequiredMixin, self).dispatch(request, *args, **kwargs) class UpdateView(BaseUpdateView): def get_context_data(self, **kwargs): context = super(UpdateView, self).get_context_data(**kwargs) context['scenario'] = _('Edit') context['base_template'] = 'base.html' super(UpdateView, self).get_context_data() return context class CreateView(BaseCreateView): def get_context_data(self, **kwargs): context = super(CreateView, self).get_context_data(**kwargs) context['scenario'] = _('Add') if self.request.is_ajax(): base_template = 'fieldsight/fieldsight_modal.html' else: base_template = 'fieldsight/fieldsight_base.html' context['base_template'] = base_template return context class AjaxableResponseMixin(object): def form_invalid(self, form): response = super(AjaxableResponseMixin, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(AjaxableResponseMixin, self).form_valid(form) if self.request.is_ajax(): if 'ret' in self.request.GET: obj = getattr(self.object, self.request.GET['ret']) else: obj = self.object return json_from_object(obj) else: return response class AjaxableResponseMixinUser(object): def form_invalid(self, form): response = super(AjaxableResponseMixinUser, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(AjaxableResponseMixinUser, self).form_valid(form) if self.request.is_ajax(): if 'ret' in self.request.GET: obj = getattr(self.object, self.request.GET['ret']) else: obj = self.object if isinstance(obj, User): obj.set_password(form.cleaned_data['password']) obj.is_superuser = True obj.save() org = None if hasattr(self.request, "organization"): if self.request.organization: org = self.request.organization if not org: organization = int(form.cleaned_data['organization']) org = Organization.objects.get(pk=organization) user_profile, created = UserProfile.objects.get_or_create(user=obj, organization=org) return json_from_object(obj) else: return response class TableObjectMixin(TemplateView): def get_context_data(self, *args, **kwargs): context = super(TableObjectMixin, self).get_context_data(**kwargs) if self.kwargs: pk = int(self.kwargs.get('pk')) obj = get_object_or_404(self.model, pk=pk, company=self.request.company) scenario = 'Update' else: obj = self.model(company=self.request.company) # if obj.__class__.__name__ == 'PurchaseVoucher': # tax = self.request.company.settings.purchase_default_tax_application_type # tax_scheme = self.request.company.settings.purchase_default_tax_scheme # if tax: # obj.tax = tax # if tax_scheme: # obj.tax_scheme = tax_scheme scenario = 'Create' data = self.serializer_class(obj).data context['data'] = data context['scenario'] = scenario context['obj'] = obj return context class TableObject(object): def get_context_data(self, *args, **kwargs): context = super(TableObject, self).get_context_data(**kwargs) if self.kwargs: pk = int(self.kwargs.get('pk')) obj = get_object_or_404(self.model, pk=pk, company=self.request.company) scenario = 'Update' else: obj = self.model(company=self.request.company) # if obj.__class__.__name__ == 'PurchaseVoucher': # tax = self.request.company.settings.purchase_default_tax_application_type # tax_scheme = self.request.company.settings.purchase_default_tax_scheme # if tax: # obj.tax = tax # if tax_scheme: # obj.tax_scheme = tax_scheme scenario = 'Create' data = self.serializer_class(obj).data context['data'] = data context['scenario'] = scenario context['obj'] = obj return context class OrganizationView(LoginRequiredMixin): def form_valid(self, form): if self.request.organization: form.instance.organization = self.request.organization return super(OrganizationView, self).form_valid(form) def get_queryset(self): if self.request.organization: return super(OrganizationView, self).get_queryset().filter(organization=self.request.organization) else: return super(OrganizationView, self).get_queryset() def get_form(self, *args, **kwargs): form = super(OrganizationView, self).get_form(*args, **kwargs) if self.request.organization: form.organization = self.request.organization if hasattr(form.Meta, 'organization_filters'): for field in form.Meta.organization_filters: form.fields[field].queryset = Organization.objects.filter(id=self.request.organization.pk) return form class OrganizationViewFromProfile(object): model = User success_url = reverse_lazy('fieldsight:user-list') def get_queryset(self): if self.request.organization: return super(OrganizationViewFromProfile, self).get_queryset().\ filter(user_profile__organization=self.request.organization) else: return super(OrganizationViewFromProfile, self).get_queryset().filter(pk__gt=0) class ProjectView(LoginRequiredMixin): def form_valid(self, form): if self.request.project: form.instance.project = self.request.project return super(ProjectView, self).form_valid(form) def get_queryset(self): if self.request.project: return super(ProjectView, self).get_queryset().filter(project=self.request.project) elif self.request.organization: return super(ProjectView, self).get_queryset().filter(project__organization=self.request.organization) else: return super(ProjectView, self).get_queryset() def get_form(self, *args, **kwargs): form = super(ProjectView, self).get_form(*args, **kwargs) if self.request.project: form.project = self.request.project if hasattr(form.Meta, 'project_filters'): for field in form.Meta.project_filters: if self.request.project: form.fields[field].queryset = Project.objects.filter(id=self.request.project.pk) elif self.request.organization: form.fields[field].queryset = Project.objects.filter(organization=self.request.organization) return form class SiteView(SiteRequiredMixin): def form_valid(self, form): form.instance.site = self.request.site return super(SiteView, self).form_valid(form) def get_queryset(self): return super(SiteView, self).get_queryset().filter(site=self.request.site) def get_form(self, *args, **kwargs): form = super(SiteView, self).get_form(*args, **kwargs) form.site = self.request.site if hasattr(form.Meta, 'site_filters'): for field in form.Meta.site_filters: form.fields[field].queryset = form.fields[field].queryset.filter(site=form.site) if hasattr(form.Meta, 'project_filters'): for field in form.Meta.project_filters: form.fields[field].queryset = form.fields[field].queryset.filter(project=form.site.project) return form class ProfileView(LoginRequiredMixin): def form_valid(self, form): if self.request.user: form.instance.user = self.request.user return super(ProfileView, self).form_valid(form) def get_form(self, *args, **kwargs): form = super(ProfileView, self).get_form(*args, **kwargs) if self.request.user: form.fields['first_name'].initial = self.request.user.first_name form.fields['last_name'].initial = self.request.user.last_name return form USURPERS = { # central engineer to project , same on roles. 'Site': ['Reviewer', 'Site Supervisor', 'Project Manager', 'Reviewer', 'Organization Admin', 'Super Admin'], 'KoboForms': ['Project Manager', 'Reviewer', 'Organization Admin', 'Super Admin'], 'Project': ['Project Manager', 'Organization Admin', 'Super Admin',], 'Reviewer': ['Project Manager', 'Reviewer', 'Organization Admin', 'Super Admin'], 'Organization': ['Organization Admin', 'Super Admin'], 'admin': ['Super Admin'], } class OwnerMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): pk = kwargs.get('pk') profile = UserProfile.objects.get(pk=pk) if request.user == profile.user: return super(OwnerMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied() class SiteMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.role.group.name in USURPERS['Site']: return super(SiteMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied() class ProjectMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.role.group.name in USURPERS['Project']: return super(ProjectMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied() class ReviewerMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.group.name == "Super Admin": return super(ReviewerMixin, self).dispatch(request, *args, **kwargs) elif request.group.name == "Organization Admin": pk = self.kwargs.get('pk', False) if not pk: return super(ReviewerMixin, self).dispatch(request, *args, **kwargs) else: site = Site.objects.get(pk=pk) organization = site.project.organization if organization == request.organization: return super(ReviewerMixin, self).dispatch(request, *args, **kwargs) elif request.role.group.name in USURPERS['Reviewer']: pk = self.kwargs.get('pk', False) if not pk: return super(ReviewerMixin, self).dispatch(request, *args, **kwargs) else: site = Site.objects.get(pk=pk) if site.project == request.project: return super(ReviewerMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied() class KoboFormsMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.role.group.name in USURPERS['KoboForms']: return super(KoboFormsMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied() #use in view class class OrganizationMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.role.group.name in USURPERS['Organization']: return super(OrganizationMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied() class MyOwnOrganizationMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.role.group.name in ['Super Admin']: return super(MyOwnOrganizationMixin, self).dispatch(request, *args, **kwargs) if request.role.group.name in ['Organization Admin']: if request.role.organization.pk == int(self.kwargs.get('pk','0')): return super(MyOwnOrganizationMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied() class MyOwnProjectMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.role.group.name in ['Super Admin']: return super(MyOwnProjectMixin, self).dispatch(request, *args, **kwargs) if request.role.group.name in ['Organization Admin']: if request.role.organization == Project.objects.get(pk=kwargs.get('pk', 0)).organization: return super(MyOwnProjectMixin, self).dispatch(request, *args, **kwargs) if request.role.group.name in ['Reviewer', 'Project Manager']: if request.role.project.pk == int(self.kwargs.get('pk', '0')): return super(MyOwnProjectMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied() class SuperAdminMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): if request.role.group.name in USURPERS['admin']: return super(SuperAdminMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied() # use in all view functions def group_required(group_name): def _check_group(view_func): @wraps(view_func) def wrapper(request, *args, **kwargs): if request.user.is_authenticated(): if request.role.group.name in USURPERS.get(group_name, []): return view_func(request, *args, **kwargs) raise PermissionDenied() return wrapper return _check_group
{ "repo_name": "awemulya/fieldsight-kobocat", "path": "onadata/apps/fieldsight/mixins.py", "copies": "1", "size": "17259", "license": "bsd-2-clause", "hash": -3584811459260159500, "line_mean": 40.5903614458, "line_max": 127, "alpha_frac": 0.6236166638, "autogenerated": false, "ratio": 4.231184113753371, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.001612801249193652, "num_lines": 415 }
from functools import wraps from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseForbidden from git.service import GIT_SERVICE_RECEIVE_PACK, GIT_SERVICE_UPLOAD_PACK from repository.models import Repository, RepositoryAccess from user.auth import base_auth def git_access_required(func): """ Checks to see if a repository is accessible to user. There are 3 scenarios: 1) If repository is private and user is doing a 'git-clone' or 'git-pull': In this case only users who have access to repository are admitted. 2) If repository is public and user is doing a 'git-clone' or 'git-pull': This operation is ok since repository is available for everyone. 3) If user is committing something to repository then regardless of being a public/private repository, user should be authenticated and has access to repository. """ @wraps(func) def _decorator(request, *args, **kwargs): service = _parse_git_service(request.build_absolute_uri()) user = User.objects.get(username=kwargs['username']) repo = Repository.objects.get(owner=user, name=kwargs['repository']) if service == GIT_SERVICE_UPLOAD_PACK and repo.private: # private repo and doing a 'git-clone' or 'git-pull' return _check_access(request, func, *args, **kwargs) elif service == GIT_SERVICE_UPLOAD_PACK and not repo.private: # public repo and doing a 'git-clone' or 'git-pull' return func(request, *args, **kwargs) elif service == GIT_SERVICE_RECEIVE_PACK: # doing a 'git-commit' return _check_access(request, func, *args, **kwargs) return _decorator def _check_access(request, func, *args, **kwargs): """ Checks user's authentication and access to repository. """ if request.META.get('HTTP_AUTHORIZATION'): user = base_auth(request.META['HTTP_AUTHORIZATION']) if user: repo = Repository.objects.get(owner=user, name=kwargs['repository']) access = RepositoryAccess.objects.get(user=user, repository=repo) if access: return func(request, *args, **kwargs) else: # User has no access to repository. return HttpResponseForbidden('Access forbidden.') else: # User is not registered on Djacket. return HttpResponseForbidden('Access forbidden.') res = HttpResponse() res.status_code = 401 # Basic authentication is needed. res['WWW-Authenticate'] = 'Basic' return res def _parse_git_service(request_path): """ Parses request url and specifies which git service is requested. """ if request_path.endswith('git-upload-pack'): return GIT_SERVICE_UPLOAD_PACK elif request_path.endswith('git-receive-pack'): return GIT_SERVICE_RECEIVE_PACK else: return None
{ "repo_name": "Djacket/djacket", "path": "core/backend/git/decorators.py", "copies": "1", "size": "2966", "license": "mit", "hash": -2638062753596887000, "line_mean": 42.6176470588, "line_max": 121, "alpha_frac": 0.6581254214, "autogenerated": false, "ratio": 4.2371428571428575, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5395268278542857, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib.auth.views import redirect_to_login from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from django.utils.decorators import available_attrs from sphinxdoc.models import Project def user_allowed_for_project(view_func): """ Check that the user is allowed for the project. If the user is not allowed, the view will be redirected to the standard login page. """ @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): try: slug = kwargs['slug'] except IndexError: raise ImproperlyConfigured project = get_object_or_404(Project, slug=slug) if project.is_allowed(request.user): return view_func(request, *args, **kwargs) if request.user.is_authenticated(): raise PermissionDenied path = request.build_absolute_uri() return redirect_to_login(path) return _wrapped_view
{ "repo_name": "kamni/django-sphinxdoc", "path": "sphinxdoc/decorators.py", "copies": "1", "size": "1100", "license": "mit", "hash": -5008816620252744000, "line_mean": 31.3529411765, "line_max": 75, "alpha_frac": 0.6954545455, "autogenerated": false, "ratio": 4.313725490196078, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5509180035696077, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib.contenttypes.models import ContentType def memoize(func, cache, num_args): """ Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be usable as dictionary keys. Only the first num_args are considered when creating the key. """ @wraps(func) def wrapper(*args): mem_args = args[:num_args] if mem_args in cache: return cache[mem_args] result = func(*args) cache[mem_args] = result return result return wrapper _get_content_type_for_model_cache = {} def get_content_type_for_model(model): return ContentType.objects.get_for_model(model) get_content_type_for_model = memoize(get_content_type_for_model, _get_content_type_for_model_cache, 1) def get_templates(instance, key, name, base='bookmarks'): """ Return a list of template names based on given *instance* and bookmark *key*. For example, if *name* is 'form.html':: bookmarks/[app_name]/[model_name]/[key]/form.html bookmarks/[app_name]/[model_name]/form.html bookmarks/[app_name]/[key]/form.html bookmarks/[app_name]/form.html bookmarks/[key]/form.html bookmarks/form.html """ app_label = instance._meta.app_label module_name = instance._meta.module_name return [ '%s/%s/%s/%s/%s' % (base, app_label, module_name, key, name), '%s/%s/%s/%s' % (base, app_label, module_name, name), '%s/%s/%s/%s' % (base, app_label, key, name), '%s/%s/%s' % (base, app_label, name), '%s/%s/%s' % (base, key, name), '%s/%s' % (base, name), ]
{ "repo_name": "gradel/django-generic-bookmarks", "path": "bookmarks/utils.py", "copies": "1", "size": "1728", "license": "mit", "hash": -5686530245159022000, "line_mean": 28.7931034483, "line_max": 76, "alpha_frac": 0.6128472222, "autogenerated": false, "ratio": 3.4353876739562623, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45482348961562624, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib import admin from django.shortcuts import render_to_response from .job import run_job from .models import Job, Artefact class ArtefactInline(admin.TabularInline): model = Artefact class JobAdmin(admin.ModelAdmin): class Meta: model = Job inlines = [ ArtefactInline, ] list_display = ('command', 'command_args', 'command_kwargs', 'status') admin.site.register(Job, JobAdmin) def action_factory(action): """ Converts your existing admin action into a Director background action Example: background_action = action_factory(download_as_csv) admin.site.add_action(background_action, 'download_as_csv') """ @wraps(action) def proxy_action(*args, **kwargs): job = run_job(action, *args, **kwargs) return render_to_response( 'director/admin_job_action.html', { 'job': job, 'opts': job._meta, } ) return proxy_action
{ "repo_name": "anentropic/django-director", "path": "director/admin.py", "copies": "1", "size": "1042", "license": "mit", "hash": -4289076413876069000, "line_mean": 21.170212766, "line_max": 74, "alpha_frac": 0.6247600768, "autogenerated": false, "ratio": 3.917293233082707, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5042053309882707, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib import auth from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User as djUser from django.core.urlresolvers import reverse from django.http.response import HttpResponseRedirect, JsonResponse from django.shortcuts import (get_object_or_404, redirect, render, render_to_response) from django.template.context import RequestContext from rest_framework import status from .forms import UserCreateForm, UserEditForm from .models import User def to_json_response(response): status_code = response.status_code data = None if status.is_success(status_code): if hasattr(response, 'is_rendered') and not response.is_rendered: response.render() data = {'data': response.content} elif status.is_redirect(status_code): data = {'redirect': response.url} elif (status.is_client_error(status_code) or status.is_server_error(status_code)): data = {'errors': [{ 'status': status_code }]} return JsonResponse(data) def accepts_ajax(ajax_template_name=None): """ Decorator for views that checks if the request was made via an XMLHttpRequest. Calls the view function and converts the output to JsonResponse. """ def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): if request.is_ajax(): kwargs['template_name'] = ajax_template_name response = view_func(request, *args, **kwargs) return to_json_response(response) return view_func(request, *args, **kwargs) return _wrapped_view return decorator @accepts_ajax(ajax_template_name='registration/_signup.html') def create_user(request, template_name='registration/signup.html'): if request.method == "POST": form = UserCreateForm(request.POST, request.FILES, instance=djUser()) if form.is_valid(): form.save() new_user = auth.authenticate(username=request.POST['username'], password=request.POST['password1']) # We now save the user into the Expfactory User object, with a role expfactory_user, _ = User.objects.update_or_create(user=new_user, role="LOCAL") expfactory_user.save() auth.login(request, new_user) # Do something. Should generally end with a redirect. For example: if request.POST['next']: return HttpResponseRedirect(request.POST['next']) else: return HttpResponseRedirect(reverse("my_profile")) else: form = UserCreateForm(instance=User()) context = {"form": form, "request": request} return render(request, template_name, context) def view_profile(request, username=None): if not username: if not request.user.is_authenticated(): return redirect('%s?next=%s' % (reverse('login'), request.path)) else: user = request.user else: user = get_object_or_404(User, username=username) return render(request, 'registration/profile.html', {'user': user}) @login_required def edit_user(request): edit_form = UserEditForm(request.POST or None, instance=request.user) if request.method == "POST": if edit_form.is_valid(): edit_form.save() return HttpResponseRedirect(reverse("my_profile")) return render_to_response("registration/edit_user.html", {'form': edit_form}, context_instance=RequestContext(request)) # def login(request): # return render_to_response('home.html', { # 'plus_id': getattr(settings, 'SOCIAL_AUTH_GOOGLE_PLUS_KEY', None) # }, RequestContext(request))
{ "repo_name": "expfactory/expfactory-docker", "path": "expdj/apps/users/views.py", "copies": "2", "size": "3983", "license": "mit", "hash": 1413642146524776000, "line_mean": 34.8828828829, "line_max": 79, "alpha_frac": 0.6228973136, "autogenerated": false, "ratio": 4.28740581270183, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.591030312630183, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib import messages from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.http import HttpResponseForbidden, HttpResponseRedirect from django.shortcuts import redirect, render, get_object_or_404 from django.views.decorators.cache import cache_page, never_cache from django.views.decorators.http import require_POST import commonware.log from funfactory.urlresolvers import reverse from tower import ugettext as _ from apps.groups.helpers import stringify_groups from apps.groups.models import Group from apps.users.models import UserProfile from apps.users.tasks import remove_from_basket_task import forms from models import Invite log = commonware.log.getLogger('m.phonebook') BAD_VOUCHER = 'Unknown Voucher' def vouch_required(f): """If a user is not vouched they get a 403.""" @login_required @wraps(f) def wrapped(request, *args, **kwargs): if request.user.get_profile().is_vouched: return f(request, *args, **kwargs) else: log.warning('vouch_required forbidding access') return HttpResponseForbidden(_('You must be vouched to do this.')) return wrapped @never_cache def home(request): if request.user.is_authenticated(): profile = request.user.get_profile() my_groups = profile.groups.exclude(steward=None).order_by('name') curated_groups = Group.get_curated() data = dict(groups=my_groups, curated_groups=curated_groups) return render(request, 'phonebook/home.html', data) else: return render(request, 'phonebook/home.html') @never_cache @login_required def profile(request, username): """View a profile by username.""" user = get_object_or_404(User, username=username) vouch_form = None profile = user.get_profile() if not request.user.userprofile.is_vouched and request.user != user: log.warning('vouch_required forbidding access') return HttpResponseForbidden(_('You must be vouched to do this.')) if not profile.is_vouched and request.user.get_profile().is_vouched: vouch_form = forms.VouchForm(initial=dict(vouchee=profile.pk)) data = dict(shown_user=user, profile=profile, vouch_form=vouch_form) return render(request, 'phonebook/profile.html', data) @never_cache @login_required def edit_profile(request): """Edit user profile view.""" # Don't user request.user user = User.objects.get(pk=request.user.id) profile = user.get_profile() user_groups = stringify_groups(profile.groups.all().order_by('name')) user_skills = stringify_groups(profile.skills.all().order_by('name')) user_languages = stringify_groups(profile.languages.all().order_by('name')) user_form = forms.UserForm(request.POST or None, instance=user) profile_form = forms.ProfileForm( request.POST or None, request.FILES or None, instance=profile, initial=dict(groups=user_groups, skills=user_skills, languages=user_languages), locale=request.locale) if request.method == 'POST': if (user_form.is_valid() and profile_form.is_valid()): old_username = request.user.username user_form.save() profile_form.save() # Notify the user that their old profile URL won't work. if user.username != old_username: messages.info(request, _(u'You changed your username; please ' 'note your profile URL has also ' 'changed.')) return redirect(reverse('profile', args=[user.username])) d = dict(profile_form=profile_form, user_form=user_form, mode='edit', user_groups=user_groups, my_vouches=UserProfile.objects.filter(vouched_by=profile), profile=profile, apps=user.apiapp_set.filter(is_active=True)) # If there are form errors, don't send a 200 OK. status = 400 if (profile_form.errors or user_form.errors) else 200 return render(request, 'phonebook/edit_profile.html', d, status=status) @never_cache @login_required def confirm_delete(request): """Display a confirmation page asking the user if they want to leave. """ return render(request, 'phonebook/confirm_delete.html') @never_cache @login_required @require_POST def delete(request): user_profile = request.user.get_profile() remove_from_basket_task.delay(user_profile.id) user_profile.anonymize() log.info('Deleting %d' % user_profile.user.id) logout(request) return redirect(reverse('home')) @vouch_required def search(request): num_pages = 0 limit = None nonvouched_only = False picture_only = False people = [] show_pagination = False form = forms.SearchForm(request.GET) groups = None curated_groups = None if form.is_valid(): query = form.cleaned_data.get('q', u'') limit = form.cleaned_data['limit'] vouched = False if form.cleaned_data['nonvouched_only'] else None profilepic = True if form.cleaned_data['picture_only'] else None page = request.GET.get('page', 1) curated_groups = Group.get_curated() # If nothing has been entered don't load any searches. if not (not query and vouched is None and profilepic is None): profiles = UserProfile.search(query, vouched=vouched, photo=profilepic) groups = Group.search(query) paginator = Paginator(profiles, limit) try: people = paginator.page(page) except PageNotAnInteger: people = paginator.page(1) except EmptyPage: people = paginator.page(paginator.num_pages) if len(profiles) == 1 and not groups: return redirect(reverse('profile', args=[people[0].user.username])) if paginator.count > forms.PAGINATION_LIMIT: show_pagination = True num_pages = len(people.paginator.page_range) d = dict(people=people, form=form, limit=limit, nonvouched_only=nonvouched_only, picture_only=picture_only, show_pagination=show_pagination, num_pages=num_pages, groups=groups, curated_groups=curated_groups) if request.is_ajax(): return render(request, 'search_ajax.html', d) return render(request, 'phonebook/search.html', d) @cache_page(60 * 60 * 168) # 1 week. def search_plugin(request): """Render an OpenSearch Plugin.""" return render(request, 'phonebook/search_opensearch.xml', content_type='application/opensearchdescription+xml') @login_required def invited(request, id): invite = Invite.objects.get(pk=id) return render(request, 'phonebook/invited.html', dict(invite=invite)) @vouch_required def invite(request): if request.method == 'POST': f = forms.InviteForm(request.POST) if f.is_valid(): profile = request.user.get_profile() invite = f.save(profile) invite.send(sender=profile) return HttpResponseRedirect(reverse(invited, args=[invite.id])) else: f = forms.InviteForm() data = dict(form=f) return render(request, 'phonebook/invite.html', data) @vouch_required @require_POST def vouch(request): """Vouch a user.""" form = forms.VouchForm(request.POST) if form.is_valid(): p = UserProfile.objects.get(pk=form.cleaned_data.get('vouchee')) p.vouch(request.user.get_profile()) # Notify the current user that they vouched successfully. msg = _(u'Thanks for vouching for a fellow Mozillian! ' 'This user is now vouched!') messages.info(request, msg) return redirect(reverse('profile', args=[p.user.username])) return HttpResponseForbidden
{ "repo_name": "satdav/mozillians", "path": "apps/phonebook/views.py", "copies": "1", "size": "8300", "license": "bsd-3-clause", "hash": -3246758227456984000, "line_mean": 32.6032388664, "line_max": 79, "alpha_frac": 0.6422891566, "autogenerated": false, "ratio": 3.8658593386120166, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0000880126738250308, "num_lines": 247 }
from functools import wraps from django.contrib import messages from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.views import redirect_to_login from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse_lazy from django.shortcuts import render from django.utils.six.moves.urllib import parse from django.utils.translation import ugettext_lazy as _ from oscar.core.compat import user_is_authenticated def staff_member_required(view_func, login_url=None): """ Ensure that the user is a logged-in staff member. * If not authenticated, redirect to a specified login URL. * If not staff, show a 403 page This decorator is based on the decorator with the same name from django.contrib.admin.views.decorators. This one is superior as it allows a redirect URL to be specified. """ if login_url is None: login_url = reverse_lazy('customer:login') @wraps(view_func) def _checklogin(request, *args, **kwargs): if request.user.is_active and request.user.is_staff: return view_func(request, *args, **kwargs) # If user is not logged in, redirect to login page if not user_is_authenticated(request.user): # If the login url is the same scheme and net location then just # use the path as the "next" url. path = request.build_absolute_uri() login_scheme, login_netloc = parse.urlparse(login_url)[:2] current_scheme, current_netloc = parse.urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() messages.warning(request, _("You must log in to access this page")) return redirect_to_login(path, login_url, REDIRECT_FIELD_NAME) else: # User does not have permission to view this page raise PermissionDenied return _checklogin def check_permissions(user, permissions): """ Permissions can be a list or a tuple of lists. If it is a tuple, every permission list will be evaluated and the outcome will be checked for truthiness. Each item of the list(s) must be either a valid Django permission name (model.codename) or a property or method on the User model (e.g. 'is_active', 'is_superuser'). Example usage: - permissions_required(['is_staff', ]) would replace staff_member_required - permissions_required(['is_anonymous', ]) would replace login_forbidden - permissions_required((['is_staff',], ['partner.dashboard_access'])) allows both staff users and users with the above permission """ def _check_one_permission_list(perms): regular_permissions = [perm for perm in perms if '.' in perm] conditions = [perm for perm in perms if '.' not in perm] # always check for is_active if not checking for is_anonymous if (conditions and 'is_anonymous' not in conditions and 'is_active' not in conditions): conditions.append('is_active') attributes = [getattr(user, perm) for perm in conditions] # evaluates methods, explicitly casts properties to booleans passes_conditions = all([ attr() if callable(attr) else bool(attr) for attr in attributes]) return passes_conditions and user.has_perms(regular_permissions) if not permissions: return True elif isinstance(permissions, list): return _check_one_permission_list(permissions) else: return any(_check_one_permission_list(perm) for perm in permissions) def permissions_required(permissions, login_url=None): """ Decorator that checks if a user has the given permissions. Accepts a list or tuple of lists of permissions (see check_permissions documentation). If the user is not logged in and the test fails, she is redirected to a login page. If the user is logged in, she gets a HTTP 403 Permission Denied message, analogous to Django's permission_required decorator. """ if login_url is None: login_url = reverse_lazy('customer:login') def _check_permissions(user): outcome = check_permissions(user, permissions) if not outcome and user_is_authenticated(user): raise PermissionDenied else: return outcome return user_passes_test(_check_permissions, login_url=login_url) def login_forbidden(view_func, template_name='login_forbidden.html', status=403): """ Only allow anonymous users to access this view. """ @wraps(view_func) def _checklogin(request, *args, **kwargs): if not user_is_authenticated(request.user): return view_func(request, *args, **kwargs) return render(request, template_name, status=status) return _checklogin
{ "repo_name": "sonofatailor/django-oscar", "path": "src/oscar/views/decorators.py", "copies": "5", "size": "5064", "license": "bsd-3-clause", "hash": -6806849112219631000, "line_mean": 38.5625, "line_max": 79, "alpha_frac": 0.672985782, "autogenerated": false, "ratio": 4.298811544991511, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 128 }
from functools import wraps from django.contrib import messages from django.shortcuts import redirect from django.template.response import TemplateResponse from django.utils.translation import pgettext from django.views.decorators.http import require_POST from ..core import load_checkout from ...discount.forms import CheckoutDiscountForm from ...discount.models import Voucher def add_voucher_form(view): @wraps(view) def func(request, checkout): prefix = 'discount' data = {k: v for k, v in request.POST.items() if k.startswith(prefix)} voucher_form = CheckoutDiscountForm( data or None, checkout=checkout, prefix=prefix) if voucher_form.is_bound: if voucher_form.is_valid(): voucher_form.apply_discount() next_url = request.GET.get( 'next', request.META['HTTP_REFERER']) return redirect(next_url) else: del checkout.discount del checkout.voucher_code # if only discount form was used we clear post for other forms request.POST = {} else: checkout.recalculate_discount() response = view(request, checkout) if isinstance(response, TemplateResponse): voucher = voucher_form.initial.get('voucher') response.context_data['voucher_form'] = voucher_form response.context_data['voucher'] = voucher return response return func def validate_voucher(view): @wraps(view) def func(request, checkout, cart): if checkout.voucher_code: try: Voucher.objects.active().get(code=checkout.voucher_code) except Voucher.DoesNotExist: del checkout.voucher_code checkout.recalculate_discount() msg = pgettext( 'Checkout warning', 'This voucher has expired. Please review your checkout.') messages.warning(request, msg) return redirect('checkout:summary') return view(request, checkout, cart) return func @require_POST @load_checkout def remove_voucher_view(request, checkout, cart): next_url = request.GET.get('next', request.META['HTTP_REFERER']) del checkout.discount del checkout.voucher_code return redirect(next_url)
{ "repo_name": "jreigel/saleor", "path": "saleor/checkout/views/discount.py", "copies": "7", "size": "2405", "license": "bsd-3-clause", "hash": -4040458176382093000, "line_mean": 34.8955223881, "line_max": 78, "alpha_frac": 0.6249480249, "autogenerated": false, "ratio": 4.572243346007604, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8697191370907604, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib import messages from django.shortcuts import redirect from django.utils.decorators import method_decorator from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from remo.base.utils import get_object_or_none from funfactory.helpers import urlparams def permission_check(permissions=[], group=None, filter_field=None, owner_field=None, model=None): """Check if a user is logged in and has the required permissions. 1. If user is not logged in then redirect to 'main', display login message 2. If user logged in and len(/permissions/) == 0, group != None and /filter_field/ == None then allow access 3. If user logged in and len(/permissions/) > 0, group != None and /filter_field/ == None then allow access only if user has all permissions 4. If user logged in and len(/permissions/) > 0 and group == None and /filter_field/ != None then allow access if user has all permissions or there is an object in /model/ with attributes /filter_field/ == kwargs[filter_field] and /owner_field/ == request.user. 5. If user logged in and len(permissions) == 0 and group == None and filter_field != None then allow access only if there is an object in /model/ with attributes /filter_field/ == kwargs[filter_field] and /owner_field/ == request.user. 6. If user logged in and len(permissions) == 0 and group != None and /filter_field/ == None then allow access if user is member of Group. 7. If user logged in and len(/permissions/) > 0 and group != None and /filter_field/ != None then allow access if user has all permissions or is part of group or there is an object in /model/ with attributes /filter_field/ == kwargs[filter_field] and /owner_field/ == request.user. 8. If user logged in and len(permissions) == 0 and group != None and filter_field != None then allow access only if user is part of group or there is an object in /model/ with attributes /filter_field/ == kwargs[filter_field] and /owner_field/ == request.user. """ def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): def _check_if_user_has_permissions(): if (((permissions and request.user.has_perms(permissions)) or request.user.groups.filter(name=group).exists())): return True return False def _check_if_user_owns_page(): if owner_field and model: if not kwargs.get(filter_field): return True obj = get_object_or_none(model, **{filter_field: kwargs[filter_field]}) if obj and getattr(obj, owner_field) == request.user: return True return False if request.user.is_authenticated(): if (((not permissions and not group and not filter_field) or request.user.is_superuser or _check_if_user_owns_page() or _check_if_user_has_permissions())): return func(request, *args, **kwargs) else: messages.error(request, 'Permission denied.') return redirect('main') else: messages.warning(request, 'Please login.') next_url = urlparams(reverse('main'), next=request.path) return HttpResponseRedirect(next_url) return wrapper return decorator class PermissionMixin(object): """Permission mixin for base content views.""" groups = ['Admin'] def __init__(self, **kwargs): groups = kwargs.pop('groups', None) if groups: self.groups = groups super(PermissionMixin, self).__init__(**kwargs) @method_decorator(permission_check()) def dispatch(self, request, *args, **kwargs): if not request.user.groups.filter(name__in=self.groups).exists(): messages.error(request, 'Permission denied.') return redirect('main') return super(PermissionMixin, self).dispatch(request, *args, **kwargs)
{ "repo_name": "chirilo/remo", "path": "remo/base/decorators.py", "copies": "3", "size": "4336", "license": "bsd-3-clause", "hash": 5188769711069400000, "line_mean": 38.7798165138, "line_max": 78, "alpha_frac": 0.6093173432, "autogenerated": false, "ratio": 4.479338842975206, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 109 }
from functools import wraps from django.contrib import messages from django.shortcuts import redirect from confucius.models import Conference, Membership def role_required(test_func): def decorator(view_func): def inner_decorator(request, *args, **kwargs): pk = kwargs.pop('conference_pk', None) membership = None try: if pk is not None: conference = Conference.objects.get(pk=pk) else: conference = request.user.get_last_accessed_conference() membership = Membership.objects.get(user=request.user, conference=conference) except: pass if not membership or not test_func(membership): messages.warning(request, u'Unauthorized access.') return redirect('membership_list') membership.set_last_accessed() request.membership = membership request.conference = conference if not membership.domains.all() : messages.warning(request, u'Please select your domains !!') return redirect('membership',request.conference.pk) return view_func(request, *args, **kwargs) return wraps(view_func)(inner_decorator) return decorator def has_chair_role(view_func): def has_chair_role(membership): return membership.has_chair_role() decorator = role_required(has_chair_role) return decorator(view_func) def has_reviewer_role(view_func): def has_chair_role(membership): return membership.has_reviewer_role() or membership.has_chair_role() decorator = role_required(has_chair_role) return decorator(view_func) def has_submitter_role(view_func): def has_chair_role(membership): return membership.has_submitter_role() or membership.has_chair_role() decorator = role_required(has_chair_role) return decorator(view_func) def has_role(view_func): decorator = role_required(lambda m: True) return decorator(view_func)
{ "repo_name": "jfouca/confucius", "path": "confucius/decorators.py", "copies": "1", "size": "2112", "license": "bsd-3-clause", "hash": 1843415584846560500, "line_mean": 31.4923076923, "line_max": 93, "alpha_frac": 0.6325757576, "autogenerated": false, "ratio": 4.249496981891348, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5382072739491348, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib import messages from django.utils.decorators import available_attrs from django.http import HttpResponseRedirect def user_passes_test(test_func, login_url=None, message=None): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ if not login_url: from .utils import get_login_url login_url = get_login_url() def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) if message is not None: messages.info(request, message, fail_silently=True) response = HttpResponseRedirect(login_url) if request.method != 'GET': from .helpers import save_next_action data = { 'action': request.META.get('PATH_INFO'), 'args': args, 'kwargs': kwargs, 'method': request.method, 'parameters': { 'POST': request.POST.urlencode() if request.POST else None, } } save_next_action(request, response, data) return response return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator def login_required(function=None, message=None, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated(), message=message, login_url=login_url ) if function: return actual_decorator(function) return actual_decorator
{ "repo_name": "thoas/django-backward", "path": "backward/decorators.py", "copies": "1", "size": "1983", "license": "mit", "hash": 7565412773987969000, "line_mean": 31.5081967213, "line_max": 83, "alpha_frac": 0.5980837115, "autogenerated": false, "ratio": 4.527397260273973, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00039032006245121, "num_lines": 61 }
from functools import wraps from django.contrib.sites.models import get_current_site from django.core import urlresolvers from django.core.paginator import EmptyPage, PageNotAnInteger from django.http import Http404 from django.template.response import TemplateResponse from django.utils import six def x_robots_tag(func): @wraps(func) def inner(request, *args, **kwargs): response = func(request, *args, **kwargs) response['X-Robots-Tag'] = 'noindex, noodp, noarchive' return response return inner @x_robots_tag def index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap'): req_protocol = 'https' if request.is_secure() else 'http' req_site = get_current_site(request) sites = [] for section, site in sitemaps.items(): if callable(site): site = site() protocol = req_protocol if site.protocol is None else site.protocol sitemap_url = urlresolvers.reverse( sitemap_url_name, kwargs={'section': section}) absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url) sites.append(absolute_url) for page in range(2, site.paginator.num_pages + 1): sites.append('%s?p=%s' % (absolute_url, page)) return TemplateResponse(request, template_name, {'sitemaps': sites}, content_type=content_type) @x_robots_tag def sitemap(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml'): req_protocol = 'https' if request.is_secure() else 'http' req_site = get_current_site(request) if section is not None: if section not in sitemaps: raise Http404("No sitemap available for section: %r" % section) maps = [sitemaps[section]] else: maps = list(six.itervalues(sitemaps)) page = request.GET.get("p", 1) urls = [] for site in maps: try: if callable(site): site = site() urls.extend(site.get_urls(page=page, site=req_site, protocol=req_protocol)) except EmptyPage: raise Http404("Page %s empty" % page) except PageNotAnInteger: raise Http404("No page '%s'" % page) return TemplateResponse(request, template_name, {'urlset': urls}, content_type=content_type)
{ "repo_name": "makinacorpus/django", "path": "django/contrib/sitemaps/views.py", "copies": "1", "size": "2512", "license": "bsd-3-clause", "hash": 9186603623373989000, "line_mean": 35.9411764706, "line_max": 77, "alpha_frac": 0.6234076433, "autogenerated": false, "ratio": 3.955905511811024, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0027135854341736694, "num_lines": 68 }
from functools import wraps from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.utils.module_loading import import_string from filer.settings import FILER_ROLES_MANAGER def get_roles_manager(): if hasattr(get_roles_manager, '_cache'): return get_roles_manager._cache try: if callable(FILER_ROLES_MANAGER): manager = FILER_ROLES_MANAGER() manager = import_string(FILER_ROLES_MANAGER)() except ImportError: err_msg = ("Cannot import {}! This should be a manager for permissions." "Please consult documentation.".format(FILER_ROLES_MANAGER)) raise ImproperlyConfigured(err_msg) get_roles_manager._cache = manager return manager def get_or_fetch(fetch_func): """ Helper decorator that sets the result of the decorated function on a user request object. It is used to minimise the number of queries done per request. """ @wraps(fetch_func) def wrapper(user, *args, **kwargs): attr_name = '_%s' % fetch_func.__name__ if not hasattr(user, attr_name): result = fetch_func(user, *args, **kwargs) setattr(user, attr_name, result) return getattr(user, attr_name) return wrapper @get_or_fetch def has_admin_role(user): return get_roles_manager().is_site_admin(user) def can_restrict_on_site(user, site): site_id = site if not str(site_id).isnumeric(): site_id = getattr(site, 'id', None) def _fetch_perm_existance(): manager = get_roles_manager() return manager.has_perm_on_site(user, site_id, 'filer.can_restrict_operations') if user.is_superuser or (site_id is None and has_admin_role(user)): return True if site_id: if not hasattr(user, '_can_restrict_on_site'): setattr(user, '_can_restrict_on_site', {}) return user._can_restrict_on_site.setdefault( site_id, _fetch_perm_existance()) return False def get_sites_without_restriction_perm(user): if user.is_superuser: return [] return [site for site in get_sites_for_user(user) if can_restrict_on_site(user, site) is False] @get_or_fetch def get_admin_sites_for_user(user): return get_roles_manager().get_administered_sites(user) def has_role_on_site(user, site): return user.is_superuser or site.id in get_sites_for_user(user) def has_admin_role_on_site(user, site): return site.id in [_site.id for _site in get_admin_sites_for_user(user)] @get_or_fetch def get_sites_for_user(user): """ Returns all sites available for user. """ if user.is_superuser: return set(Site.objects.values_list('id', flat=True)) return get_roles_manager().get_accessible_sites(user)
{ "repo_name": "pbs/django-filer", "path": "filer/utils/cms_roles.py", "copies": "1", "size": "2863", "license": "bsd-3-clause", "hash": 7633846157807199000, "line_mean": 29.1368421053, "line_max": 87, "alpha_frac": 0.6496681802, "autogenerated": false, "ratio": 3.583229036295369, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.973164935779137, "avg_score": 0.00024957174079981095, "num_lines": 95 }
from functools import wraps from django.core.cache import cache from django.http import HttpResponseBadRequest from django.core.exceptions import ObjectDoesNotExist def get_cache_key(prefix, *args, **kwargs): """ Calculates cache key based on `args` and `kwargs`. `args` and `kwargs` must be instances of hashable types. """ hash_args_kwargs = hash(tuple(kwargs.iteritems()) + args) return '{}_{}'.format(prefix, hash_args_kwargs) def cache_method(func=None, prefix=''): """ Cache result of function execution into the `self` object (mostly useful in models). Calculate cache key based on `args` and `kwargs` of the function (except `self`). """ def decorator(func): @wraps(func) def wrapper(self, *args, **kwargs): cache_key_prefix = prefix or '_cache_{}'.format(func.__name__) cache_key = get_cache_key(cache_key_prefix, *args, **kwargs) if not hasattr(self, cache_key): setattr(self, cache_key, func(self)) return getattr(self, cache_key) return wrapper if func is None: return decorator else: return decorator(func) def cache_func(prefix, method=False): """ Cache result of function execution into the django cache backend. Calculate cache key based on `prefix`, `args` and `kwargs` of the function. For using like object method set `method=True`. """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): cache_args = args if method: cache_args = args[1:] cache_key = get_cache_key(prefix, *cache_args, **kwargs) cached_value = cache.get(cache_key) if cached_value is None: cached_value = func(*args, **kwargs) cache.set(cache_key, cached_value) return cached_value return wrapper return decorator def get_or_default(func=None, default=None): """ Wrapper around Django's ORM `get` functionality. Wrap anything that raises ObjectDoesNotExist exception and provide the default value if necessary. `default` by default is None. `default` can be any callable, if it is callable it will be called when ObjectDoesNotExist exception will be raised. """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ObjectDoesNotExist: if callable(default): return default() else: return default return wrapper if func is None: return decorator else: return decorator(func) def ajax_required(func): @wraps(func) def wrapper(request, *args, **kwargs): if request.method == 'POST' and request.is_ajax(): return func(request, *args, **kwargs) return HttpResponseBadRequest() return wrapper
{ "repo_name": "steelkiwi/django-skd-tools", "path": "skd_tools/decorators.py", "copies": "1", "size": "3012", "license": "mit", "hash": 1083305489574984200, "line_mean": 32.0989010989, "line_max": 88, "alpha_frac": 0.6075697211, "autogenerated": false, "ratio": 4.3652173913043475, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5472787112404347, "avg_score": null, "num_lines": null }
from functools import wraps from django.core.cache import cache from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from django.core.exceptions import ValidationError from django.contrib.formtools.preview import FormPreview try: from django.db.transaction import atomic except ImportError: # DROP_WITH_DJANGO15 # pragma: no cover from django.db.transaction import commit_on_success as atomic try: from django.utils.encoding import force_text except ImportError: # DROP_WITH_DJANGO13 # pragma: no cover from django.utils.encoding import force_unicode as force_text try: from django.utils.text import slugify except ImportError: # DROP_WITH_DJANGO14 # pragma: no cover from django.template.defaultfilters import slugify from .models import Embed from .backends import InvalidResponseError IS_POPUP_VAR = "_popup" def generate_cache_key(backend, url): cache_key = "armstrong.apps.embeds-response-for-%s-%s" % \ (backend.pk, slugify(unicode(url))) return cache_key[:250] # memcached max key length # TODO relocate to a shared location # TODO if Django updates this class to use class-based Views # (as they did with FormWizard in Django 1.4) this will need to change, though # some things (such as admin_view() wrapping) will be dramatically easier class AdminFormPreview(FormPreview): """ Adapt FormPreview into the Admin replacing the normal add/change views with a two-step process for editing a Model and previewing before save. """ def __init__(self, form, admin): super(AdminFormPreview, self).__init__(form) self.admin = admin self.model = self.admin.model self.object_id = None self.object = None self.action = "add" self.admin.add_form_template = self.form_template self.admin.change_form_template = self.preview_template def __call__(self, request, *args, **kwargs): """Wrap the FormPreview in Admin decorators""" # Change View if we've been passed an object_id if len(args) >= 1: try: from django.contrib.admin.utils import unquote except ImportError: # DROP_WITH_DJANGO16 # pragma: no cover from django.contrib.admin.util import unquote self.object_id = args[0] self.action = "change" self.object = self.admin.get_object(request, unquote(self.object_id)) method = super(AdminFormPreview, self).__call__ method = self.perm_check(method) method = self.admin.admin_site.admin_view(method) return method(request, *args, **kwargs) def perm_check(self, func): """Provide permissions checking normally handled in add_view() and change_view()""" @wraps(func) def wrapper(request, *args, **kwargs): if self.object_id and not self.object: from django.utils.html import escape from django.http import Http404 raise Http404( _('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(self.model._meta.verbose_name), 'key': escape(self.object_id)}) from django.core.exceptions import PermissionDenied if self.action == "add" and not self.admin.has_add_permission(request): raise PermissionDenied elif not self.admin.has_change_permission(request, self.object): raise PermissionDenied return func(request, *args, **kwargs) return wrapper def get_context(self, request, form): """Provide templates vars expected by the Admin change_form.html""" opts = self.model._meta context = super(AdminFormPreview, self).get_context(request, form) context.update(dict( title=_('%s %s') % (self.action.title(), force_text(opts.verbose_name)), object_id=self.object_id, original=self.object, is_popup=(IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), current_app=self.admin.admin_site.name, show_delete=(self.action == "change"), app_label=opts.app_label, opts=opts, # # Other context vars present in the Admin add_view/change_view-- # Not entirely sure how or if its appropriate to use these # so acknowledge them and make it clear we aren't using them # # adminform -- our stuff is not an AdminForm # media -- collection of ModelAdmin, AdminForm and inline formset media inline_admin_formsets=[], # we know this should be empty # errors -- AdminErrorList, combines all form and formset errors )) return context def get_render_change_form_params(self, request): return dict( obj=self.object, add=(self.action == 'add'), change=(self.action == 'change')) def preview_get(self, request): """ Displays the form. Overriden to provide the model instance instead of initial data and call the Admin's render_change_form(). """ f = self.form(auto_id=self.get_auto_id(), instance=self.object) context = self.get_context(request, f) render_params = self.get_render_change_form_params(request) return self.admin.render_change_form(request, context, **render_params) def preview_post(self, request): """ Validates the POST data. If valid, displays the preview page, else redisplays form. Overriden to - provide the model instance - use Admin's render_change_form() - update the title context var - provide a "step2" context var letting us share a single tempate """ f = self.form(request.POST, auto_id=self.get_auto_id(), instance=self.object) context = self.get_context(request, f) if f.is_valid(): self.process_preview(request, f, context) context.update(dict( is_step2=True, title=_('Preview %s') % force_text(context['opts'].verbose_name), hash_field=self.unused_name('hash'), hash_value=self.security_hash(request, f))) render_params = self.get_render_change_form_params(request) return self.admin.render_change_form(request, context, **render_params) def post_post(self, request): """ Validates the POST data. If valid, calls done(). Else, redisplays form. Overriden to - supply the form model instance - call preview_post() instead of calling its own render - add transaction support """ f = self.form(request.POST, auto_id=self.get_auto_id(), instance=self.object) if f.is_valid(): if not self._check_security_hash(request.POST.get(self.unused_name('hash'), ''), request, f): return self.failed_hash(request) # Security hash failed with atomic(): return self.done(request, f.cleaned_data) else: return self.preview_post(request) class EmbedFormPreview(AdminFormPreview): """ A replacement for the normal Admin edit views that provides a two-step process for editing an Embed object. Since so much of the Embed data is gathered from an API, we want to present that to the user so they have an idea what they are creating. """ form_template = "embeds/admin/embed_change_form.html" preview_template = "embeds/admin/embed_change_form.html" def process_preview(self, request, form, context): """ Generate the response (and cache it) or provide error messaging. Update the form with the auto-assigned Backend if necessary. """ try: response = form.instance.get_response() if not response.is_valid(): # throw an error so we can share the except block logic raise InvalidResponseError(response._data) except InvalidResponseError as e: msg = mark_safe(_( "Invalid response from the Backend API.<br />" "Check the URL for typos and/or try a different Backend.")) try: form.add_error(None, ValidationError(msg, code="invalid")) except AttributeError: # DROP_WITH_DJANGO16 # pragma: no cover from django.forms.forms import NON_FIELD_ERRORS if NON_FIELD_ERRORS not in form._errors: form._errors[NON_FIELD_ERRORS] = form.error_class() form._errors[NON_FIELD_ERRORS].append(msg) try: # handle dict data masquerading as an Exception string from ast import literal_eval error_dict = literal_eval(str(e)) except (ValueError, SyntaxError): # just use the string error_dict = dict(data=e) error_dict['exception'] = type(e).__name__ context['response_error'] = error_dict else: context['duplicate_response'] = (form.instance.response == response) form.instance.response = response # cache the response to prevent another API call on save # set() overwrites if anything already exists from another attempt cache_key = generate_cache_key( form.instance.backend, form.instance.url) cache.set(cache_key, form.instance.response_cache, 300) #HACK if the backend was auto-assigned the form field must also be set if not form.data['backend']: data = form.data.copy() # mutable QueryDict backends = list(form.fields['backend']._queryset) data['backend'] = backends.index(form.instance.backend) + 1 # select box options are 1-indexed form.data = data def done(self, request, cleaned_data): """Save Embed using cached response to avoid another API call""" # get or create the object and use form data embed = self.object if self.object else Embed() embed.url = cleaned_data['url'] embed.backend = cleaned_data['backend'] # load and use cached response then delete/clean up cache_key = generate_cache_key(embed.backend, embed.url) embed.response = embed.backend.wrap_response_data(cache.get(cache_key), fresh=True) cache.delete(cache_key) # save and continue with the Admin Site workflow embed.save() return self.admin.response_add(request, embed) def get_context(self, request, form): context = super(EmbedFormPreview, self).get_context(request, form) context['errornote_css_class'] = 'errornote' context['form1_submit_text'] = "Request new data & Preview" if self.action == "change" else "Preview" return context
{ "repo_name": "armstrong/armstrong.apps.embeds", "path": "armstrong/apps/embeds/admin_forms.py", "copies": "1", "size": "11104", "license": "apache-2.0", "hash": -220776903057456060, "line_mean": 40.5880149813, "line_max": 109, "alpha_frac": 0.6206772334, "autogenerated": false, "ratio": 4.272412466333205, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0006403406114981533, "num_lines": 267 }
from functools import wraps from django.core.checks import Error from minicash.core.settings import minicash_settings class NotDefined: pass def is_defined(name): return getattr(minicash_settings, name, NotDefined) != NotDefined class requires_minicash_settings: '''A decorator which checks for required Minicash settings and yields Error CheckMessages if settings are not found.''' def __init__(self, settings_list=None): self.settings_list = settings_list or [] def __call__(self, f): @wraps(f) def wrapper(*args, **kwargs): messages = list(self._check_settings_defined()) if messages: yield from messages raise StopIteration() else: if len(self.settings_list) == 1: name = self.settings_list[0] val = getattr(minicash_settings, name) yield from f(name=name, val=val, *args, **kwargs) else: yield from f(*args, **kwargs) return wrapper def _check_settings_defined(self): for setting_name in self.settings_list: if not is_defined(setting_name): yield Error( f"Setting {setting_name} is not found in settings.", id='MINICASH-CHECK-E0001' )
{ "repo_name": "BasicWolf/minicash", "path": "src/minicash/utils/checks.py", "copies": "1", "size": "1386", "license": "apache-2.0", "hash": 2701488773807183000, "line_mean": 29.8, "line_max": 72, "alpha_frac": 0.5707070707, "autogenerated": false, "ratio": 4.37223974763407, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 45 }
from functools import wraps from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.shortcuts import get_object_or_404 from django.conf import settings OWNERSHIP_REQUIRED_PASS_OBJ = getattr(settings, 'OWNERSHIP_REQUIRED_PASS_OBJ', True) OWNERSHIP_REQUIRED_CALLABLE = getattr(settings, 'OWNERSHIP_REQUIRED_CALLABLE', 'get_owner') OWNERSHIP_REQUIRED_PASS_RESULT = getattr(settings, 'OWNERSHIP_REQUIRED_PASS_RESULT', True) OWNERSHIP_REQUIRED_RESULT_NAME = getattr(settings, 'OWNERSHIP_REQUIRED_RESULT_NAME', 'is_owner') def is_owner(user, obj): if not hasattr(obj, OWNERSHIP_REQUIRED_CALLABLE): raise ImproperlyConfigured('"%s" doesn\'t have requried callable' % obj.__class__.__name__) attr = getattr(obj, OWNERSHIP_REQUIRED_CALLABLE) if not callable(attr): raise ImproperlyConfigured('"%s" attribute is not callable' % attr.__name__) return attr() == user or user.is_superuser def ownership_required(model, raise_exception=True, pass_obj=None, pass_result=None, **query): def decorator(func): def view(request, *args, **kwargs): if not len(query): raise ImproperlyConfigured('ownership_requried received empty queryset') q = query.copy() for k, v in q.items(): if v in kwargs: q[k] = kwargs[v] obj = get_object_or_404(model, **q) if pass_obj is not False: if OWNERSHIP_REQUIRED_PASS_OBJ or pass_obj: kwargs[v] = obj result = is_owner(request.user, obj) if not result and raise_exception: raise PermissionDenied if pass_result is not False: if OWNERSHIP_REQUIRED_PASS_RESULT or pass_result: setattr(request, OWNERSHIP_REQUIRED_RESULT_NAME, result) return func(request, *args, **kwargs) return wraps(func)(view) return decorator
{ "repo_name": "arturtamborski/wypok", "path": "wypok/wypok/utils/ownership_required.py", "copies": "1", "size": "1978", "license": "mit", "hash": 3452480315233919500, "line_mean": 34.9636363636, "line_max": 99, "alpha_frac": 0.6450960566, "autogenerated": false, "ratio": 4.012170385395538, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0015901734030414017, "num_lines": 55 }
from functools import wraps from django.core.exceptions import ObjectDoesNotExist from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from apps.public_api.util import (public_api_method, short_id, long_id) from apps.public_api.models import (PublicAPICommentDetails, PublicAPIGroupDetails, PublicAPIUserDetails) from canvas import util, knobs, stickers, experiments, fact from canvas.api_decorators import json_service from canvas.cache_patterns import CachedCall from canvas.exceptions import ServiceError from canvas.metrics import Metrics from canvas.models import User, Comment, Thread from canvas.view_helpers import CommentViewData @public_api_method def root(request, payload={}): """ Root of the example.com public api Available endpoints are: /public_api/ /public_api/users/ /public_api/posts/ /public_api/groups/ """ pass @public_api_method def posts(request, payload={}, short_id=None): """ Posts endpoint of the example.com public api Request with an id parameter: /public_api/posts/1qkx8 POST JSON in the following format: POST /public_api/posts/ {"ids":["1qkx8","ma6fz"]} """ Metrics.api_comment.record(request) ids = payload.get('ids') if short_id and not ids: try: comment = Comment.details_by_id(long_id(short_id), promoter=PublicAPICommentDetails) (comment,) = CachedCall.multicall([comment]) return comment.to_client() except (ObjectDoesNotExist, util.Base36DecodeException): raise ServiceError("Post not found") elif ids: ids = [long_id(x) for x in set(ids)] calls = [Comment.details_by_id(id, ignore_not_found=True, promoter=PublicAPICommentDetails) for id in ids] comments = CachedCall.multicall(calls, skip_decorator=True) return {'posts': [x.to_client() for x in comments if x]} @public_api_method def users(request, payload={}, username=None): """ Users endpoint of the example.com public api Request with an id parameter: /public_api/users/watermelonbot POST JSON in the following format: POST /public_api/users/ {"ids":["watermelonbot", "jeff"]} User posts will be returned """ + str(knobs.PUBLIC_API_PAGINATION_SIZE) + """ at a time, ordered newest to oldest. You can request posts beyond the initial range by POSTing JSON in the following format: POST /public_api/users/ {"ids":[{"user":"watermelonbot","skip":100},"jeff"} """ Metrics.api_user.record(request) if username and not payload: try: return PublicAPIUserDetails(username).to_client() except (ObjectDoesNotExist, Http404): raise ServiceError("User does not exist") elif payload: def inner_user(user_arg): try: return PublicAPIUserDetails(user_arg).to_client() except (ObjectDoesNotExist, Http404): return None potential_users = [inner_user(x) for x in payload.get('ids')] return {'users': [x for x in potential_users if x]} @public_api_method def groups(request, payload={}, group_name=None): """ Groups endpoint of the example.com public api Request with an id parameter: /public_api/groups/funny POST JSON in the following format: POST /public_api/groups/ {"ids":["funny","canvas"]} Group posts will be returned """ + str(knobs.PUBLIC_API_PAGINATION_SIZE) + """ at a time, ordered newest to oldest. You can request posts beyond the initial range by POSTing JSON in the following format: POST /public_api/groups/ {"ids":[{"group":"funny","skip":100},"canvas"} """ Metrics.api_group.record(request) ids = payload.get('ids') if group_name and not ids: try: return PublicAPIGroupDetails(group_name).to_client() except (ObjectDoesNotExist, Http404): raise ServiceError("Group does not exist") elif ids: def inner_group(group_arg): try: return PublicAPIGroupDetails(group_arg).to_client() except (ObjectDoesNotExist, Http404): return None potential_groups = [inner_group(x) for x in payload.get('ids')] return {'groups': [x for x in potential_groups if x]}
{ "repo_name": "canvasnetworks/canvas", "path": "website/apps/public_api/views.py", "copies": "1", "size": "4488", "license": "bsd-3-clause", "hash": 5399292817061321000, "line_mean": 32.2444444444, "line_max": 207, "alpha_frac": 0.6586452763, "autogenerated": false, "ratio": 3.899218071242398, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5057863347542397, "avg_score": null, "num_lines": null }
from functools import wraps from django.core.exceptions import PermissionDenied from django.contrib.auth.views import redirect_to_login from django.utils.decorators import available_attrs from mc2.organizations.models import Organization, ORGANIZATION_SESSION_KEY def active_organization(request): ''' Returns the active :py:class:`organizations.models.Organization` object for the current user. Returns None if the user is not logged in or active, or no organization has been set. :params :py:class:`django.http.HttpRequest` request: The current request :returns: :py:class:`organizations.models.Organization` ''' if not request.user.is_authenticated(): return None org_id = request.session.get(ORGANIZATION_SESSION_KEY) if org_id is None and request.user.is_superuser: return None try: if org_id is None: return Organization.objects.for_user(request.user).first() return Organization.objects.for_user(request.user).get(pk=org_id) except Organization.DoesNotExist: return None def org_permission_required(perm, login_url=None, raise_exception=False): ''' Decorator for views that checks that a user has the given permission for the active organization, redirecting to the login page if necessary. :params list or string perm: The permission(s) to check :params string login_url: The login url to redirect to if the check fails. :params bool raise_exception: Indicates whether to raise PermissionDenied if the check fails. ''' def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if isinstance(perm, basestring): perms = (perm,) else: perms = perm user = request.user organization = active_organization(request) if organization and organization.has_perms(user, perms): return view_func(request, *args, **kwargs) elif not organization and user.has_perms(perms): # user permissions supersede user-organization permissions return view_func(request, *args, **kwargs) if raise_exception: raise PermissionDenied return redirect_to_login(request.build_absolute_uri(), login_url) return _wrapped_view return decorator
{ "repo_name": "praekelt/mc2", "path": "mc2/organizations/utils.py", "copies": "1", "size": "2493", "license": "bsd-2-clause", "hash": -5707773765753588000, "line_mean": 34.1126760563, "line_max": 77, "alpha_frac": 0.6662655435, "autogenerated": false, "ratio": 4.475763016157989, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5642028559657989, "avg_score": null, "num_lines": null }
from functools import wraps from django.core.exceptions import PermissionDenied from django.contrib.auth.views import redirect_to_login from django.utils.decorators import available_attrs from organizations.models import Organization, ORGANIZATION_SESSION_KEY def active_organization(request): ''' Returns the active :py:class:`organizations.models.Organization` object for the current user. Returns None if the user is not logged in or active, or no organization has been set. :params :py:class:`django.http.HttpRequest` request: The current request :returns: :py:class:`organizations.models.Organization` ''' if not request.user.is_authenticated(): return None org_id = request.session.get(ORGANIZATION_SESSION_KEY) if org_id is None: return None try: return Organization.objects.for_user(request.user).get(pk=org_id) except Organization.DoesNotExist: return None def org_permission_required(perm, login_url=None, raise_exception=False): ''' Decorator for views that checks that a user has the given permission for the active organization, redirecting to the login page if necessary. :params list or string perm: The permission(s) to check :params string login_url: The login url to redirect to if the check fails. :params bool raise_exception: Indicates whether to raise PermissionDenied if the check fails. ''' def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if isinstance(perm, basestring): perms = (perm,) else: perms = perm user = request.user organization = active_organization(request) if organization and organization.has_perms(user, perms): return view_func(request, *args, **kwargs) elif not organization and user.has_perms(perms): # user permissions supersede user-organization permissions return view_func(request, *args, **kwargs) if raise_exception: raise PermissionDenied return redirect_to_login(request.build_absolute_uri(), login_url) return _wrapped_view return decorator
{ "repo_name": "universalcore/unicore-mc", "path": "organizations/utils.py", "copies": "1", "size": "2360", "license": "bsd-2-clause", "hash": -2336069458586184700, "line_mean": 33.7058823529, "line_max": 77, "alpha_frac": 0.6661016949, "autogenerated": false, "ratio": 4.521072796934866, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 68 }
from functools import wraps from django.core.exceptions import PermissionDenied from django.http import Http404 from django.shortcuts import redirect from django.contrib.auth.decorators import user_passes_test from helpdesk import settings as helpdesk_settings def check_staff_status(check_staff=False): """ Somewhat ridiculous currying to check user permissions without using lambdas. The function most only take one User parameter at the end for use with the Django function user_passes_test. """ def check_superuser_status(check_superuser): def check_user_status(u): is_ok = u.is_authenticated and u.is_active if check_staff: return is_ok and u.is_staff elif check_superuser: return is_ok and u.is_superuser else: return is_ok return check_user_status return check_superuser_status if callable(helpdesk_settings.HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE): # apply a custom user validation condition is_helpdesk_staff = helpdesk_settings.HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE elif helpdesk_settings.HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE: # treat 'normal' users like 'staff' is_helpdesk_staff = check_staff_status(False)(False) else: is_helpdesk_staff = check_staff_status(True)(False) helpdesk_staff_member_required = user_passes_test(is_helpdesk_staff) helpdesk_superuser_required = user_passes_test(check_staff_status(False)(True)) def protect_view(view_func): """ Decorator for protecting the views checking user, redirecting to the log-in page if necessary or returning 404 status code """ @wraps(view_func) def _wrapped_view(request, *args, **kwargs): if not request.user.is_authenticated and helpdesk_settings.HELPDESK_REDIRECT_TO_LOGIN_BY_DEFAULT: return redirect('helpdesk:login') elif not request.user.is_authenticated and helpdesk_settings.HELPDESK_ANON_ACCESS_RAISES_404: raise Http404 return view_func(request, *args, **kwargs) return _wrapped_view def staff_member_required(view_func): """ Decorator for staff member the views checking user, redirecting to the log-in page if necessary or returning 403 """ @wraps(view_func) def _wrapped_view(request, *args, **kwargs): if not request.user.is_authenticated and not request.user.is_active: return redirect('helpdesk:login') if not helpdesk_settings.HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE and not request.user.is_staff: raise PermissionDenied() return view_func(request, *args, **kwargs) return _wrapped_view def superuser_required(view_func): """ Decorator for superuser member the views checking user, redirecting to the log-in page if necessary or returning 403 """ @wraps(view_func) def _wrapped_view(request, *args, **kwargs): if not request.user.is_authenticated and not request.user.is_active: return redirect('helpdesk:login') if not request.user.is_superuser: raise PermissionDenied() return view_func(request, *args, **kwargs) return _wrapped_view
{ "repo_name": "rossp/django-helpdesk", "path": "helpdesk/decorators.py", "copies": "3", "size": "3226", "license": "bsd-3-clause", "hash": -5593637674583856000, "line_mean": 34.8444444444, "line_max": 105, "alpha_frac": 0.6946683199, "autogenerated": false, "ratio": 3.8588516746411483, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6053519994541149, "avg_score": null, "num_lines": null }
from functools import wraps from django.core.exceptions import PermissionDenied from django.views.decorators.csrf import csrf_exempt from canvas import util, knobs, browse from canvas.api_decorators import json_service from canvas.exceptions import ServiceError from canvas.metrics import Metrics from canvas.redis_models import RateLimit def short_id(id): return util.base36encode(id) def long_id(short_id): return util.base36decode(short_id) def check_rate_limit(request): return RateLimit('apicall:' + request.META['REMOTE_ADDR'], knobs.PUBLIC_API_RATE_LIMIT).allowed() def public_api_method(f): @csrf_exempt @json_service @wraps(f) def wrapper(*args, **kwargs): try: request = kwargs.get('request') or args[0] if not check_rate_limit(request): Metrics.api_rate_limited.record(request) raise ServiceError("Slow down there, cowboy!") payload = request.JSON ids = payload.get('ids') if ids and len(ids) > knobs.PUBLIC_API_MAX_ITEMS: Metrics.api_items_limited.record(request) raise ServiceError("Max items per query limited to {0}".format(knobs.PUBLIC_API_MAX_ITEMS)) kwargs['payload'] = payload ret = f(*args, **kwargs) Metrics.api_successful_request.record(request) if not ret: Metrics.api_documentation.record(request) return {'documentation': f.__doc__} else: return ret except ServiceError as se: Metrics.api_failed_request.record(request) raise se return wrapper
{ "repo_name": "canvasnetworks/canvas", "path": "website/apps/public_api/util.py", "copies": "1", "size": "1688", "license": "bsd-3-clause", "hash": -2442527364042362400, "line_mean": 29.1428571429, "line_max": 107, "alpha_frac": 0.634478673, "autogenerated": false, "ratio": 4.009501187648456, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5143979860648455, "avg_score": null, "num_lines": null }
from functools import wraps from django.core import mail from django.test.utils import override_settings from mock import MagicMock, patch import requests_mock import pytest from fjord.base.tests import TestCase from fjord.mailinglist.models import MailingList from fjord.translations import gengo_utils from fjord.translations.models import ( GengoHumanTranslator, GengoMachineTranslator, GengoJob, GengoOrder, SuperModel ) from fjord.translations.tests import has_gengo_creds from fjord.translations.utils import translate @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class BaseGengoTestCase(TestCase): def setUp(self): gengo_utils.GENGO_LANGUAGE_CACHE = ( {u'opstat': u'ok', u'response': [ {u'unit_type': u'word', u'localized_name': u'Espa\xf1ol', u'lc': u'es', u'language': u'Spanish (Spain)'}, {u'unit_type': u'word', u'localized_name': u'Deutsch', u'lc': u'de', u'language': u'German'}, {u'unit_type': u'word', u'localized_name': u'English', u'lc': u'en', u'language': u'English'} ]}, (u'es', u'de', u'en') ) gengo_utils.GENGO_LANGUAGE_PAIRS_CACHE = [ (u'es', u'en'), (u'en', u'es-la'), (u'de', u'pl') ] super(BaseGengoTestCase, self).setUp() def account_balance(bal): def account_balance_handler(fun): @wraps(fun) def _account_balance_handler(*args, **kwargs): patcher = patch('fjord.translations.gengo_utils.Gengo') mocker = patcher.start() instance = mocker.return_value instance.getAccountBalance.return_value = { u'opstat': u'ok', u'response': { u'credits': str(bal), u'currency': u'USD' } } try: return fun(*args, **kwargs) finally: patcher.stop() return _account_balance_handler return account_balance_handler def guess_language(lang): def guess_language_handler(fun): @wraps(fun) def _guess_language_handler(*args, **kwargs): ret = { u'text_bytes_found': 10, u'opstat': u'ok', u'is_reliable': True, } if lang == 'un': ret.update({ u'detected_lang_code': u'un', u'details': [], u'detected_lang_name': u'Unknown' }) elif lang == 'es': ret.update({ u'detected_lang_code': u'es', u'details': [ [u'SPANISH', u'es', 62, 46.728971962616825], [u'ITALIAN', u'it', 38, 9.237875288683602] ], u'detected_lang_name': u'SPANISH' }) elif lang == 'el': ret.update({ u'detected_lang_code': u'el', u'details': [ [u'GREEK', u'el', 62, 46.728971962616825], [u'ITALIAN', u'it', 38, 9.237875288683602] ], u'detected_lang_name': u'GREEK' }) elif lang == 'en': ret.update({ u'detected_lang_code': u'en', u'details': [ [u'ENGLISH', u'en', 62, 46.728971962616825], [u'ITALIAN', u'it', 38, 9.237875288683602] ], u'detected_lang_name': u'ENGLISH' }) with requests_mock.Mocker() as m: m.post(gengo_utils.GENGO_DETECT_LANGUAGE_API, json=ret) return fun(*args, **kwargs) return _guess_language_handler return guess_language_handler @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class TestGuessLanguage(BaseGengoTestCase): @guess_language('un') def test_guess_language_throws_error(self): gengo_api = gengo_utils.FjordGengo() with pytest.raises(gengo_utils.GengoUnknownLanguage): gengo_api.guess_language(u'Muy lento') @guess_language('es') def test_guess_language_returns_language(self): gengo_api = gengo_utils.FjordGengo() text = u'Facebook no se puede enlazar con peru' assert gengo_api.guess_language(text) == u'es' def test_guess_language_unintelligible_response(self): # If the gengo api returns some crazy non-json response, make sure # that guess_language should throw a GengoAPIFailure. gengo_api = gengo_utils.FjordGengo() with patch('fjord.translations.gengo_utils.requests') as req_patch: # Create a mock that we can call .post() on and it returns # a response that has a .json() method that throws a # ValueError which is what happens when it's not valid # JSON. post_return = MagicMock() post_return.text = 'abcd' post_return.status_code = 500 post_return.json.side_effect = ValueError('bleh') req_patch.post.return_value = post_return with pytest.raises(gengo_utils.GengoAPIFailure): gengo_api.guess_language(u'whatever text') @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class TestGetLanguages(BaseGengoTestCase): def test_get_languages(self): response = { u'opstat': u'ok', u'response': [ {u'unit_type': u'word', u'localized_name': u'Espa\xf1ol', u'lc': u'es', u'language': u'Spanish (Spain)'} ] } gengo_utils.GENGO_LANGUAGE_CACHE = None with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: instance = GengoMock.return_value instance.getServiceLanguages.return_value = response # Make sure the cache is empty assert gengo_utils.GENGO_LANGUAGE_CACHE is None # Test that we generate a list based on what we think the # response is. gengo_api = gengo_utils.FjordGengo() assert gengo_api.get_languages() == (u'es',) # Test that the new list is cached. assert gengo_utils.GENGO_LANGUAGE_CACHE == (response, (u'es',)) @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class TestGetLanguagePairs(BaseGengoTestCase): def test_get_language_pairs(self): resp = { u'opstat': u'ok', u'response': [ {u'tier': u'standard', u'lc_tgt': u'es-la', u'lc_src': u'en', u'unit_price': u'0.05', u'currency': u'USD'}, {u'tier': u'ultra', u'lc_tgt': u'ar', u'lc_src': u'en', u'unit_price': u'0.15', u'currency': u'USD'}, {u'tier': u'pro', u'lc_tgt': u'ar', u'lc_src': u'en', u'unit_price': u'0.10', u'currency': u'USD'}, {u'tier': u'ultra', u'lc_tgt': u'es', u'lc_src': u'en', u'unit_price': u'0.15', u'currency': u'USD'}, {u'tier': u'standard', u'lc_tgt': u'pl', u'lc_src': u'de', u'unit_price': u'0.05', u'currency': u'USD'} ] } gengo_utils.GENGO_LANGUAGE_PAIRS_CACHE = None with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: instance = GengoMock.return_value instance.getServiceLanguagePairs.return_value = resp # Make sure the cache is empty assert gengo_utils.GENGO_LANGUAGE_PAIRS_CACHE is None # Test that we generate a list based on what we think the # response is. gengo_api = gengo_utils.FjordGengo() assert ( gengo_api.get_language_pairs() == [(u'en', u'es-la'), (u'de', u'pl')] ) # Test that the new list is cached. assert ( gengo_utils.GENGO_LANGUAGE_PAIRS_CACHE == [(u'en', u'es-la'), (u'de', u'pl')] ) @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class TestGetBalance(BaseGengoTestCase): @account_balance(20.0) def test_get_balance(self): gengo_api = gengo_utils.FjordGengo() assert gengo_api.get_balance() == 20.0 @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class TestMachineTranslate(BaseGengoTestCase): @guess_language('es') def test_translate_gengo_machine(self): # Note: This just sets up the GengoJob--it doesn't create any # Gengo human translation jobs. obj = SuperModel( locale='es', desc=u'Facebook no se puede enlazar con peru' ) obj.save() assert obj.trans_desc == u'' translate(obj, 'gengo_machine', 'es', 'desc', 'en', 'trans_desc') # Nothing should be translated assert obj.trans_desc == u'' assert len(GengoJob.objects.all()) == 1 def test_gengo_push_translations(self): """Tests GengoOrders get created""" ght = GengoMachineTranslator() # Create a few jobs covering multiple languages descs = [ ('es', u'Facebook no se puede enlazar con peru'), ('es', u'No es compatible con whatsap'), ('de', u'Absturze und langsam unter Android'), ] for lang, desc in descs: obj = SuperModel(locale=lang, desc=desc) obj.save() job = GengoJob( content_object=obj, tier='machine', src_field='desc', dst_field='trans_desc', src_lang=lang, dst_lang='en' ) job.save() with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: mocker = GengoMock.return_value # FIXME: This returns the same thing both times, but to # make the test "more kosher" we'd have this return two # different order_id values. mocker.postTranslationJobs.return_value = { u'opstat': u'ok', u'response': { u'order_id': u'1337', u'job_count': 2, u'credits_used': u'0.0', u'currency': u'USD' } } ght.push_translations() assert GengoOrder.objects.count() == 2 order_by_id = dict( [(order.id, order) for order in GengoOrder.objects.all()] ) jobs = GengoJob.objects.all() for job in jobs: assert job.order_id in order_by_id @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class TestHumanTranslation(BaseGengoTestCase): @guess_language('es') def test_translate_gengo_human(self): # Note: This just sets up the GengoJob--it doesn't create any # Gengo human translation jobs. obj = SuperModel( locale='es', desc=u'Facebook no se puede enlazar con peru' ) obj.save() assert obj.trans_desc == u'' translate(obj, 'gengo_human', 'es', 'desc', 'en', 'trans_desc') # Nothing should be translated assert obj.trans_desc == u'' assert len(GengoJob.objects.all()) == 1 @guess_language('es') def test_no_translate_if_disabled(self): """No GengoAPI calls if gengosystem switch is disabled""" with patch('fjord.translations.models.waffle') as waffle_mock: waffle_mock.switch_is_active.return_value = False with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: # Note: This just sets up the GengoJob--it doesn't # create any Gengo human translation jobs. obj = SuperModel( locale='es', desc=u'Facebook no se puede enlazar con peru' ) obj.save() assert obj.trans_desc == u'' translate(obj, 'gengo_human', 'es', 'desc', 'en', 'trans_desc') assert obj.trans_desc == u'' # Verify no jobs were created assert len(GengoJob.objects.all()) == 0 # Verify we didn't call the API at all. assert GengoMock.called is False @guess_language('en') def test_translate_gengo_human_english_copy_over(self): obj = SuperModel( locale='es', desc=u'This is English.' ) obj.save() assert obj.trans_desc == u'' translate(obj, 'gengo_human', 'es', 'desc', 'en', 'trans_desc') # If the guesser guesses English, then we just copy it over. assert obj.trans_desc == u'This is English.' @guess_language('el') def test_translate_gengo_human_unsupported_pair(self): obj = SuperModel( locale='el', desc=u'This is really greek.' ) obj.save() assert obj.trans_desc == u'' translate(obj, 'gengo_human', 'el', 'desc', 'en', 'trans_desc') # el -> en is not a supported pair, so it shouldn't get translated. assert obj.trans_desc == u'' @override_settings( ADMINS=(('Jimmy Discotheque', 'jimmy@example.com'),), GENGO_ACCOUNT_BALANCE_THRESHOLD=20.0 ) @account_balance(0.0) def test_push_translations_low_balance_mails_admin(self): """Tests that a low balance sends email and does nothing else""" # Add recipients to mailing list ml = MailingList.objects.get(name='gengo_balance') ml.members = u'foo@example.com' ml.save() # Verify nothing is in the outbox assert len(mail.outbox) == 0 # Call push_translation which should balk and email the # admin ght = GengoHumanTranslator() ght.push_translations() # Verify an email got sent and no jobs were created assert len(mail.outbox) == 1 assert GengoJob.objects.count() == 0 @override_settings(GENGO_ACCOUNT_BALANCE_THRESHOLD=20.0) def test_gengo_push_translations(self): """Tests GengoOrders get created""" ght = GengoHumanTranslator() # Create a few jobs covering multiple languages descs = [ ('es', u'Facebook no se puede enlazar con peru'), ('es', u'No es compatible con whatsap'), ('de', u'Absturze und langsam unter Android'), ] for lang, desc in descs: obj = SuperModel(locale=lang, desc=desc) obj.save() job = GengoJob( content_object=obj, tier='standard', src_field='desc', dst_field='trans_desc', src_lang=lang, dst_lang='en' ) job.save() with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: mocker = GengoMock.return_value mocker.getAccountBalance.return_value = { u'opstat': u'ok', u'response': { u'credits': '400.00', u'currency': u'USD' } } # FIXME: This returns the same thing both times, but to # make the test "more kosher" we'd have this return two # different order_id values. mocker.postTranslationJobs.return_value = { u'opstat': u'ok', u'response': { u'order_id': u'1337', u'job_count': 2, u'credits_used': u'0.35', u'currency': u'USD' } } ght.push_translations() assert GengoOrder.objects.count() == 2 order_by_id = dict( [(order.id, order) for order in GengoOrder.objects.all()] ) jobs = GengoJob.objects.all() for job in jobs: assert job.order_id in order_by_id @override_settings( ADMINS=(('Jimmy Discotheque', 'jimmy@example.com'),), GENGO_ACCOUNT_BALANCE_THRESHOLD=20.0 ) def test_gengo_push_translations_not_enough_balance(self): """Tests enough balance for one order, but not both""" # Add recipients to mailing list ml = MailingList.objects.get(name='gengo_balance') ml.members = u'foo@example.com' ml.save() ght = GengoHumanTranslator() # Create a few jobs covering multiple languages descs = [ ('es', u'Facebook no se puede enlazar con peru'), ('de', u'Absturze und langsam unter Android'), ] for lang, desc in descs: obj = SuperModel(locale=lang, desc=desc) obj.save() job = GengoJob( content_object=obj, tier='standard', src_field='desc', dst_field='trans_desc', src_lang=lang, dst_lang='en' ) job.save() with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: # FIXME: This returns the same thing both times, but to # make the test "more kosher" we'd have this return two # different order_id values. mocker = GengoMock.return_value mocker.getAccountBalance.return_value = { u'opstat': u'ok', u'response': { # Enough for one order, but dips below threshold # for the second one. u'credits': '20.30', u'currency': u'USD' } } mocker.postTranslationJobs.return_value = { u'opstat': u'ok', u'response': { u'order_id': u'1337', u'job_count': 2, u'credits_used': u'0.35', u'currency': u'USD' } } ght.push_translations() assert GengoOrder.objects.count() == 1 # The "it's too low" email only. assert len(mail.outbox) == 1 with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: # FIXME: This returns the same thing both times, but to # make the test "more kosher" we'd have this return two # different order_id values. mocker = GengoMock.return_value mocker.getAccountBalance.return_value = { u'opstat': u'ok', u'response': { # This is the balance after one order. u'credits': '19.95', u'currency': u'USD' } } mocker.postTranslationJobs.return_value = { u'opstat': u'ok', u'response': { u'order_id': u'1337', u'job_count': 2, u'credits_used': u'0.35', u'currency': u'USD' } } # The next time push_translations runs, it shouldn't # create any new jobs, but should send an email. ght.push_translations() assert GengoOrder.objects.count() == 1 # This generates one more email. assert len(mail.outbox) == 2 @override_settings( ADMINS=(('Jimmy Discotheque', 'jimmy@example.com'),), GENGO_ACCOUNT_BALANCE_THRESHOLD=20.0 ) def test_gengo_daily_activities_warning(self): """Tests warning email is sent""" # Add recipients to mailing list ml = MailingList.objects.get(name='gengo_balance') ml.members = u'foo@example.com' ml.save() ght = GengoHumanTranslator() with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: # FIXME: This returns the same thing both times, but to # make the test "more kosher" we'd have this return two # different order_id values. mocker = GengoMock.return_value mocker.getAccountBalance.return_value = { u'opstat': u'ok', u'response': { # Enough for one order, but dips below threshold # for the second one. u'credits': '30.00', u'currency': u'USD' } } ght.run_daily_activities() # The "balance is low warning" email only. assert len(mail.outbox) == 1 @override_settings(GENGO_PUBLIC_KEY='ou812', GENGO_PRIVATE_KEY='ou812') class TestCompletedJobsForOrder(BaseGengoTestCase): def test_no_approved_jobs(self): gtoj_resp = { u'opstat': u'ok', u'response': { u'order': { u'jobs_pending': [u'746197'], u'jobs_revising': [], u'as_group': 0, u'order_id': u'263413', u'jobs_queued': u'0', u'total_credits': u'0.35', u'currency': u'USD', u'total_units': u'7', u'jobs_approved': [], u'jobs_reviewable': [], u'jobs_available': [], u'total_jobs': u'1' } } } with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: instance = GengoMock.return_value instance.getTranslationOrderJobs.return_value = gtoj_resp gengo_api = gengo_utils.FjordGengo() jobs = gengo_api.completed_jobs_for_order('263413') assert jobs == [] def test_approved_jobs(self): gtoj_resp = { u'opstat': u'ok', u'response': { u'order': { u'jobs_pending': [], u'jobs_revising': [], u'as_group': 0, u'order_id': u'263413', u'jobs_queued': u'0', u'total_credits': u'0.35', u'currency': u'USD', u'total_units': u'7', u'jobs_approved': [u'746197'], u'jobs_reviewable': [], u'jobs_available': [], u'total_jobs': u'1' } } } gtjb_resp = { u'opstat': u'ok', u'response': { u'jobs': [ { u'status': u'approved', u'job_id': u'746197', u'currency': u'USD', u'order_id': u'263413', u'body_tgt': u'Facebook can bind with peru', u'body_src': u'Facebook no se puede enlazar con peru', u'credits': u'0.35', u'eta': -1, u'custom_data': u'localhost||GengoJob||7', u'tier': u'standard', u'lc_tgt': u'en', u'lc_src': u'es', u'auto_approve': u'1', u'unit_count': u'7', u'slug': u'Mozilla Input feedback response', u'ctime': 1403296006 } ] } } with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: instance = GengoMock.return_value instance.getTranslationOrderJobs.return_value = gtoj_resp instance.getTranslationJobBatch.return_value = gtjb_resp gengo_api = gengo_utils.FjordGengo() jobs = gengo_api.completed_jobs_for_order('263413') assert( [item['custom_data'] for item in jobs] == [u'localhost||GengoJob||7'] ) def test_pull_translations(self): ght = GengoHumanTranslator() obj = SuperModel(locale='es', desc=u'No es compatible con whatsap') obj.save() gj = GengoJob( content_object=obj, tier='standard', src_field='desc', dst_field='trans_desc', src_lang='es', dst_lang='en' ) gj.save() order = GengoOrder(order_id=u'263413') order.save() gj.assign_to_order(order) gtoj_resp = { u'opstat': u'ok', u'response': { u'order': { u'jobs_pending': [], u'jobs_revising': [], u'as_group': 0, u'order_id': u'263413', u'jobs_queued': u'0', u'total_credits': u'0.35', u'currency': u'USD', u'total_units': u'7', u'jobs_approved': [u'746197'], u'jobs_reviewable': [], u'jobs_available': [], u'total_jobs': u'1' } } } gtjb_resp = { u'opstat': u'ok', u'response': { u'jobs': [ { u'status': u'approved', u'job_id': u'746197', u'currency': u'USD', u'order_id': u'263413', u'body_tgt': u'No es compatible con whatsap', u'body_src': u'Not compatible with whatsap', u'credits': u'0.35', u'eta': -1, u'custom_data': u'localhost||GengoJob||{0}'.format( gj.id), u'tier': u'standard', u'lc_tgt': u'en', u'lc_src': u'es', u'auto_approve': u'1', u'unit_count': u'7', u'slug': u'Mozilla Input feedback response', u'ctime': 1403296006 } ] } } with patch('fjord.translations.gengo_utils.Gengo') as GengoMock: instance = GengoMock.return_value instance.getTranslationOrderJobs.return_value = gtoj_resp instance.getTranslationJobBatch.return_value = gtjb_resp ght.pull_translations() jobs = GengoJob.objects.all() assert len(jobs) == 1 assert jobs[0].status == 'complete' orders = GengoOrder.objects.all() assert len(orders) == 1 assert orders[0].status == 'complete' @pytest.mark.skipif(not has_gengo_creds(), reason='no gengo creds') class TestGengoLive(TestCase): """These are tests that execute calls against the real live Gengo API These tests require GENGO_PUBLIC_KEY and GENGO_PRIVATE_KEY to be valid values in your settings_local.py file. These tests will use the sandbox where possible, but otherwise use the real live Gengo API. Please don't fake the credentials since then you'll just get API authentication errors. These tests should be minimal end-to-end tests. """ def setUp(self): # Wipe out the caches gengo_utils.GENGO_LANGUAGE_CACHE = None gengo_utils.GENGO_LANGUAGE_PAIRS_CACHE = None super(TestGengoLive, self).setUp() def test_get_language(self): text = u'Facebook no se puede enlazar con peru' gengo_api = gengo_utils.FjordGengo() assert gengo_api.guess_language(text) == u'es'
{ "repo_name": "mozilla/fjord", "path": "fjord/translations/tests/test_gengo.py", "copies": "2", "size": "28033", "license": "bsd-3-clause", "hash": 1131356856437822200, "line_mean": 34.5297845374, "line_max": 79, "alpha_frac": 0.5030856491, "autogenerated": false, "ratio": 3.8522742888552974, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 789 }
from functools import wraps from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponseServerError from django.utils.importlib import import_module from social_auth.backends import get_backend from social_auth.utils import setting, log, backend_setting LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL')) PROCESS_EXCEPTIONS = setting('SOCIAL_AUTH_PROCESS_EXCEPTIONS', 'social_auth.utils.log_exceptions_to_messages') def dsa_view(redirect_name=None): """Decorate djangos-social-auth views. Will check and retrieve backend or return HttpResponseServerError if backend is not found. redirect_name parameter is used to build redirect URL used by backend. """ def dec(func): @wraps(func) def wrapper(request, backend, *args, **kwargs): if redirect_name: redirect = reverse(redirect_name, args=(backend,)) else: redirect = request.path backend = get_backend(backend, request, redirect) if not backend: return HttpResponseServerError('Incorrect authentication ' + 'service') RAISE_EXCEPTIONS = backend_setting(backend, 'SOCIAL_AUTH_RAISE_EXCEPTIONS', setting('DEBUG')) try: return func(request, backend, *args, **kwargs) except Exception, e: # some error ocurred if RAISE_EXCEPTIONS: raise log('error', unicode(e), exc_info=True, extra={ 'request': request }) mod, func_name = PROCESS_EXCEPTIONS.rsplit('.', 1) try: process = getattr(import_module(mod), func_name, lambda *args: None) except ImportError: pass else: process(request, backend, e) url = backend_setting(backend, 'SOCIAL_AUTH_BACKEND_ERROR_URL', LOGIN_ERROR_URL) return HttpResponseRedirect(url) return wrapper return dec
{ "repo_name": "kurdd/Oauth", "path": "social_auth/decorators.py", "copies": "1", "size": "2339", "license": "apache-2.0", "hash": 183984425909346780, "line_mean": 37.9833333333, "line_max": 79, "alpha_frac": 0.5472424113, "autogenerated": false, "ratio": 5.129385964912281, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 60 }
from functools import wraps from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from mtvc_client.client import APIClientException def view_exception_handler(view_func): """ A view decorator that undestands MTVC error codes and how to deal with the state changes that they hint at. Eg when a Subscriber's Profile information is incomplete or outdated then the API returns HTTP 401 (Unauthorized) with the following error details in the response: { "error_code": "NO_SUBSCRIBER_PROFILE" } The API client would catch these, raise APIClientException and add the error details to the exception context. """ def _decorator(request, *args, **kwargs): try: return view_func(request, *args, **kwargs) except APIClientException, e: if e.error_code == 'HANDSET_NOT_SUPPORTED': return HttpResponseRedirect(reverse('handset-not-supported')) if e.error_code == 'NO_SUBSCRIBER_PROFILE': return HttpResponseRedirect(reverse('profile')) if e.error_code == 'NO_SUBSCRIPTION': return HttpResponseRedirect(reverse('product')) if e.error_code == 'TRANSACTION_FAILED': return HttpResponseRedirect(reverse('transaction-failed')) raise return wraps(view_func)(_decorator)
{ "repo_name": "praekelt/mtvc-api-client", "path": "mtvc_client/libs/django/decorators.py", "copies": "1", "size": "1422", "license": "mit", "hash": -4816038160615530000, "line_mean": 32.0697674419, "line_max": 77, "alpha_frac": 0.6610407876, "autogenerated": false, "ratio": 4.572347266881029, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5733388054481029, "avg_score": null, "num_lines": null }
from functools import wraps from django.core.urlresolvers import reverse from django.shortcuts import render from django.contrib.auth.views import (password_reset, password_reset_confirm, password_reset_done, password_reset_complete, password_change, password_change_done, ) from django.contrib.auth.models import User from mediaviewer.views.views_utils import setSiteWideContext from mediaviewer.forms import (MVSetPasswordForm, MVPasswordChangeForm, PasswordResetFormWithBCC, ) def reset_confirm(request, uidb64=None, token=None): return password_reset_confirm( request, template_name='mediaviewer/password_reset_confirm.html', uidb64=uidb64, token=token, set_password_form=MVSetPasswordForm, post_reset_redirect=reverse('mediaviewer:password_reset_complete')) def reset(request): if request.method == 'POST' and request.POST['email']: email = request.POST['email'] user = User.objects.filter(email__iexact=email).first() if not user: return render(request, 'mediaviewer/password_reset_no_email.html', {'email': email}) return password_reset( request, template_name='mediaviewer/password_reset_form.html', email_template_name='mediaviewer/password_reset_email.html', subject_template_name='mediaviewer/password_reset_subject.txt', post_reset_redirect=reverse('mediaviewer:password_reset_done'), password_reset_form=PasswordResetFormWithBCC, ) def reset_done(request): return password_reset_done( request, template_name='mediaviewer/password_reset_done.html', ) def reset_complete(request): return password_reset_complete( request, template_name='mediaviewer/password_reset_complete.html', ) def create_new_password(request, uidb64=None, token=None): return password_reset_confirm( request, template_name='mediaviewer/password_create_confirm.html', uidb64=uidb64, token=token, set_password_form=MVSetPasswordForm, post_reset_redirect=reverse('mediaviewer:password_reset_complete')) def change_password(request): context = {'force_change': request.user.settings().force_password_change} setSiteWideContext(context, request) context['active_page'] = 'change_password' return password_change( request, template_name='mediaviewer/change_password.html', post_change_redirect=reverse('mediaviewer:change_password_submit'), password_change_form=MVPasswordChangeForm, extra_context=context, ) def check_force_password_change(func): @wraps(func) def wrap(*args, **kwargs): request = args and args[0] if request and request.user: user = request.user if user.is_authenticated(): settings = user.settings() if settings.force_password_change: return change_password(request) res = func(*args, **kwargs) return res return wrap def change_password_submit(request): context = {} context['active_page'] = 'change_password_submit' setSiteWideContext(context, request) return password_change_done( request, template_name='mediaviewer/change_password_submit.html', extra_context=context, )
{ "repo_name": "kyokley/MediaViewer", "path": "mediaviewer/views/password_reset.py", "copies": "1", "size": "3900", "license": "mit", "hash": -4676138099855332000, "line_mean": 34.7798165138, "line_max": 79, "alpha_frac": 0.5902564103, "autogenerated": false, "ratio": 4.572098475967175, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 109 }
from functools import wraps from django.core.urlresolvers import reverse from django.views.decorators.http import require_POST from django.views.decorators.csrf import csrf_protect from social_auth.backends import get_backend from social_auth.exceptions import WrongBackend from social_auth.utils import setting def dsa_view(redirect_name=None): """Decorate djangos-social-auth views. Will check and retrieve backend or return HttpResponseServerError if backend is not found. redirect_name parameter is used to build redirect URL used by backend. """ def dec(func): @wraps(func) def wrapper(request, backend, *args, **kwargs): if redirect_name: redirect = reverse(redirect_name, args=(backend,)) else: redirect = request.path request.social_auth_backend = get_backend(backend, request, redirect) if request.social_auth_backend is None: raise WrongBackend(backend) return func(request, request.social_auth_backend, *args, **kwargs) return wrapper return dec def disconnect_view(func): @wraps(func) def wrapper(request, *args, **kwargs): return func(request, *args, **kwargs) if setting('SOCIAL_AUTH_FORCE_POST_DISCONNECT'): wrapper = require_POST(csrf_protect(wrapper)) return wrapper
{ "repo_name": "WW-Digital/django-social-auth", "path": "social_auth/decorators.py", "copies": "8", "size": "1438", "license": "bsd-3-clause", "hash": 5095708184951222000, "line_mean": 34.0731707317, "line_max": 78, "alpha_frac": 0.6550764951, "autogenerated": false, "ratio": 4.452012383900929, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 41 }
from functools import wraps from django.db import connection from django.test import TestCase from django.conf import settings from django.contrib.auth.models import User, Group from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.template.loader import Template, Context from actstream.models import Action, Follow, model_stream, user_stream from actstream.actions import follow, unfollow from actstream.exceptions import ModelNotActionable from actstream.signals import action class ActivityTestCase(TestCase): urls = 'actstream.urls' def setUp(self): settings.DEBUG = True self.group = Group.objects.get_or_create(name='CoolGroup')[0] self.user1 = User.objects.get_or_create(username='admin')[0] self.user1.set_password('admin') self.user1.is_superuser = self.user1.is_staff = True self.user1.save() self.user2 = User.objects.get_or_create(username='Two')[0] # User1 joins group self.user1.groups.add(self.group) action.send(self.user1, verb='joined', target=self.group) # User1 follows User2 follow(self.user1, self.user2) # User2 joins group self.user2.groups.add(self.group) action.send(self.user2, verb='joined', target=self.group) # User2 follows group follow(self.user2, self.group) # User1 comments on group # Use a site object here and predict the "__unicode__ method output" action.send(self.user1, verb='commented on', target=self.group) self.comment = Site.objects.create( domain="admin: Sweet Group!...") # Group responds to comment action.send(self.group, verb='responded to', target=self.comment) def test_aauser1(self): self.assertEqual(map(unicode, self.user1.actor_actions.all()), [ u'admin commented on CoolGroup 0 minutes ago', u'admin started following Two 0 minutes ago', u'admin joined CoolGroup 0 minutes ago', ]) def test_user2(self): self.assertEqual(map(unicode, Action.objects.actor(self.user2)), [ u'Two started following CoolGroup 0 minutes ago', u'Two joined CoolGroup 0 minutes ago', ]) def test_group(self): self.assertEqual(map(unicode, Action.objects.actor(self.group)), [u'CoolGroup responded to admin: Sweet Group!... 0 minutes ago']) def test_empty_follow_stream(self): unfollow(self.user1, self.user2) self.assert_(not user_stream(self.user1)) def test_stream(self): self.assertEqual(map(unicode, Action.objects.user(self.user1)), [ u'Two started following CoolGroup 0 minutes ago', u'Two joined CoolGroup 0 minutes ago', ]) self.assertEqual(map(unicode, Action.objects.user(self.user2)), [u'CoolGroup responded to admin: Sweet Group!... 0 minutes ago']) def test_stream_stale_follows(self): """ Action.objects.user() should ignore Follow objects with stale actor references. """ self.user2.delete() self.assert_(not 'Two' in str(Action.objects.user(self.user1))) def test_rss(self): rss = self.client.get('/feed/').content self.assert_(rss.startswith('<?xml version="1.0" encoding="utf-8"?>\n' '<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">')) self.assert_(rss.find('Activity feed for your followed actors') > -1) def test_atom(self): atom = self.client.get('/feed/atom/').content self.assert_(atom.startswith('<?xml version="1.0" encoding="utf-8"?>\n' '<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="%s">' % settings.LANGUAGE_CODE)) self.assert_(atom.find('Activity feed for your followed actors') > -1) def test_action_object(self): action.send(self.user1, verb='created comment', action_object=self.comment, target=self.group) created_action = Action.objects.get(verb='created comment') self.assertEqual(created_action.actor, self.user1) self.assertEqual(created_action.action_object, self.comment) self.assertEqual(created_action.target, self.group) self.assertEqual(unicode(created_action), u'admin created comment admin: Sweet Group!... on CoolGroup 0 ' 'minutes ago') def test_doesnt_generate_duplicate_follow_records(self): g = Group.objects.get_or_create(name='DupGroup')[0] s = User.objects.get_or_create(username='dupuser')[0] f1 = follow(s, g) self.assertTrue(f1 is not None, "Should have received a new follow " "record") self.assertTrue(isinstance(f1, Follow), "Returns a Follow object") self.assertEquals(1, Follow.objects.filter(user=s, object_id=g.pk, content_type=ContentType.objects.get_for_model(g)).count(), "Should only have 1 follow record here") f2 = follow(s, g) self.assertEquals(1, Follow.objects.filter(user=s, object_id=g.pk, content_type=ContentType.objects.get_for_model(g)).count(), "Should still only have 1 follow record here") self.assertTrue(f2 is not None, "Should have received a Follow object") self.assertTrue(isinstance(f2, Follow), "Returns a Follow object") self.assertEquals(f1, f2, "Should have received the same Follow " "object that I first submitted") def test_zzzz_no_orphaned_actions(self): actions = self.user1.actor_actions.count() self.user2.delete() self.assertEqual(actions, self.user1.actor_actions.count() + 1) def test_generic_relation_accessors(self): self.assertEqual((2, 1, 0), ( self.user2.actor_actions.count(), self.user2.target_actions.count(), self.user2.action_object_actions.count())) def test_bad_actionable_model(self): self.assertRaises(ModelNotActionable, follow, self.user1, ContentType.objects.get_for_model(self.user1)) def test_hidden_action(self): action = self.user1.actor_actions.all()[0] action.public = False action.save() self.assert_(not action in self.user1.actor_actions.public()) def _the_zombies_are_coming(self, nums={'human': 10, 'zombie': 2}): from random import choice player_generator = lambda n: [User.objects.create( username='%s%d' % (n, i)) for i in range(nums[n])] humans = player_generator('human') zombies = player_generator('zombie') while len(humans): for z in zombies: if not len(humans): break victim = choice(humans) humans.pop(humans.index(victim)) victim.save() zombies.append(victim) action.send(z, verb='killed', target=victim) self.assertEqual(Action.objects.filter(verb='killed').count(), nums['human']) def query_load(f): @wraps(f) def inner(self): self._the_zombies_are_coming({'human': 10, 'zombie': 1}) ci = len(connection.queries) length, limit = f(self) result = list([map(unicode, (x.actor, x.target, x.action_object)) for x in model_stream(User, _limit=limit)]) self.assert_(len(connection.queries) - ci <= 4, 'Too many queries, got %d expected no more than 4' % len(connection.queries)) self.assertEqual(len(result), length) return result return inner @query_load def test_load(self): return 15, None @query_load def test_after_slice(self): return 10, 10 def test_follow_templates(self): ct = ContentType.objects.get_for_model(User) src = '{% load activity_tags %}{% activity_follow_url user %}{% activity_follow_label user yup nope %}' self.assert_(Template(src).render(Context({ 'user': self.user1 })).endswith('/%s/%s/nope' % (ct.id, self.user1.id))) def test_model_actions_with_kwargs(self): """ Testing the model_actions method of the ActionManager by passing kwargs """ self.assertEqual(map(unicode, model_stream(self.user1, verb='commented on')), [ u'admin commented on CoolGroup 0 minutes ago', ]) def test_user_stream_with_kwargs(self): """ Testing the user method of the ActionManager by passing additional filters in kwargs """ self.assertEqual(map(unicode, Action.objects.user(self.user1, verb='joined')), [ u'Two joined CoolGroup 0 minutes ago', ]) def test_is_following_filter(self): src = '{% load activity_tags %}{% if user|is_following:group %}yup{% endif %}' self.assertEqual(Template(src).render(Context({ 'user': self.user2, 'group': self.group })), u'yup') self.assertEqual(Template(src).render(Context({ 'user': self.user1, 'group': self.group })), u'') def tearDown(self): Action.objects.all().delete() User.objects.all().delete() self.comment.delete() Group.objects.all().delete() Follow.objects.all().delete() class GFKManagerTestCase(TestCase): def setUp(self): self.user_ct = ContentType.objects.get_for_model(User) self.group_ct = ContentType.objects.get_for_model(Group) self.group, _ = Group.objects.get_or_create(name='CoolGroup') self.user1, _ = User.objects.get_or_create(username='admin') self.user2, _ = User.objects.get_or_create(username='Two') self.user3, _ = User.objects.get_or_create(username='Three') self.user4, _ = User.objects.get_or_create(username='Four') Action.objects.get_or_create( actor_content_type=self.user_ct, actor_object_id=self.user1.id, verb='followed', target_content_type=self.user_ct, target_object_id=self.user2.id ) Action.objects.get_or_create( actor_content_type=self.user_ct, actor_object_id=self.user1.id, verb='followed', target_content_type=self.user_ct, target_object_id=self.user3.id ) Action.objects.get_or_create( actor_content_type=self.user_ct, actor_object_id=self.user1.id, verb='followed', target_content_type=self.user_ct, target_object_id=self.user4.id ) Action.objects.get_or_create( actor_content_type=self.user_ct, actor_object_id=self.user1.id, verb='joined', target_content_type=self.group_ct, target_object_id=self.group.id ) def test_fetch_generic_relations(self): # baseline without fetch_generic_relations _actions = Action.objects.filter(actor_content_type=self.user_ct, actor_object_id=self.user1.id) actions = lambda: _actions._clone() num_content_types = len(set(actions().values_list( 'target_content_type_id', flat=True))) n = actions().count() # compare to fetching only 1 generic relation self.assertNumQueries(n + 1, lambda: [a.target for a in actions()]) self.assertNumQueries(num_content_types + 2, lambda: [a.target for a in actions().fetch_generic_relations('target')]) action_targets = [(a.id, a.target) for a in actions()] action_targets_fetch_generic = [(a.id, a.target) for a in actions().fetch_generic_relations('target')] self.assertEqual(action_targets, action_targets_fetch_generic) # compare to fetching all generic relations num_content_types = len(set(sum(actions().values_list( 'actor_content_type_id', 'target_content_type_id'), ()))) self.assertNumQueries(2 * n + 1, lambda: [(a.actor, a.target) for a in actions()]) self.assertNumQueries(num_content_types + 2, lambda: [(a.actor, a.target) for a in actions().fetch_generic_relations()]) action_actor_targets = [(a.id, a.actor, a.target) for a in actions()] action_actor_targets_fetch_generic_all = [ (a.id, a.actor, a.target) for a in actions().fetch_generic_relations()] self.assertEqual(action_actor_targets, action_actor_targets_fetch_generic_all) # fetch only 1 generic relation, but access both gfks self.assertNumQueries(n + num_content_types + 2, lambda: [(a.actor, a.target) for a in actions().fetch_generic_relations('target')]) action_actor_targets_fetch_generic_target = [ (a.id, a.actor, a.target) for a in actions().fetch_generic_relations('target')] self.assertEqual(action_actor_targets, action_actor_targets_fetch_generic_target) def tearDown(self): Action.objects.all().delete() User.objects.all().delete() Group.objects.all().delete()
{ "repo_name": "azizmb/django-activity-stream", "path": "actstream/tests.py", "copies": "1", "size": "13429", "license": "bsd-3-clause", "hash": 8410365819424353000, "line_mean": 39.4487951807, "line_max": 111, "alpha_frac": 0.607565716, "autogenerated": false, "ratio": 3.794574738626731, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4902140454626731, "avg_score": null, "num_lines": null }
from functools import wraps from django.db import models from django.contrib.contenttypes.models import ContentType _get_content_type_for_model_cache = {} def memoize(func, cache, num_args): """ Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be usable as dictionary keys. Only the first num_args are considered when creating the key. """ @wraps(func) def wrapper(*args): mem_args = args[:num_args] if mem_args in cache: return cache[mem_args] result = func(*args) cache[mem_args] = result return result return wrapper def get_content_type_for_model(model): return ContentType.objects.get_for_model(model) get_content_type_for_model = memoize(get_content_type_for_model, _get_content_type_for_model_cache, 1) class QuerysetWithContents(object): """ Queryset wrapper. """ def __init__(self, queryset): self.queryset = queryset def __getattr__(self, name): if name in ('get', 'create', 'get_or_create', 'count', 'in_bulk', 'iterator', 'latest', 'aggregate', 'exists', 'update', 'delete'): return getattr(self.queryset, name) if hasattr(self.queryset, name): attr = getattr(self.queryset, name) if callable(attr): def _wrap(*args, **kwargs): return self.__class__(attr(*args, **kwargs)) return _wrap return attr raise AttributeError(name) def __getitem__(self, key): return self.__class__(self.queryset[key]) def __iter__(self): objects = list(self.queryset) generics = {} for i in objects: generics.setdefault(i.content_type_id, set()).add(i.object_id) content_types = ContentType.objects.in_bulk(generics.keys()) relations = {} for content_type_id, pk_list in generics.items(): model = content_types[content_type_id].model_class() relations[content_type_id] = model.objects.in_bulk(pk_list) for i in objects: setattr(i, '_content_object_cache', relations[i.content_type_id][i.object_id]) return iter(objects) def __len__(self): return len(self.queryset) class RatingsManager(models.Manager): """ Manager used by *Score* and *Vote* models. """ def get_for(self, content_object, key, **kwargs): """ Return the instance related to *content_object* and matching *kwargs*. Return None if a vote is not found. """ content_type = get_content_type_for_model(type(content_object)) try: return self.get(key=key, content_type=content_type, object_id=content_object.pk, **kwargs) except self.model.DoesNotExist: return None def filter_for(self, content_object_or_model, **kwargs): """ Return all the instances related to *content_object_or_model* and matching *kwargs*. The argument *content_object_or_model* can be both a model instance or a model class. """ if isinstance(content_object_or_model, models.base.ModelBase): lookups = {'content_type': get_content_type_for_model( content_object_or_model)} else: lookups = { 'content_type': get_content_type_for_model( type(content_object_or_model)), 'object_id': content_object_or_model.pk, } lookups.update(kwargs) return self.filter(**lookups) def filter_with_contents(self, **kwargs): """ Return all instances retreiving content objects in bulk in order to minimize db queries, e.g. to get all objects voted by a user:: for vote in Vote.objects.filter_with_contents(user=myuser): vote.content_object # this does not hit the db """ if 'content_object' in kwargs: content_object = kwargs.pop('content_object') queryset = self.filter_for(content_object, **kwargs) else: queryset = self.filter(**kwargs) return QuerysetWithContents(queryset)
{ "repo_name": "gradel/django-generic-ratings", "path": "ratings/managers.py", "copies": "3", "size": "4301", "license": "mit", "hash": 5835416001931856000, "line_mean": 33.685483871, "line_max": 81, "alpha_frac": 0.5956754243, "autogenerated": false, "ratio": 4.019626168224299, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00079609156307072, "num_lines": 124 }
from functools import wraps from django.db import ( connections, DEFAULT_DB_ALIAS, DatabaseError, Error, ProgrammingError) from django.utils.decorators import available_attrs class TransactionManagementError(ProgrammingError): """ This exception is thrown when transaction management is used improperly. """ pass def get_connection(using=None): """ Get a database connection by name, or the default database connection if no name is provided. This is a private API. """ if using is None: using = DEFAULT_DB_ALIAS return connections[using] def get_autocommit(using=None): """ Get the autocommit status of the connection. """ return get_connection(using).get_autocommit() def set_autocommit(autocommit, using=None): """ Set the autocommit status of the connection. """ return get_connection(using).set_autocommit(autocommit) def commit(using=None): """ Commits a transaction. """ get_connection(using).commit() def rollback(using=None): """ Rolls back a transaction. """ get_connection(using).rollback() def savepoint(using=None): """ Creates a savepoint (if supported and required by the backend) inside the current transaction. Returns an identifier for the savepoint that will be used for the subsequent rollback or commit. """ return get_connection(using).savepoint() def savepoint_rollback(sid, using=None): """ Rolls back the most recent savepoint (if one exists). Does nothing if savepoints are not supported. """ get_connection(using).savepoint_rollback(sid) def savepoint_commit(sid, using=None): """ Commits the most recent savepoint (if one exists). Does nothing if savepoints are not supported. """ get_connection(using).savepoint_commit(sid) def clean_savepoints(using=None): """ Resets the counter used to generate unique savepoint ids in this thread. """ get_connection(using).clean_savepoints() def get_rollback(using=None): """ Gets the "needs rollback" flag -- for *advanced use* only. """ return get_connection(using).get_rollback() def set_rollback(rollback, using=None): """ Sets or unsets the "needs rollback" flag -- for *advanced use* only. When `rollback` is `True`, it triggers a rollback when exiting the innermost enclosing atomic block that has `savepoint=True` (that's the default). Use this to force a rollback without raising an exception. When `rollback` is `False`, it prevents such a rollback. Use this only after rolling back to a known-good state! Otherwise, you break the atomic block and data corruption may occur. """ return get_connection(using).set_rollback(rollback) ################################# # Decorators / context managers # ################################# class Atomic(object): """ This class guarantees the atomic execution of a given block. An instance can be used either as a decorator or as a context manager. When it's used as a decorator, __call__ wraps the execution of the decorated function in the instance itself, used as a context manager. When it's used as a context manager, __enter__ creates a transaction or a savepoint, depending on whether a transaction is already in progress, and __exit__ commits the transaction or releases the savepoint on normal exit, and rolls back the transaction or to the savepoint on exceptions. It's possible to disable the creation of savepoints if the goal is to ensure that some code runs within a transaction without creating overhead. A stack of savepoints identifiers is maintained as an attribute of the connection. None denotes the absence of a savepoint. This allows reentrancy even if the same AtomicWrapper is reused. For example, it's possible to define `oa = @atomic('other')` and use `@oa` or `with oa:` multiple times. Since database connections are thread-local, this is thread-safe. This is a private API. """ def __init__(self, using, savepoint): self.using = using self.savepoint = savepoint def __enter__(self): connection = get_connection(self.using) if not connection.in_atomic_block: # Reset state when entering an outermost atomic block. connection.commit_on_exit = True connection.needs_rollback = False if not connection.get_autocommit(): # Some database adapters (namely sqlite3) don't handle # transactions and savepoints properly when autocommit is off. # Turning autocommit back on isn't an option; it would trigger # a premature commit. Give up if that happens. if connection.features.autocommits_when_autocommit_is_off: raise TransactionManagementError( "Your database backend doesn't behave properly when " "autocommit is off. Turn it on before using 'atomic'.") # When entering an atomic block with autocommit turned off, # Django should only use savepoints and shouldn't commit. # This requires at least a savepoint for the outermost block. if not self.savepoint: raise TransactionManagementError( "The outermost 'atomic' block cannot use " "savepoint = False when autocommit is off.") # Pretend we're already in an atomic block to bypass the code # that disables autocommit to enter a transaction, and make a # note to deal with this case in __exit__. connection.in_atomic_block = True connection.commit_on_exit = False if connection.in_atomic_block: # We're already in a transaction; create a savepoint, unless we # were told not to or we're already waiting for a rollback. The # second condition avoids creating useless savepoints and prevents # overwriting needs_rollback until the rollback is performed. if self.savepoint and not connection.needs_rollback: sid = connection.savepoint() connection.savepoint_ids.append(sid) else: connection.savepoint_ids.append(None) else: # We aren't in a transaction yet; create one. # The usual way to start a transaction is to turn autocommit off. # However, some database adapters (namely sqlite3) don't handle # transactions and savepoints properly when autocommit is off. # In such cases, start an explicit transaction instead, which has # the side-effect of disabling autocommit. if connection.features.autocommits_when_autocommit_is_off: connection._start_transaction_under_autocommit() connection.autocommit = False else: connection.set_autocommit(False) connection.in_atomic_block = True def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) if connection.savepoint_ids: sid = connection.savepoint_ids.pop() else: # Prematurely unset this flag to allow using commit or rollback. connection.in_atomic_block = False try: if connection.closed_in_transaction: # The database will perform a rollback by itself. # Wait until we exit the outermost block. pass elif exc_type is None and not connection.needs_rollback: if connection.in_atomic_block: # Release savepoint if there is one if sid is not None: try: connection.savepoint_commit(sid) except DatabaseError: try: connection.savepoint_rollback(sid) except Error: # If rolling back to a savepoint fails, mark for # rollback at a higher level and avoid shadowing # the original exception. connection.needs_rollback = True raise else: # Commit transaction try: connection.commit() except DatabaseError: try: connection.rollback() except Error: # An error during rollback means that something # went wrong with the connection. Drop it. connection.close() raise else: # This flag will be set to True again if there isn't a savepoint # allowing to perform the rollback at this level. connection.needs_rollback = False if connection.in_atomic_block: # Roll back to savepoint if there is one, mark for rollback # otherwise. if sid is None: connection.needs_rollback = True else: try: connection.savepoint_rollback(sid) except Error: # If rolling back to a savepoint fails, mark for # rollback at a higher level and avoid shadowing # the original exception. connection.needs_rollback = True else: # Roll back transaction try: connection.rollback() except Error: # An error during rollback means that something # went wrong with the connection. Drop it. connection.close() finally: # Outermost block exit when autocommit was enabled. if not connection.in_atomic_block: if connection.closed_in_transaction: connection.connection = None elif connection.features.autocommits_when_autocommit_is_off: connection.autocommit = True else: connection.set_autocommit(True) # Outermost block exit when autocommit was disabled. elif not connection.savepoint_ids and not connection.commit_on_exit: if connection.closed_in_transaction: connection.connection = None else: connection.in_atomic_block = False def __call__(self, func): @wraps(func, assigned=available_attrs(func)) def inner(*args, **kwargs): with self: return func(*args, **kwargs) return inner def atomic(using=None, savepoint=True): # Bare decorator: @atomic -- although the first argument is called # `using`, it's actually the function being decorated. if callable(using): return Atomic(DEFAULT_DB_ALIAS, savepoint)(using) # Decorator: @atomic(...) or context manager: with atomic(...): ... else: return Atomic(using, savepoint) def _non_atomic_requests(view, using): try: view._non_atomic_requests.add(using) except AttributeError: view._non_atomic_requests = set([using]) return view def non_atomic_requests(using=None): if callable(using): return _non_atomic_requests(using, DEFAULT_DB_ALIAS) else: if using is None: using = DEFAULT_DB_ALIAS return lambda view: _non_atomic_requests(view, using)
{ "repo_name": "aleksandra-tarkowska/django", "path": "django/db/transaction.py", "copies": "10", "size": "12081", "license": "bsd-3-clause", "hash": -557718563460745300, "line_mean": 37.474522293, "line_max": 80, "alpha_frac": 0.5901001573, "autogenerated": false, "ratio": 5.080319596299411, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00015726979633561374, "num_lines": 314 }
from functools import wraps from django.db import ( connections, DEFAULT_DB_ALIAS, DatabaseError, ProgrammingError) from django.utils.decorators import available_attrs class TransactionManagementError(ProgrammingError): """ This exception is thrown when transaction management is used improperly. """ pass def get_connection(using=None): """ Get a database connection by name, or the default database connection if no name is provided. This is a private API. """ if using is None: using = DEFAULT_DB_ALIAS return connections[using] def get_autocommit(using=None): """ Get the autocommit status of the connection. """ return get_connection(using).get_autocommit() def set_autocommit(autocommit, using=None): """ Set the autocommit status of the connection. """ return get_connection(using).set_autocommit(autocommit) def commit(using=None): """ Commits a transaction. """ get_connection(using).commit() def rollback(using=None): """ Rolls back a transaction. """ get_connection(using).rollback() def savepoint(using=None): """ Creates a savepoint (if supported and required by the backend) inside the current transaction. Returns an identifier for the savepoint that will be used for the subsequent rollback or commit. """ return get_connection(using).savepoint() def savepoint_rollback(sid, using=None): """ Rolls back the most recent savepoint (if one exists). Does nothing if savepoints are not supported. """ get_connection(using).savepoint_rollback(sid) def savepoint_commit(sid, using=None): """ Commits the most recent savepoint (if one exists). Does nothing if savepoints are not supported. """ get_connection(using).savepoint_commit(sid) def clean_savepoints(using=None): """ Resets the counter used to generate unique savepoint ids in this thread. """ get_connection(using).clean_savepoints() def get_rollback(using=None): """ Gets the "needs rollback" flag -- for *advanced use* only. """ return get_connection(using).get_rollback() def set_rollback(rollback, using=None): """ Sets or unsets the "needs rollback" flag -- for *advanced use* only. When `rollback` is `True`, it triggers a rollback when exiting the innermost enclosing atomic block that has `savepoint=True` (that's the default). Use this to force a rollback without raising an exception. When `rollback` is `False`, it prevents such a rollback. Use this only after rolling back to a known-good state! Otherwise, you break the atomic block and data corruption may occur. """ return get_connection(using).set_rollback(rollback) ################################# # Decorators / context managers # ################################# class Atomic(object): """ This class guarantees the atomic execution of a given block. An instance can be used either as a decorator or as a context manager. When it's used as a decorator, __call__ wraps the execution of the decorated function in the instance itself, used as a context manager. When it's used as a context manager, __enter__ creates a transaction or a savepoint, depending on whether a transaction is already in progress, and __exit__ commits the transaction or releases the savepoint on normal exit, and rolls back the transaction or to the savepoint on exceptions. It's possible to disable the creation of savepoints if the goal is to ensure that some code runs within a transaction without creating overhead. A stack of savepoints identifiers is maintained as an attribute of the connection. None denotes the absence of a savepoint. This allows reentrancy even if the same AtomicWrapper is reused. For example, it's possible to define `oa = @atomic('other')` and use `@oa` or `with oa:` multiple times. Since database connections are thread-local, this is thread-safe. This is a private API. """ def __init__(self, using, savepoint): self.using = using self.savepoint = savepoint def __enter__(self): connection = get_connection(self.using) if not connection.in_atomic_block: # Reset state when entering an outermost atomic block. connection.commit_on_exit = True connection.needs_rollback = False if not connection.get_autocommit(): # Some database adapters (namely sqlite3) don't handle # transactions and savepoints properly when autocommit is off. # Turning autocommit back on isn't an option; it would trigger # a premature commit. Give up if that happens. if connection.features.autocommits_when_autocommit_is_off: raise TransactionManagementError( "Your database backend doesn't behave properly when " "autocommit is off. Turn it on before using 'atomic'.") # When entering an atomic block with autocommit turned off, # Django should only use savepoints and shouldn't commit. # This requires at least a savepoint for the outermost block. if not self.savepoint: raise TransactionManagementError( "The outermost 'atomic' block cannot use " "savepoint = False when autocommit is off.") # Pretend we're already in an atomic block to bypass the code # that disables autocommit to enter a transaction, and make a # note to deal with this case in __exit__. connection.in_atomic_block = True connection.commit_on_exit = False if connection.in_atomic_block: # We're already in a transaction; create a savepoint, unless we # were told not to or we're already waiting for a rollback. The # second condition avoids creating useless savepoints and prevents # overwriting needs_rollback until the rollback is performed. if self.savepoint and not connection.needs_rollback: sid = connection.savepoint() connection.savepoint_ids.append(sid) else: connection.savepoint_ids.append(None) else: # We aren't in a transaction yet; create one. # The usual way to start a transaction is to turn autocommit off. # However, some database adapters (namely sqlite3) don't handle # transactions and savepoints properly when autocommit is off. # In such cases, start an explicit transaction instead, which has # the side-effect of disabling autocommit. if connection.features.autocommits_when_autocommit_is_off: connection._start_transaction_under_autocommit() connection.autocommit = False else: connection.set_autocommit(False) connection.in_atomic_block = True def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) if connection.savepoint_ids: sid = connection.savepoint_ids.pop() else: # Prematurely unset this flag to allow using commit or rollback. connection.in_atomic_block = False try: if exc_type is None and not connection.needs_rollback: if connection.in_atomic_block: # Release savepoint if there is one if sid is not None: try: connection.savepoint_commit(sid) except DatabaseError: connection.savepoint_rollback(sid) raise else: # Commit transaction try: connection.commit() except DatabaseError: connection.rollback() raise else: # This flag will be set to True again if there isn't a savepoint # allowing to perform the rollback at this level. connection.needs_rollback = False if connection.in_atomic_block: # Roll back to savepoint if there is one, mark for rollback # otherwise. if sid is None: connection.needs_rollback = True else: try: connection.savepoint_rollback(sid) except DatabaseError: # If rolling back to a savepoint fails, mark for # rollback at a higher level and avoid shadowing # the original exception. connection.needs_rollback = True else: # Roll back transaction connection.rollback() finally: # Outermost block exit when autocommit was enabled. if not connection.in_atomic_block: if connection.features.autocommits_when_autocommit_is_off: connection.autocommit = True else: connection.set_autocommit(True) # Outermost block exit when autocommit was disabled. elif not connection.savepoint_ids and not connection.commit_on_exit: connection.in_atomic_block = False def __call__(self, func): @wraps(func, assigned=available_attrs(func)) def inner(*args, **kwargs): with self: return func(*args, **kwargs) return inner def atomic(using=None, savepoint=True): # Bare decorator: @atomic -- although the first argument is called # `using`, it's actually the function being decorated. if callable(using): return Atomic(DEFAULT_DB_ALIAS, savepoint)(using) # Decorator: @atomic(...) or context manager: with atomic(...): ... else: return Atomic(using, savepoint) def _non_atomic_requests(view, using): try: view._non_atomic_requests.add(using) except AttributeError: view._non_atomic_requests = set([using]) return view def non_atomic_requests(using=None): if callable(using): return _non_atomic_requests(using, DEFAULT_DB_ALIAS) else: if using is None: using = DEFAULT_DB_ALIAS return lambda view: _non_atomic_requests(view, using)
{ "repo_name": "simone/django-gb", "path": "django/db/transaction.py", "copies": "1", "size": "10779", "license": "bsd-3-clause", "hash": 2849975187987581400, "line_mean": 36.4270833333, "line_max": 80, "alpha_frac": 0.6096112812, "autogenerated": false, "ratio": 4.904003639672429, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6013614920872429, "avg_score": null, "num_lines": null }
from functools import wraps from django.db import transaction from django.core.files.base import ContentFile from django.core.cache import get_cache from .AgentManager import AgentManager from .ActivityManager import ActivityManager from ..models import Verb, Statement, StatementRef, StatementAttachment, StatementContextActivity, SubStatement, SubStatementContextActivity att_cache = get_cache('attachment_cache') class default_on_exception(object): def __init__(self,default): self.default = default def __call__(self,f): @wraps(f) def closure(obj,*args,**kwargs): try: return f(obj,*args,**kwargs) except: return self.default return closure class StatementManager(): def __init__(self, data, auth, full_stmt={}): # Auth contains define, endpoint, user, and request authority self.data = data self.auth = auth if self.__class__.__name__ == 'StatementManager': # Full statement is for a statement only, same with authority self.data['full_statement'] = full_stmt self.build_authority_object(auth) self.populate() @transaction.commit_on_success def void_statement(self,stmt_id): stmt = Statement.objects.get(statement_id=stmt_id) stmt.voided = True stmt.save() # Create statement ref stmt_ref = StatementRef.objects.create(ref_id=stmt_id) return stmt_ref @transaction.commit_on_success # Save sub to DB def save_substatement_to_db(self): # Pop off any context activities con_act_data = self.data.pop('context_contextActivities',{}) # Try to create SubStatement # Delete objectType since it is not a field in the model del self.data['objectType'] sub = SubStatement.objects.create(**self.data) # Save context activities # Can have multiple groupings for con_act_group in con_act_data.items(): ca = SubStatementContextActivity.objects.create(key=con_act_group[0], substatement=sub) # Incoming contextActivities can either be a list or dict if isinstance(con_act_group[1], list): for con_act in con_act_group[1]: act = ActivityManager(con_act, auth=self.auth['authority'], define=self.auth['define']).Activity ca.context_activity.add(act) else: act = ActivityManager(con_act_group[1], auth=self.auth['authority'], define=self.auth['define']).Activity ca.context_activity.add(act) ca.save() return sub @transaction.commit_on_success # Save statement to DB def save_statement_to_db(self): # Pop off any context activities con_act_data = self.data.pop('context_contextActivities',{}) self.data['user'] = self.auth['user'] # Name of id field in models is statement_id if 'id' in self.data: self.data['statement_id'] = self.data['id'] del self.data['id'] # Try to create statement stmt = Statement.objects.create(**self.data) # Save context activities # Can have multiple groupings for con_act_group in con_act_data.items(): ca = StatementContextActivity.objects.create(key=con_act_group[0], statement=stmt) # Incoming contextActivities can either be a list or dict if isinstance(con_act_group[1], list): for con_act in con_act_group[1]: act = ActivityManager(con_act, auth=self.auth['authority'], define=self.auth['define']).Activity ca.context_activity.add(act) else: act = ActivityManager(con_act_group[1], auth=self.auth['authority'], define=self.auth['define']).Activity ca.context_activity.add(act) ca.save() return stmt def populate_result(self): if 'result' in self.data: result = self.data['result'] for k,v in result.iteritems(): self.data['result_' + k] = v if 'result_score' in self.data: for k,v in self.data['result_score'].iteritems(): self.data['result_score_' + k] = v del self.data['result']['score'] del self.data['result_score'] del self.data['result'] def save_attachment(self, attach): sha2 = attach['sha2'] try: attachment = StatementAttachment.objects.get(sha2=sha2) created = False except StatementAttachment.DoesNotExist: attachment = StatementAttachment.objects.create(**attach) created = True # Since there is a sha2, there must be a payload cached # Decode payload from msg object saved in cache and create ContentFile from raw data msg = att_cache.get(sha2) raw_payload = msg.get_payload(decode=True) try: payload = ContentFile(raw_payload) except: try: payload = ContentFile(raw_payload.read()) except Exception, e: raise e # Save ContentFile payload to attachment model object attachment.payload.save(sha2, payload) return attachment, created @transaction.commit_on_success def populate_attachments(self, attachment_data, attachment_payloads): if attachment_data: # Iterate through each attachment for attach in attachment_data: # Get or create based on sha2 if 'sha2' in attach: attachment, created = self.save_attachment(attach) # If no sha2 there must be a fileUrl which is unique else: try: attachment = StatementAttachment.objects.get(fileUrl=attach['fileUrl']) created = False except Exception: attachment = StatementAttachment.objects.create(**attach) created = True # If have define permission and attachment already has existed if self.auth['define'] and not created: if attachment.display: existing_displays = attachment.display else: existing_displays = {} if attachment.description: existing_descriptions = attachment.description else: existing_descriptions = {} # Save displays if 'display' in attach: attachment.display = dict(existing_displays.items() + attach['display'].items()) if 'description' in attach: attachment.description = dict(existing_descriptions.items() + attach['description'].items()) attachment.save() # Add each attach to the stmt self.model_object.attachments.add(attachment) # Delete everything in cache for this statement if attachment_payloads: att_cache.delete_many(attachment_payloads) self.model_object.save() def populate_context(self): if 'context' in self.data: context = self.data['context'] for k,v in context.iteritems(): self.data['context_' + k] = v if 'context_instructor' in self.data: self.data['context_instructor'] = AgentManager(params=self.data['context_instructor'], define=self.auth['define']).Agent if 'context_team' in self.data: self.data['context_team'] = AgentManager(params=self.data['context_team'], define=self.auth['define']).Agent if 'context_statement' in self.data: self.data['context_statement'] = self.data['context_statement']['id'] del self.data['context'] @transaction.commit_on_success def build_verb_object(self): incoming_verb = self.data['verb'] verb_id = incoming_verb['id'] # Get or create the verb verb_object, created = Verb.objects.get_or_create(verb_id=verb_id) # If existing, get existing keys if not created: if verb_object.display: existing_lang_maps = verb_object.display else: existing_lang_maps = {} else: existing_lang_maps = {} # Save verb displays if 'display' in incoming_verb: verb_object.display = dict(existing_lang_maps.items() + incoming_verb['display'].items()) verb_object.save() self.data['verb'] = verb_object def build_statement_object(self): statement_object_data = self.data['object'] # If not specified, the object is assumed to be an activity if not 'objectType' in statement_object_data: statement_object_data['objectType'] = 'Activity' valid_agent_objects = ['Agent', 'Group'] # Check to see if voiding statement if self.data['verb'].verb_id == 'http://adlnet.gov/expapi/verbs/voided': self.data['object_statementref'] = self.void_statement(statement_object_data['id']) else: # Check objectType, get object based on type if statement_object_data['objectType'] == 'Activity': self.data['object_activity'] = ActivityManager(statement_object_data, auth=self.auth['authority'], define=self.auth['define']).Activity elif statement_object_data['objectType'] in valid_agent_objects: self.data['object_agent'] = AgentManager(params=statement_object_data, define=self.auth['define']).Agent elif statement_object_data['objectType'] == 'SubStatement': self.data['object_substatement'] = SubStatementManager(statement_object_data, self.auth).model_object elif statement_object_data['objectType'] == 'StatementRef': self.data['object_statementref'] = StatementRef.objects.create(ref_id=statement_object_data['id']) del self.data['object'] def build_authority_object(self, auth): # Could still have no authority in stmt if HTTP_AUTH and OAUTH are disabled # Have to set auth in kwarg dict for Agent auth object to be saved in statement # Also have to save auth in full_statement kwargs for when returning exact statements # Set object auth as well for when creating other objects in a substatement if auth['authority']: self.data['authority'] = auth['authority'] self.data['full_statement']['authority'] = auth['authority'].to_dict() # If no auth in request, look in statement else: # If authority is given in statement if 'authority' in self.data: self.data['authority'] = AgentManager(params=self.data['full_statement']['authority']).Agent self.auth['authority'] = self.data['authority'] # TODO - what to do with authority field in statement here? # Since no data about auth sent in with request, have to set it with the authority agent # If authorty is just an agent, won't necessarily be a user and will have define scope # if self.auth['authority'].objectType == 'Group': # self.auth['user'] = self.auth['authority'].get_user_from_oauth_group() # self.auth['define'] = # Empty auth in request or statement else: self.auth['authority'] = None #Once JSON is verified, populate the statement object def populate(self): if self.__class__.__name__ == 'StatementManager': self.data['voided'] = False self.build_verb_object() self.build_statement_object() self.data['actor'] = AgentManager(params=self.data['actor'], define=self.auth['define']).Agent self.populate_context() self.populate_result() attachment_data = self.data.pop('attachments', None) attachment_payloads = self.data.pop('attachment_payloads', None) if self.__class__.__name__ == 'StatementManager': #Save statement/substatement self.model_object = self.save_statement_to_db() else: self.model_object = self.save_substatement_to_db() self.populate_attachments(attachment_data, attachment_payloads) class SubStatementManager(StatementManager): def __init__(self, data, auth): StatementManager.__init__(self, data, auth)
{ "repo_name": "daafgo/Server_LRS", "path": "lrs/objects/StatementManager.py", "copies": "1", "size": "13074", "license": "apache-2.0", "hash": 3550631034251883000, "line_mean": 41.3139158576, "line_max": 141, "alpha_frac": 0.5819183112, "autogenerated": false, "ratio": 4.523875432525951, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.006443637857520605, "num_lines": 309 }
from functools import wraps from django.db.models import Manager from django.db.models.query import QuerySet from django.utils.six import with_metaclass def _make_proxy(name, fn): @wraps(fn) def _proxy(self, *args, **kwargs): qs = self.get_queryset() return getattr(qs, name)(*args, **kwargs) return _proxy class ChainableManagerMetaclass(type(Manager)): """ Metaclass for ChainableManager. """ def __new__(cls, name, bases, attrs): # Construct the class as normal so we can examine it. We will not # actually use this class, unless there is no queryset mixin temp_cls = super(ChainableManagerMetaclass, cls).__new__( cls, name, bases, attrs) # Get the custom QuerySet mixin defined on the class QuerySetMixin = getattr(temp_cls, 'QuerySetMixin', None) # Bail here if there is no QuerySetMixin if QuerySetMixin is None: return temp_cls # Make a custom QuerySet from the mixin ChainableQuerySet = type( 'ChainableQuerySet', (QuerySetMixin, QuerySet), {}) # Make a new class with the mixin in place attrs['ChainableQuerySet'] = ChainableQuerySet bases = bases + (QuerySetMixin, ) cls = super(ChainableManagerMetaclass, cls).__new__( cls, name, bases, attrs) return cls class ChainableManager(with_metaclass(ChainableManagerMetaclass, Manager)): """ A Model Manager that allows chaining custom filters and other methods on both the manager and any querysets produced by it. Add a class named `QuerySetMixin` to the Manager, and define all your custom, chainable methods on this class instead. """ use_for_related_fields = True def get_queryset(self): """ Create a QuerySet for querying this model. Will also have all the chainable methods defined on `QuerySetMixin`. """ return self.ChainableQuerySet(self.model, using=self._db)
{ "repo_name": "timheap/django-chainable-manager", "path": "chainablemanager/manager.py", "copies": "1", "size": "2019", "license": "unlicense", "hash": 1150073468862308700, "line_mean": 30.546875, "line_max": 76, "alpha_frac": 0.6567607727, "autogenerated": false, "ratio": 4.37012987012987, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5526890642829869, "avg_score": null, "num_lines": null }
from functools import wraps from django.db.models import Max from tars.api.utils import str2bool, convert_status from tars.deployment.constants import HALTED, SUCCESS from tars.deployment.models import TarsDeployment, TarsFortDeployment def fort_batch(param='fort_batch'): def decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): queryset = func(*args, **kwargs) request = args[1] fort_batch_id = None if isinstance(args[0], TarsFortDeployment): fort_batch_id = args[0].get_fort_batch().id is_fort_batch = str2bool(request.QUERY_PARAMS.get(param)) if is_fort_batch is not None: if is_fort_batch: queryset = queryset.filter(id=fort_batch_id) else: queryset = queryset.exclude(id=fort_batch_id) return queryset return func_wrapper return decorator def running(param='running'): def decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): queryset = func(*args, **kwargs) request = args[1] is_running = str2bool(request.QUERY_PARAMS.get(param)) if is_running is not None: if is_running: return queryset.exclude(status__in=HALTED) else: return queryset.filter(status__in=HALTED) return queryset return func_wrapper return decorator def last_success_deployment(param='last_success'): def decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): queryset = func(*args, **kwargs) request = args[1] last_success = str2bool(request.QUERY_PARAMS.get(param)) if last_success: queryset = queryset.order_by( '-created_at').filter(status=SUCCESS)[:1] return queryset return func_wrapper return decorator def status(param='status'): def decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): queryset = func(*args, **kwargs) request = args[1] query_param_status = request.QUERY_PARAMS.get(param) if query_param_status is not None: statuses = query_param_status.split(',') queryset = queryset.filter(status__in=statuses) return queryset return func_wrapper return decorator def deployment(param='deployment'): def decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): queryset = func(*args, **kwargs) request = args[1] deployment_id = request.QUERY_PARAMS.get(param) if deployment_id is not None: queryset = queryset.filter( pk=TarsDeployment.objects.get(pk=deployment_id).package_id) return queryset return func_wrapper return decorator def last_success_package(param='last_success'): def decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): queryset = func(*args, **kwargs) request = args[1] last_success = str2bool(request.QUERY_PARAMS.get(param)) if last_success: last_success_ids = queryset.filter(status=SUCCESS).annotate(max_pk=Max('pk')) queryset = queryset.filter(pk__in=last_success_ids.values('max_pk')) return queryset return func_wrapper return decorator def created_from(param='created_from'): def decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): queryset = func(*args, **kwargs) request = args[1] query_param_date = request.QUERY_PARAMS.get(param) if query_param_date is not None: queryset = queryset.filter(created_at__gte=query_param_date) return queryset return func_wrapper return decorator def created_before(param='created_before'): def decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): queryset = func(*args, **kwargs) request = args[1] query_param_date = request.QUERY_PARAMS.get(param) if query_param_date is not None: queryset = queryset.filter(created_at__lt=query_param_date) return queryset return func_wrapper return decorator def ids(param, field): def decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): queryset = func(*args, **kwargs) request = args[1] query_param_id = request.QUERY_PARAMS.get(param) if query_param_id is not None: ids = query_param_id.split(',') kwargs = {'{0}__in'.format(field): ids} queryset = queryset.filter(**kwargs) return queryset return func_wrapper return decorator def app_status(func): @wraps(func) def func_wrapper(*args, **kwargs): queryset = func(*args, **kwargs) request = args[1] query_param_status = request.QUERY_PARAMS.get('status') if query_param_status is not None: from django.db.models import F from tars.deployment.models import Deployment statuses = query_param_status.split(',') statuses = convert_status(statuses) app_ids = [d['group__application_id'] for d in Deployment.objects .annotate(max_deployment=Max('group__deployments__id')) .filter(id=F('max_deployment'), status__in=statuses) .values('group__application_id')] return queryset.filter(id__in=app_ids) return queryset return func_wrapper def log_request(logger=None): def decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): request = args[1] body = request.body if logger is not None: logger.info("url: {}, body: {}".format(request.path, body)) return func(*args, **kwargs) return func_wrapper return decorator def clean_request_data(func): @wraps(func) def func_wrapper(*args, **kwargs): request = args[1] data = request.data request._full_data = {k: v for k, v in data.items() if v is not None} return func(*args, **kwargs) return func_wrapper
{ "repo_name": "ctripcorp/tars", "path": "tars/api/decorators.py", "copies": "1", "size": "6578", "license": "apache-2.0", "hash": 3429720263150346000, "line_mean": 33.0829015544, "line_max": 93, "alpha_frac": 0.5717543326, "autogenerated": false, "ratio": 4.211267605633803, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5283021938233803, "avg_score": null, "num_lines": null }
from functools import wraps from django.forms.models import construct_instance from foundry.forms import JoinForm from neo.models import NeoProfile def patch_join_clean(original_clean): @wraps(original_clean) def clean_join_form(form): cleaned_data = original_clean(form) if not form._errors and not form.non_field_errors(): opts = form._meta # Update the model instance with cleaned_data. member = construct_instance(form, form.instance, opts.fields, opts.exclude) member.set_password(form.cleaned_data["password1"]) member.full_clean() try: form.neoprofile = member.neoprofile except NeoProfile.DoesNotExist: pass return cleaned_data return clean_join_form def patch_join_save(original_save): @wraps(original_save) def save_join_form(form, commit=True): instance = original_save(form, commit) if hasattr(form, 'neoprofile') and form.neoprofile: form.neoprofile.user = instance form.neoprofile.save() return instance return save_join_form JoinForm.clean = patch_join_clean(JoinForm.clean) JoinForm.save = patch_join_save(JoinForm.save) try: from jmbo_registration.forms import JoinForm as RegJoinForm RegJoinForm.clean = patch_join_clean(RegJoinForm.clean) RegJoinForm.save = patch_join_save(RegJoinForm.save) except ImportError: pass
{ "repo_name": "praekelt/jmbo-neo", "path": "neo/forms.py", "copies": "1", "size": "1477", "license": "bsd-3-clause", "hash": 8561914426054323000, "line_mean": 28.54, "line_max": 87, "alpha_frac": 0.6702775897, "autogenerated": false, "ratio": 3.8363636363636364, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00022727272727272727, "num_lines": 50 }