text
stringlengths
0
1.05M
meta
dict
from functools import wraps from collections import Iterable from django.conf import settings from django.shortcuts import render from django.core.exceptions import PermissionDenied from django.utils.decorators import available_attrs from django.utils.encoding import force_str from django.utils.six.moves.urllib.parse import urlparse from django.utils.six import string_types from django.contrib.auth import REDIRECT_FIELD_NAME from django.shortcuts import resolve_url from .models import ACLRule from .settings import (WALIKI_ANONYMOUS_USER_PERMISSIONS, WALIKI_LOGGED_USER_PERMISSIONS, WALIKI_RENDER_403) def check_perms(perms, user, slug, raise_exception=False): """a helper user to check if a user has the permissions for a given slug""" if isinstance(perms, string_types): perms = {perms} else: perms = set(perms) allowed_users = ACLRule.get_users_for(perms, slug) if allowed_users: return user in allowed_users if perms.issubset(set(WALIKI_ANONYMOUS_USER_PERMISSIONS)): return True if user.is_authenticated() and perms.issubset(set(WALIKI_LOGGED_USER_PERMISSIONS)): return True # 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 def permission_required(perms, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME): """ this is analog to django's builtin ``permission_required`` decorator, but improved to check per slug ACLRules and default permissions for anonymous and logged in users if there is a rule affecting a slug, the user needs to be part of the rule's allowed users. If there isn't a matching rule, defaults permissions apply. """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if check_perms(perms, request.user, kwargs['slug'], raise_exception=raise_exception): return view_func(request, *args, **kwargs) if request.user.is_authenticated(): if WALIKI_RENDER_403: return render(request, 'waliki/403.html', kwargs, status=403) else: raise PermissionDenied path = request.build_absolute_uri() # urlparse chokes on lazy objects in Python 3, force to str resolved_login_url = force_str( 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
{ "repo_name": "RobertoMaurizzi/waliki", "path": "waliki/acl.py", "copies": "6", "size": "3426", "license": "bsd-3-clause", "hash": 5922623673360028000, "line_mean": 38.8488372093, "line_max": 111, "alpha_frac": 0.6646234676, "autogenerated": false, "ratio": 4.198529411764706, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7863152879364704, "avg_score": null, "num_lines": null }
from functools import wraps from collections import namedtuple import operator import builtins def get_op(name): name = name.strip('_') op = (getattr(builtins, name, None) or getattr(operator, name, None) or getattr(operator, '__{}__'.format(name), None)) if op is None: raise AttributeError("can't reslove operator {}".format(name)) return op class Op(namedtuple('Op', 'name op reflect n kind format')): def __new__(cls, name, n, format, kind='unknown', reflect=False): op = get_op(name) if reflect: reflect = Reflect(name, n, format, kind, reflect=False) else: reflect = None return super().__new__(cls, name, op, reflect, n, kind, format) @property def method(self): return '__{}__'.format(self.name) @property def defines(self): return self.method def __call__(self, *args): return self.op(*args) def on(self, item): return getattr(item, self.op) def __str__(self): return self.format.replace(' ', '').format(*['_']*self.n) def __repr__(self): return self.format.format(*map('@{}'.format, range(self.n))) class Reflect(Op): @property def defines(self): return '__r{}__'.format(self.name) def __call__(self, a, b): return self.op(b, a) def __repr__(self): return self.format.format(*map('@{}'.format, reversed(range(self.n)))) class Ops(namedtuple('Ops', 'kind ops reflect')): def __new__(cls, kind, ops, reflect=False): ops = tuple(Op(*args, kind=kind, reflect=reflect) for args in ops) return super().__new__(cls, kind, ops, reflect) def __str__(self): return '{}-ops'.format(self.kind) def __repr__(self): return '{}-ops: {}'.format(self.kind, ', '.join(map(str, self.ops))) class _Operators: def __init__(self, name, *defines): self.name = name self.defines = defines self.flat = [op for ops in self.defines for op in ops.ops] self.by_name = {op.name: op for op in self} self.by_kind = {ops.kind: ops for ops in self.defines} def __iter__(self): return iter(self.flat) def __getitem__(self, name): return self.by_name[name.strip('__')] def __getattr__(self, kind): return type(self)('{}.{}'.format(self.name, kind), self.by_kind[kind]) def __str__(self): return '{}.{}'.format(__name__, self.name) def __repr__(self): return '{} ({})'.format(self, ', '.join(map(str, self.defines))) operators = _Operators( 'operators', Ops('compare', (('lt', 2, '{} < {}'), ('le', 2, '{} <= {}'), ('eq', 2, '{} == {}'), ('ge', 2, '{} >= {}'), ('gt', 2, '{} > {}'))), Ops('object', (('hash', 1, 'hash({})'), ('bool', 1, 'bool({})'))), Ops('container', (('len', 1, 'len({})'), ('length_hint', 1, 'length_hint({})'), ('getitem', 2, '{}[{}]'), ('setitem', 3, '{}[{}] = {}'), ('delitem', 2, 'del {}[{}]'), ('iter', 1, 'iter({})'), ('reversed', 1, 'reversed({})'), ('contains', 2, '{1} in {0}'))), Ops('numeric', (('add', 2, '{} + {}'), ('sub', 2, '{} - {}'), ('mul', 2, '{} * {}'), ('truediv', 2, '{} / {}'), ('floordiv', 2, '{} // {}'), ('mod', 2, '{} % {}'), ('divmod', 2, 'divmod({}, {})'), ('pow', 2, '{} ** {}'), ('lshift', 2, '{} << {}'), ('rshift', 2, '{} >> {}'), ('and', 2, '{} & {}'), ('xor', 2, '{} ^ {}'), ('or', 2, '{} | {}')), True), Ops('unary', (('neg', 1, '-{}'), ('pos', 1, '+{}'), ('abs', 1, 'abs({})'), ('invert', 1, '~{}'))), Ops('conversion', (('complex', 1, 'complex({})'), ('int', 1, 'int({})'), ('float', 1, 'float({})'), ('round', 1, 'round({})'))), Ops('indexing', (('index', 1, 'index({})'),)), ) def iter_ops(cls, reflect=True): """ iterator over all operators of a class """ for op in operators: if hasattr(cls, op.defines): yield op if op.reflect: ref = op.reflect if (reflect and hasattr(cls, op.defines) or hasattr(cls, ref.defines)): yield ref def opsame(op): """ checks for type mismatch between first and second argument""" @wraps(op) def checked(self, other): if not isinstance(other, type(self)): return NotImplemented return op(self, other) return checked def operate(by=None, reflect=True): """ define a class with operators that access an attribute to work on """ if isinstance(by, type): return autowraped_ops(by) else: def annotate(cls): return autowraped_ops(cls, by=by, reflect=reflect) return annotate def autowraped_ops(cls, by=None, reflect=True): """ Creates a dynamic mixin with operator forwarding to wraped instances Parameters ---------- cls : type class that the object by : str instance attribute that is used to constructed wrapped objects reflect : bool also create reflected operator wrappings Return ------ mixin : type dynamic mixin class with operator definitions """ def wrapping(op): call = op.__call__ if by: def wrap(self, *args): return call(getattr(self, by), *args) else: def wrap(self, *args): return call(cls(self), *args) return wraps(getattr(cls, op.method))(wrap) ops = {op.defines: wrapping(op) for op in iter_ops(cls, reflect=reflect) if op.name not in ['hash', 'eq']} ops.update({'__def__': cls}) return type('Fwd' + cls.__name__, (object,), ops) def bind(cls): def annotate(f): f.__bind__ = cls return f return annotate
{ "repo_name": "wabu/pyadds", "path": "pyadds/meta/ops.py", "copies": "1", "size": "6492", "license": "mit", "hash": -3219237649090863000, "line_mean": 29.3364485981, "line_max": 78, "alpha_frac": 0.46025878, "autogenerated": false, "ratio": 3.9132007233273054, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48734595033273054, "avg_score": null, "num_lines": null }
from functools import wraps from collections import OrderedDict def _embed_ipython_shell(namespace={}, banner=''): """Start an IPython Shell""" try: from IPython.terminal.embed import InteractiveShellEmbed from IPython.terminal.ipapp import load_default_config except ImportError: from IPython.frontend.terminal.embed import InteractiveShellEmbed from IPython.frontend.terminal.ipapp import load_default_config @wraps(_embed_ipython_shell) def wrapper(namespace=namespace, banner=''): config = load_default_config() # Always use .instace() to ensure _instance propagation to all parents # this is needed for <TAB> completion works well for new imports # and clear the instance to always have the fresh env # on repeated breaks like with inspect_response() InteractiveShellEmbed.clear_instance() shell = InteractiveShellEmbed.instance( banner1=banner, user_ns=namespace, config=config) shell() return wrapper def _embed_bpython_shell(namespace={}, banner=''): """Start a bpython shell""" import bpython @wraps(_embed_bpython_shell) def wrapper(namespace=namespace, banner=''): bpython.embed(locals_=namespace, banner=banner) return wrapper def _embed_ptpython_shell(namespace={}, banner=''): """Start a ptpython shell""" import ptpython.repl @wraps(_embed_ptpython_shell) def wrapper(namespace=namespace, banner=''): print(banner) ptpython.repl.embed(locals=namespace) return wrapper def _embed_standard_shell(namespace={}, banner=''): """Start a standard python shell""" import code try: # readline module is only available on unix systems import readline except ImportError: pass else: import rlcompleter readline.parse_and_bind("tab:complete") @wraps(_embed_standard_shell) def wrapper(namespace=namespace, banner=''): code.interact(banner=banner, local=namespace) return wrapper DEFAULT_PYTHON_SHELLS = OrderedDict([ ('ptpython', _embed_ptpython_shell), ('ipython', _embed_ipython_shell), ('bpython', _embed_bpython_shell), ('python', _embed_standard_shell), ]) def get_shell_embed_func(shells=None, known_shells=None): """Return the first acceptable shell-embed function from a given list of shell names. """ if shells is None: # list, preference order of shells shells = DEFAULT_PYTHON_SHELLS.keys() if known_shells is None: # available embeddable shells known_shells = DEFAULT_PYTHON_SHELLS.copy() for shell in shells: if shell in known_shells: try: # function test: run all setup code (imports), # but dont fall into the shell return known_shells[shell]() except ImportError: continue def start_python_console(namespace=None, banner='', shells=None): """Start Python console bound to the given namespace. Readline support and tab completion will be used on Unix, if available. """ if namespace is None: namespace = {} try: shell = get_shell_embed_func(shells) if shell is not None: shell(namespace=namespace, banner=banner) except SystemExit: # raised when using exit() in python code.interact pass
{ "repo_name": "ArturGaspar/scrapy", "path": "scrapy/utils/console.py", "copies": "12", "size": "3403", "license": "bsd-3-clause", "hash": 9118952297907458000, "line_mean": 35.2021276596, "line_max": 78, "alpha_frac": 0.6620628857, "autogenerated": false, "ratio": 4.3295165394402035, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
from functools import wraps from collections import OrderedDict from flask import abort, request, g from flask_login import current_user from flask_httpauth import HTTPTokenAuth from werkzeug.datastructures import Authorization def permission_required(permission): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): if not current_user.can(permission): abort(403) return func(*args, **kwargs) return wrapper return decorator def admin_required(func): return permission_required('ADMINISTER')(func) def extend_attribute(obj, new_attr, attr): def _extend(item): setattr(item, new_attr, getattr(item, attr)) return item if isinstance(obj, list): return list(map(_extend, obj)) else: return _extend(obj) class HTTPJWTAuth(HTTPTokenAuth): def login_with_token(self): auth = None if 'Authorization' in request.headers: try: auth_type, token = request.headers['Authorization'].split( None, 1) auth = Authorization(auth_type, {'token': token}) except ValueError: # The Authorization header is either empty or has no token pass if auth is not None and auth.type.lower() != self.scheme.lower(): auth = None if request.method != 'OPTIONS': # pragma: no cover password = None if not self.authenticate(auth, password): # Clear TCP receive buffer of any pending data request.data return self.auth_error_callback() def permission_required(self, permission): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): self.login_with_token() if not g.user.can(permission): abort(403) return func(*args, **kwargs) return wrapper return decorator def admin_required(self, func): return self.permission_required('ADMINISTER')(func) class ArchiveDict(object): def __init__(self, archives): self.dict = OrderedDict(archives) self.keys = list(self.dict.keys()) def prev(self, key): try: index = self.keys.index(key) return self.keys[index+1] except (ValueError, IndexError): pass def next(self, key): try: index = self.keys.index(key) if index: return self.keys[index-1] except ValueError: pass def __getitem__(self, key): return self.dict[key]
{ "repo_name": "piratecb/up1and", "path": "app/utils.py", "copies": "1", "size": "2703", "license": "mit", "hash": -8703073494815136000, "line_mean": 28.3804347826, "line_max": 74, "alpha_frac": 0.5763965964, "autogenerated": false, "ratio": 4.512520868113523, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0006708407871198569, "num_lines": 92 }
from functools import wraps from collections import OrderedDict from graphql.core import graphql from graphql.core.type import ( GraphQLSchema as _GraphQLSchema ) from graphql.core.execution.executor import Executor from graphql.core.execution.middlewares.sync import SynchronousExecutionMiddleware from graphql.core.execution import ExecutionResult, execute from graphql.core.language.parser import parse from graphql.core.language.source import Source from graphql.core.validation import validate from graphql.core.utils.introspection_query import introspection_query from graphene import signals from graphene.utils import cached_property class GraphQLSchema(_GraphQLSchema): def __init__(self, schema, *args, **kwargs): self.graphene_schema = schema super(GraphQLSchema, self).__init__(*args, **kwargs) class Schema(object): _query = None _executor = None def __init__(self, query=None, mutation=None, name='Schema', executor=None): self._internal_types = {} self.mutation = mutation self.query = query self.name = name self.executor = executor signals.init_schema.send(self) def __repr__(self): return '<Schema: %s (%s)>' % (str(self.name), hash(self)) @property def query(self): return self._query @query.setter def query(self, query): self._query = query self._query_type = query and query.internal_type(self) @property def executor(self): if not self._executor: self.executor = Executor([SynchronousExecutionMiddleware()], map_type=OrderedDict) return self._executor @executor.setter def executor(self, value): self._executor = value @cached_property def schema(self): if not self._query_type: raise Exception('You have to define a base query type') return GraphQLSchema(self, query=self._query_type, mutation=self.mutation) def associate_internal_type(self, internal_type, object_type): self._internal_types[internal_type.name] = object_type def register(self, object_type): self._internal_types[object_type._meta.type_name] = object_type return object_type def get_type(self, type_name): if type_name not in self._internal_types: raise Exception('Type %s not found in %r' % (type_name, self)) return self._internal_types[type_name] @property def types(self): return self._internal_types def execute(self, request='', root=None, variables=None, operation_name=None, **kwargs): root = root or object() return self.executor.execute( self.schema, request=request, root=self.query(root), args=variables, operation_name=operation_name, **kwargs ) def introspect(self): return self.execute(introspection_query).data def register_internal_type(fun): @wraps(fun) def wrapper(cls, schema): internal_type = fun(cls, schema) if isinstance(schema, Schema): schema.associate_internal_type(internal_type, cls) return internal_type return wrapper
{ "repo_name": "jhgg/graphene", "path": "graphene/core/schema.py", "copies": "1", "size": "3229", "license": "mit", "hash": -8622858864251346000, "line_mean": 29.1775700935, "line_max": 94, "alpha_frac": 0.6615051099, "autogenerated": false, "ratio": 4.082174462705436, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5243679572605435, "avg_score": null, "num_lines": null }
from functools import wraps from collections import OrderedDict def _embed_ipython_shell(namespace={}, banner=''): """Start an IPython Shell""" try: from IPython.terminal.embed import InteractiveShellEmbed from IPython.terminal.ipapp import load_default_config except ImportError: from IPython.frontend.terminal.embed import InteractiveShellEmbed from IPython.frontend.terminal.ipapp import load_default_config @wraps(_embed_ipython_shell) def wrapper(namespace=namespace, banner=''): config = load_default_config() # Always use .instace() to ensure _instance propagation to all parents # this is needed for <TAB> completion works well for new imports # and clear the instance to always have the fresh env # on repeated breaks like with inspect_response() InteractiveShellEmbed.clear_instance() shell = InteractiveShellEmbed.instance( banner1=banner, user_ns=namespace, config=config) shell() return wrapper def _embed_bpython_shell(namespace={}, banner=''): """Start a bpython shell""" import bpython @wraps(_embed_bpython_shell) def wrapper(namespace=namespace, banner=''): bpython.embed(locals_=namespace, banner=banner) return wrapper def _embed_ptpython_shell(namespace={}, banner=''): """Start a ptpython shell""" import ptpython.repl @wraps(_embed_ptpython_shell) def wrapper(namespace=namespace, banner=''): print(banner) ptpython.repl.embed(locals=namespace) return wrapper def _embed_standard_shell(namespace={}, banner=''): """Start a standard python shell""" import code try: # readline module is only available on unix systems import readline except ImportError: pass else: import rlcompleter # noqa: F401 readline.parse_and_bind("tab:complete") @wraps(_embed_standard_shell) def wrapper(namespace=namespace, banner=''): code.interact(banner=banner, local=namespace) return wrapper DEFAULT_PYTHON_SHELLS = OrderedDict([ ('ptpython', _embed_ptpython_shell), ('ipython', _embed_ipython_shell), ('bpython', _embed_bpython_shell), ('python', _embed_standard_shell), ]) def get_shell_embed_func(shells=None, known_shells=None): """Return the first acceptable shell-embed function from a given list of shell names. """ if shells is None: # list, preference order of shells shells = DEFAULT_PYTHON_SHELLS.keys() if known_shells is None: # available embeddable shells known_shells = DEFAULT_PYTHON_SHELLS.copy() for shell in shells: if shell in known_shells: try: # function test: run all setup code (imports), # but dont fall into the shell return known_shells[shell]() except ImportError: continue def start_python_console(namespace=None, banner='', shells=None): """Start Python console bound to the given namespace. Readline support and tab completion will be used on Unix, if available. """ if namespace is None: namespace = {} try: shell = get_shell_embed_func(shells) if shell is not None: shell(namespace=namespace, banner=banner) except SystemExit: # raised when using exit() in python code.interact pass
{ "repo_name": "eLRuLL/scrapy", "path": "scrapy/utils/console.py", "copies": "1", "size": "3428", "license": "bsd-3-clause", "hash": 7900198662405950000, "line_mean": 32.9405940594, "line_max": 78, "alpha_frac": 0.6595682614, "autogenerated": false, "ratio": 4.306532663316583, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0008824411852950001, "num_lines": 101 }
from functools import wraps from ..common import custom_widget_wrapper from wtforms.widgets.core import HTMLString __all__ = ['bootstrap_styled'] def render_field_errors(field): """ Render field errors as html. """ if field.errors: html = """<p class="help-block">Error: {errors}</p>""".format( errors='. '.join(field.errors) ) return HTMLString(html) return None def render_field_description(field): """ Render a field description as HTML. """ if hasattr(field, 'description') and field.description != '': html = """<p class="help-block">{field.description}</p>""" html = html.format( field=field ) return HTMLString(html) return '' def form_group_wrapped(f): """ Wrap a field within a bootstrap form-group. Additionally sets has-error This decorator sets has-error if the field has any errors. """ @wraps(f) def wrapped(self, field, *args, **kwargs): classes = ['form-group'] if field.errors: classes.append('has-error') html = """<div class="{classes}">{rendered_field}</div>""".format( classes=' '.join(classes), rendered_field=f(self, field, *args, **kwargs) ) return HTMLString(html) return wrapped def meta_wrapped(f): """ Add a field label, errors, and a description (if it exists) to a field. """ @wraps(f) def wrapped(self, field, *args, **kwargs): html = "{label}{errors}{original}<small>{description}</small>".format( label=field.label(class_='control-label'), original=f(self, field, *args, **kwargs), errors=render_field_errors(field) or '', description=render_field_description(field) ) return HTMLString(html) return wrapped def bootstrap_styled(cls=None, add_meta=True, form_group=True, input_class='form-control'): """ Wrap a widget to conform with Bootstrap's html control design. Args: input_class: Class to give to the rendered <input> control. add_meta: bool: """ def real_decorator(cls): class NewClass(cls): pass NewClass.__name__ = cls.__name__ NewClass = custom_widget_wrapper(NewClass) _call = NewClass.__call__ def call(*args, **kwargs): if input_class: kwargs.setdefault('class', input_class) return _call(*args, **kwargs) if add_meta: call = meta_wrapped(call) if form_group: call = form_group_wrapped(call) NewClass.__call__ = call return NewClass if cls: # Allow calling decorator(cls) instead of decorator()(cls) rv = real_decorator(cls) return rv return real_decorator
{ "repo_name": "nickw444/wtforms-webwidgets", "path": "wtforms_webwidgets/bootstrap/util.py", "copies": "1", "size": "2852", "license": "mit", "hash": 6232959969700215000, "line_mean": 25.9056603774, "line_max": 78, "alpha_frac": 0.5827489481, "autogenerated": false, "ratio": 4.022566995768688, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5105315943868688, "avg_score": null, "num_lines": null }
from functools import wraps from ConfigService import Config import daemon from lockfile import FileLock def Daemonize(function): ''' Decorates a function that will be ran as a well behaved Unix daemon. ''' @wraps(function) def wrapper(*args, **kwargs): #======================================================================= # This is interesting. # # What is happening here is that the python-daemon module is asking itself # if we are daemonizing something from a "superserver". How the author chose # to determine this was to see if main's stdin is actually a socket. However, the # multiprocess.Process that is calling this code has already taken it upon # itself to close the stdin file, resulting in an I/O error. # # Really, the answer to this question is "no". So here we are, just saying "no". #======================================================================= if hasattr(daemon.daemon, 'is_process_started_by_superserver'): daemon.daemon.is_process_started_by_superserver = lambda: False #=================================================================== #=================================================================== context = daemon.DaemonContext( detach_process=True, working_directory = '/', uid = Config.getUID(), gid = Config.getGID(), pidfile=FileLock(Config.getPIDFile()) ) with context: try: function(*args, **kwargs) except Exception as e: print (e) return wrapper
{ "repo_name": "christopher-henderson/Tweeter", "path": "src/Tools/daemonize.py", "copies": "1", "size": "1695", "license": "mit", "hash": 8797733344663607000, "line_mean": 42.4871794872, "line_max": 89, "alpha_frac": 0.5020648968, "autogenerated": false, "ratio": 5.247678018575852, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.015839485738211933, "num_lines": 39 }
from functools import wraps from contextlib import AbstractContextManager, ExitStack, contextmanager from abc import ABC, abstractmethod from enum import Enum from operator import * from funklib.core.prelude import flip, const from functools import wraps,partial from collections import namedtuple def from_context(cm): """Extract the value produced by a context manager""" with cm as x: return x class MatchFailure(Exception): """Exception raised in case of a pattern match failure""" def __init__(self, matched=None, pattern=None): self.matched = matched self.pattern = pattern def __repr__(self): return "MatchFailure(pattern={}, matched={})".format( self.matched, self.pattern ) def __str__(self): return "MatchFailure: value {!r} does not match pattern {!r}".format(self.matched, self.pattern) class MatchSuccess(Exception): """Exception raised in case of match success""" pass class matchstatus(Enum): pending = 0 failed = 1 succeeded = 2 class match: def __init__(self, value): self._value = value # self._tried = 0 # self._actives = [] # self._status = matchstatus.pending @property def value(self): return self._value @contextmanager def subcases(self): try: with match(self._value) as m: yield m raise MatchSuccess except MatchFailure: return @contextmanager def case(self, pattern=None): """Creates a case context. If an extractor is provided, binds an extractor context to the 'as' clause. Silence MatchFailure exceptions and raise MatchSuccess if all goes okay.""" try: if pattern: yield pattern.of(self._value) else: yield None raise MatchSuccess except MatchFailure: return @contextmanager def ignore(self): """Equivalent to self.case(ignore), introduce a context without binding anything.""" yield None raise MatchSuccess def __enter__(self): return self def __exit__(self, t, ex, tb): if t is MatchSuccess: return True if ex is None: raise MatchFailure("No pattern matches value {!r}".format(self._value)) def __repr__(self): return "Match({})".format(self._value) class Pattern(ABC): def __call__(self, x): return self.__match__(x) @abstractmethod def __match__(self, x): """Try and match its argument and return a value or a tuple of values, or raise MatchFailure""" pass @contextmanager def of(self, x): yield self.__match__(x) class ClassPattern(ABC): @classmethod @abstractmethod def __match__(cls, x): """Try and match its argument and return a value or a tuple of values, or raise MatchFailure""" pass @classmethod @contextmanager def of(cls, x): yield cls.__match__(x) class StaticPattern(ABC): @staticmethod @abstractmethod def __match__(x): """Try and match its argument and return a value or a tuple of values, or raise MatchFailure""" pass @classmethod @contextmanager def of(cls, x): yield cls.__match__(x) @contextmanager def match_except(*exceptions): """Context manager that transforms specified exceptions in MatchFailure exceptions :param exceptions: exceptions to be transformed into a match failure""" try: yield None except exceptions as ex: raise MatchFailure() from ex class Key(Pattern): """Pattern that match a gettable object that contains a given key, exposing the value associated with that key""" def __init__(self, key): self.key = key @match_except(KeyError, TypeError) def __match__(self, x): return x[self.key] class Keys(Pattern): """Pattern that match a mapping which includes certain keys""" def __init__(self, keys): self.keys = keys @match_except(KeyError, TypeError) def __match__(self, x): return tuple(x[k] for k in self.keys) class Attr(Pattern): """Pattern that match an object which has a specified attribute, exposing that attribute""" def __init__(self, attribute): self.attribute = attribute @match_except(AttributeError) def __match__(self, x): return getattr(x, self.attribute) class Attrs(Pattern): """Pattern that match an object which has all specified attributes, exposing all those attributes""" def __init__(self, *attributes): self.attributes = attributes @match_except(AttributeError) def __match__(self, x): return tuple(getattr(x, attr) for attr in self.attributes) class Any(Pattern): """Pattern that match any value""" def __match__(self, x): return x def pattern(Pattern): def __init__(self, func): self.pattern = func def __match__(self, x): return self.pattern(x) _ignore = const(None) ignore = pattern(_ignore) def ismatch(value, pattern): """Evaluate a match pattern, return True if match else False""" try: pattern.__match__(value) return True except MatchFailure: return False class Symbol(str): pass _NoDefault = Symbol("NoDefault") def getmatch(value, pattern, default=_NoDefault): try: return pattern.__match__(value) except MatchFailure: if default is not _NoDefault: return default else: raise def predicate_method(f): @wraps(f) def wrapper(self, arg): if f(self, arg): return arg else: raise MatchFailure() return wrapper def predicate_classmethod(f): @wraps(f) def wrapper(cls, arg): if f(cls, arg): return arg else: raise MatchFailure return wrapper def predicate_function(f): @wraps(f) def wrapper(arg): if f(arg): return arg else: raise MatchFailure return wrapper class Predicate(Pattern): """Base class for 'predicate' objects implementing the match protocol""" def __init__(self, predicate): self.predicate = predicate def __match__(self, x): if self.predicate(x): return x else: raise MatchFailure(matched=x, pattern=self) def __repr__(self): return "Predicate({})".format(self.predicate) class Is(Predicate): def __init__(self, identity): self.identity = identity self.predicate = partial(is_, identity) def __match__(self, x): if x is self.identity: return x else: raise MatchFailure(matched=x, pattern=self) class Equal(Predicate): def __init__(self, value): self.equal = value self.predicate = partial(eq, value) @predicate_method def __match__(self, x): if x == self.equal: return x else: raise MatchFailure(matched=x, pattern=self) class In(Predicate): def __init__(self, iterable): self.container = iterable self.predicate = partial(contains, iterable) @predicate_method def __match__(self, x): if x in self.container: return x else: raise MatchFailure(matched=x, pattern=self) class Compose(Pattern): """ Pattern combiner that applies patterns in chain, matching the composition of all patterns, and failing if any of them fails """ def __init__(self, *patterns): self.patterns = patterns def __match__(self, x): m = x for p in reversed(self.patterns): m = getmatch(m, p) return m class AsPredicate(Pattern): def __init__(self, pattern): self.pattern = pattern def __match__(self, x): if ismatch(x, self.pattern): return x else: raise MatchFailure(matched=x, pattern=self.pattern) WithMatch = namedtuple("WithMatch", ("value", "match")) class With(Pattern): def __init__(self, pattern): self.pattern = pattern def __match__(self, x): m = getmatch(x, self.pattern) return WithMatch(value=x, match=m) class All(Predicate): """Predicate combiner that match a value which is matched by all subpredicates""" def __init__(self, *predicates): def _all(x): return all(map(partial(ismatch, x), predicates)) self.predicates = predicates self.predicate = _all @predicate_method def __match__(self, x): return all(map(partial(ismatch, x), self.predicates)) class AnyOf(Predicate): """Predicates combiner that match a value which is matched by any(at least one) subpredicates""" def __init__(self, *predicates): def _any(x): return any(map(partial(ismatch, x), predicates)) self.predicates = predicates self.predicate = _any @predicate_method def __match__(self, x): return any(map(partial(ismatch, x), self.predicates)) class OneOf(Predicate): """Predicates combiner that match a value which is matched by one and only one subpredicate""" def __init__(self, *predicates): def _oneof(x): return len(tuple(map(partial(ismatch, x), self.predicates))) == 1 self.predicates = predicates self.predicate = _oneof @predicate_method def __match__(self, x): return len(tuple((partial(ismatch, x), self.predicates))) == 1 class Type(Predicate): """Predicate that match a value by its type""" def __init__(self, t): self.type = t self.predicate = partial(flip(isinstance), t) @predicate_method def __match__(self, x): return isinstance(x, self.type) class Many(Pattern): def __init__(self, patterns): self.patterns = patterns def __match__(self, x): return tuple(map(partial(getmatch, x), self.patterns))
{ "repo_name": "DrPyser/python-multimethods", "path": "patmat.py", "copies": "1", "size": "10346", "license": "mit", "hash": 146172242588500960, "line_mean": 23.8105515588, "line_max": 104, "alpha_frac": 0.5920162382, "autogenerated": false, "ratio": 4.262875978574372, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5354892216774372, "avg_score": null, "num_lines": null }
from functools import wraps from contextlib import contextmanager from threading import local thread_local = local() from surround.django.logging import setupModuleLogger setupModuleLogger(globals()) class LocalCacheBackend(object): def __init__(self): self.backend = {} def get(self, key): return self.backend.get(key, None) def set(self, key, value): self.backend[key] = value def cached(func): name = func.__module__ + '.' + func.__name__ def _get_key(args, kwargs): return name + ':a:' + ','.join(map(str, args)) + ':kw:' + ','.join(['%s=%s' % (k, v) for k, v in kwargs.items()]) @wraps(func) def wrapped(*args, **kwargs): current = get_active() if current is None: return func(*args, **kwargs) key = _get_key(args, kwargs) cached_value = current.get(key) if cached_value is not None: return cached_value result = func(*args, **kwargs) current.set(key, result) return result def _force(value, args=[], kwargs={}): key = _get_key(args, kwargs) current = get_active() if current is None: raise Exception('forcing context cache value outside context') current.set(key, value) wrapped._force = _force wrapped._get_key = _get_key return wrapped @contextmanager def make_active(current): old = getattr(thread_local, 'backend', None) thread_local.backend = current try: yield current finally: if old is not None: thread_local.backend = old else: del thread_local.backend def wrap_with_current(func): current = get_active() @wraps(func) def wrapped(*args, **kwargs): with make_active(current): return func(*args, **kwargs) return wrapped def wrap_with_activate(func): @wraps(func) def wrapped(*args, **kwargs): with activate(): return func(*args, **kwargs) return wrapped def wrap_with_assure_active(func): @wraps(func) def wrapped(*args, **kwargs): with assure_active(): return func(*args, **kwargs) return wrapped def activate(): return make_active(LocalCacheBackend()) @contextmanager def assure_active(): current = get_active() if current is not None: yield else: with activate(): yield def deactivate(): return make_active(None) def get_active(): return getattr(thread_local, 'backend', None)
{ "repo_name": "sniegu/django-surround", "path": "surround/django/context_cache.py", "copies": "1", "size": "2555", "license": "mit", "hash": 8704961173664516000, "line_mean": 20.4705882353, "line_max": 121, "alpha_frac": 0.5941291585, "autogenerated": false, "ratio": 3.936825885978428, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.997924792761943, "avg_score": 0.010341423371799456, "num_lines": 119 }
from functools import wraps from contextlib import contextmanager import time, json, sys, random import cv2 from unqlite import UnQLite import tensorflow as tf import numpy as np from ai import detection, preprocessing, deepq import i2c from controls import CursesControl, RemoteControlServer from camera import PiVideoStream from livestream import LiveStreamClient db = UnQLite('records.udb') @contextmanager def timeit_context(name): startTime = time.time() yield elapsedTime = time.time() - startTime print('[{}] finished in {} ms'.format(name, int(elapsedTime * 1000))) class Driver(object): def __init__(self): super(Driver, self).__init__() def foo(): pass class AutonomousDriver(object): """docstring for AutonomousDriver""" def __init__(self): super(AutonomousDriver, self).__init__() self.LAST_OBSERV = [] self.LAST_ACTION = None def start(self): session = tf.InteractiveSession() size_ = 10 brain = deepq.MLP([size_,], [10, 10], [tf.tanh, tf.identity]) optimizer = tf.train.RMSPropOptimizer(learning_rate = 0.01, decay=0.9) self.current_controller = deepq.DiscreteDeepQ(size_, 10, brain, optimizer, session, discount_rate=0.9, exploration_period=100, max_experience=10000, store_every_nth=1, train_every_nth=4, target_network_update_rate=0.1) session.run(tf.initialize_all_variables()) session.run(self.current_controller.target_network_update) return self def _train(self, reward, new_obs): self.current_controller.store(self.LAST_OBSERV, self.LAST_ACTION, reward, new_obs) if random.random() < 0.25: self.current_controller.training_step() def learn(self): """Learn on a given dataset""" # db.all() experiences = json.loads('[' + db['env'][1:].replace('\'', '\"') + ']') experiences = filter(lambda x: x['output']['command'] == 'auto_logic_based', experiences) for i, exp in enumerate(experiences): path = 'records/' + exp['img'] + '.jpg' img = cv2.imread(path) mask = preprocessing.get_mask_color(img, color='red') reward = preprocessing.get_reward(mask) points = np.array(list(preprocessing.get_path_points(mask))) if len(self.LAST_OBSERV) > 1: self._train(reward, points) print('learning', i, '/', len(experiences)) self.LAST_OBSERV = points self.LAST_ACTION = 4 if experiences[0]['output']['turn'] == -5 else 5 def load(): """Load a model""" pass def action(self, command, img): mask = preprocessing.get_mask_color(img, color='red') reward = preprocessing.get_reward(mask) points = np.array(list(preprocessing.get_path_points(mask))) action = self.current_controller.action(points) if len(self.LAST_OBSERV) > 1: self._train(reward, points) self.LAST_OBSERV = points self.LAST_ACTION = action if action < 5: action = (9 - action) action = - int(action*1.5 - 5) else: action = int(action*1.5 - 5) return 5, action # speed, turn class LogicBasedDriver(object): def __init__(self): super(LogicBasedDriver, self).__init__() def action(self, command, img, *args, **kwargs): speed, turn = 0, 0 with timeit_context('Detections'): detections = detection.detections(img, detect=['stop']) mask = preprocessing.get_mask_color(img, color='red') mask = preprocessing.get_size_mask(mask, 0.5, 1) # get the bottom half cx, cy, surface_size = preprocessing.get_mask_info(mask) screen_size = mask.shape[1]/2 speed = 30 K = 0.6 turn = K * speed * (cx - screen_size)/screen_size """ if 'stop' in detections: i2c.move_backward() """ return speed, int(turn) class HumanDriver(object): def __init__(self): super(HumanDriver, self).__init__() def action(self, command, *args): speed, turn = 0, 0 if command == 'left': turn = -20 elif command == 'right': turn = 20 elif command == 'up': speed = 20 elif command == 'down': speed = -20 return speed, turn def get_sensors(func): @wraps(func) def wrapper(self, *args, **kwargs): with timeit_context('Image'): img = self.camera.read() with timeit_context('Sensors'): sensors = i2c.get_sonars_input() return func(self, img=img, sensors=sensors, *args, **kwargs) return wrapper def save_state(self, **states): # write the image filename = str(states['time']).replace('.', '_') # states['output'] = list(states['output']) with timeit_context('Img Write'): cv2.imwrite('./records/' + filename + '.jpg', states['img']) states['img'] = filename with timeit_context('Data Write'): # if len(db.get('env', '')) > 0: db.append('env', ',') db.append('env', states) if random.random() < 0.05: db.commit() def record(func): @wraps(func) def wrapper(self, *args, **kwargs): output = func(self, *args, **kwargs) with timeit_context('Save states'): save_state(self, output=output, time=time.time(), *args, **kwargs) return output return wrapper class Car(object): """docstring for Car""" def __init__(self, control): super(Car, self).__init__() self.live_stream = None self.camera = PiVideoStream(resolution=(320, 240), framerate=16) self.control = control self.driver = HumanDriver() def exit(self): self.camera.stop() self.control.stop() if self.live_stream: self.live_stream.stop() print('exit') def start(self): i2c.setup(mode_motors=3) self.control.start() self.camera.start() @get_sensors @record # inputs (camera + sensor) and output def drive(self, img, sensors): if self.live_stream: self.live_stream.send(frame=img, sensors=sensors) command = self.control.read() if command == 'quit': self.exit() sys.exit(1) elif command == 'stream': try: if not self.live_stream: self.live_stream = LiveStreamClient().start() except Exception as e: print('live_stream', e) elif command == 'stop': i2c.stop() if command == 'auto_logic_based': if not isinstance(self.driver, LogicBasedDriver): self.driver = LogicBasedDriver() elif command == 'auto_neural_network': if not isinstance(self.driver, AutonomousDriver): ai = AutonomousDriver().start() ai.learn() self.driver = ai # utonomousDriver().start() else: self.driver = HumanDriver() pass # human control speed, turn = self.driver.action(command, img) i2c.set_speed(speed) i2c.set_turn(turn) # CONSTRAINTS for sonar in i2c.SONARS: if sonar == i2c.I2C_SONAR_2: continue if sensors.get(str(sonar), [30])[0] < 20: i2c.stop() return {'command': command, 'speed': speed, 'turn': turn} def main(): if len(sys.argv) > 1 and sys.argv[1] == '--remote': control = RemoteControl() else: control = CursesControl() car = Car(control=control) car.start() while True: car.drive() if __name__ == '__main__': main()
{ "repo_name": "SelfDrivUTT/selfdrivutt", "path": "robot/raspberry/drive.py", "copies": "1", "size": "7983", "license": "mit", "hash": 2828849764217935400, "line_mean": 30.1875, "line_max": 108, "alpha_frac": 0.5584366779, "autogenerated": false, "ratio": 3.8141423793597706, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48725790572597705, "avg_score": null, "num_lines": null }
from functools import wraps from contextlib import contextmanager from barin.util import _Reified def listen(obj, hook, callback): obj.__barin__.hooks[hook].append(callback) def listens_for(obj, hook=None): def decorator(func): if hook is None: hook_name = func.__name__ else: hook_name = hook listen(obj, hook_name, func) return func return decorator def with_hooks(hook=None, before=True, after=True): def decorator(func): if hook is None: hook_name = func.__name__ else: hook_name = hook @wraps(func) def wrapper(self, *args, **kwargs): with hook_context(self.hooks, hook_name, self, args, kwargs): return func(self, *args, **kwargs) return wrapper return decorator @contextmanager def hook_context(hooks, hook, self, args, kwargs, before=True, after=True): if before: _call_hooks(hooks.get('before_' + hook, []), self, args, kwargs) yield if after: _call_hooks(hooks.get('after_' + hook, []), self, args, kwargs) def _call_hooks(funcs, self, args, kwargs): for func in funcs: func(self, *args, **kwargs)
{ "repo_name": "rick446/barin", "path": "barin/event.py", "copies": "1", "size": "1227", "license": "apache-2.0", "hash": 939871083603558400, "line_mean": 25.1063829787, "line_max": 75, "alpha_frac": 0.597392013, "autogenerated": false, "ratio": 3.7408536585365852, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4838245671536585, "avg_score": null, "num_lines": null }
from functools import wraps from contextlib import contextmanager def proxy_factory(type, underlying_getter): """ Create a callable that creates proxies. This function (#1) will return another function (#2) that can be called with a name. The return value will be a proxy function (#3) that simply delegates to the underlying object. The underlying object itself is found through calling underlying_getter, and the type of this object must be given (which is used to look up whether it's a function or property. """ def proxy_function(name): proxy_to = getattr(type, name) if isinstance(proxy_to, property): def fget(self, *args, **kwargs): underlying = underlying_getter(self) return proxy_to.fget(underlying, *args, **kwargs) if proxy_to.fset is not None: def fset(self, *args, **kwargs): underlying = underlying_getter(self) return proxy_to.fset(underlying, *args, **kwargs) else: fset = None if proxy_to.fdel is not None: def fdel(self, *args, **kwargs): underlying = underlying_getter(self) return proxy_to.fdel(underlying, *args, **kwargs) else: fdel = None the_proxy = property(fget=fget, fset=fset, fdel=fdel, doc=proxy_to.__doc__) else: @wraps(proxy_to) def the_proxy(self, *args, **kwargs): underlying = underlying_getter(self) return proxy_to(underlying, *args, **kwargs) return the_proxy return proxy_function @contextmanager def patch(obj, attr, value): hasOld = False old = None if hasattr(obj, attr): old = getattr(obj, attr) hasOld = True setattr(obj, attr, value) yield if hasOld: setattr(obj, attr, old) else: delattr(obj, attr)
{ "repo_name": "andrew-d/Specter.py", "path": "specter/util.py", "copies": "1", "size": "2031", "license": "mit", "hash": -5144849310272282000, "line_mean": 31.2380952381, "line_max": 75, "alpha_frac": 0.5711472181, "autogenerated": false, "ratio": 4.2489539748953975, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 63 }
from functools import wraps from copy import copy from collections import OrderedDict from ..commands import InterfaceObj from ..core.objects.memory import StackObj, RegObj def BeforeParse(f): @wraps(f) def wrapper(inst, *args, **kwargs): # noinspection PyProtectedMember if inst._parsed is True: raise Exception("Only before Parse") # TODO: Create Environment Exception return f(inst, *args, **kwargs) return wrapper def BeforePrecompile(f): @wraps(f) def wrapper(inst, *args, **kwargs): # noinspection PyProtectedMember if inst._precompiled is True: raise Exception("Only before Precompile") # TODO: Create Environment Exception return f(inst, *args, **kwargs) return wrapper def BeforeCompile(f): @wraps(f) def wrapper(inst, *args, **kwargs): # noinspection PyProtectedMember if inst._compiled is True: raise Exception("Only before Compile") # TODO: Create Environment Exception return f(inst, *args, **kwargs) return wrapper class Environment: """ Environment Object used for the MurPy operations. """ def __init__(self): """Create a new Environment indipendent instance.""" self._code = None self.PseudoCode = [] # Contenitore delle operazioni da eseguire self._StackColl = OrderedDict() # Container degli StackObj self._RegistryColl = OrderedDict() # Container dei RegObj self.RoutineDict = {} self._parsed = False self._precompiled = False self._compiled = False @property def StackColl(self): return copy(self._StackColl) @property def RegistryColl(self): return copy(self._RegistryColl) @BeforePrecompile def ExistStackName(self, name): return name in self._StackColl.keys() @BeforePrecompile def RequestStackName(self, name): if self.ExistStackName(name): raise Exception("Required insertion of duplicated Stack name!") else: tmp = StackObj(name) self._StackColl[name] = tmp return tmp @BeforeCompile def RequestRegistry(self): """ Request a new registry slot. :return: the new Reg Object. """ regkey = len(self._RegistryColl) item = RegObj(regkey) self._RegistryColl[regkey] = item return item @BeforeCompile def RequestRegistryArray(self, size): # TODO: Documentazione # Di per se richieste successive hanno regkey successive ed adiacenti # PER ORA... assert size > 0 output = tuple([self.RequestRegistry() for _ in range(size)]) return output @BeforeCompile def getStackObjByName(self, name): if not self.ExistStackName(name): raise Exception("Variabile non definita") return self._StackColl[name] @BeforeCompile def getStackPosition(self, stackobjs): """ Given a StackObject return the Tape Position of the associated registry. :param stackobjs: Identity Object for the stack variable or a list of it. :return: Tape Position of the registry or a tuple of it. """ names = list(self._StackColl) work = str(stackobjs.name) return int(names.index(work)) @BeforeCompile def getRegPosition(self, regobjs): """ Given a RegObject return the Tape Position of the associated registry. :param regobjs: Identity Object for the registry. :return: Tape Position of the registry. """ keys = list(self._RegistryColl.keys()) work = int(regobjs.regkey) return len(self._StackColl) + keys.index(work) @staticmethod def MoveP(start: int, end: int): """ Autogenerate the BFCode for the pointer moving from a position to another. :param start: Position of start. :param end: Position of end. :return: The BFCode of the movement. """ if start > end: return "<" * (start - end) else: return ">" * (end - start) @staticmethod def ClearRegList(startpos: int, reglist: tuple): code = "" pointer = int(startpos) for reg in reglist: code += Environment.MoveP(pointer, reg) + "[-]" pointer = reg return code, pointer def clear(self): self.__init__() @BeforeParse def addRoutine(self, func): """ Introduce in the Routine Dictionary the specified routine. :param func: The Routine to put in the Routine Dictionary. """ # Per essere certi che l'input sia una funzione assert callable(func) assert hasattr(func, "__name__") self.RoutineDict[func.__name__] = func @BeforeParse def Parse(self): """ Do on the data previously provided the Parsing process. After that all the PseudoCode will be generated into the Environment. """ # MODELLO PER UNA SOLA FUNZIONE MAIN # TODO: Estendere il parser in modo dinamica a casi multifunzione self.RoutineDict["main"]() self.PseudoCode = InterfaceObj.BUFFER.GetMainBuffer() self._parsed = True @BeforePrecompile def Precompile(self): """ Do the Precompilation process. After that all the Operation in the PseudoCode will have already executed his PreCompile method on the Environment for tuning it. """ for op in self.PseudoCode: op.PreCompile(self) self._precompiled = True @BeforeCompile def Compile(self): """ Do the Compilation process. After the Precompilation and the tuning of the Environment with this method the Environment will compute the final BFCode. :return: The BFCode compiled. """ self._code = "" pointer = 0 for op in self.PseudoCode: code, newpointer = op.GetCode(self, pointer) self._code += code pointer = newpointer self._compiled = True return self._code @property def BFCode(self): """Get the BFCode if already generated.""" return self._code del BeforeParse, BeforePrecompile, BeforeCompile
{ "repo_name": "eisterman/MurPy", "path": "murpy/compiletools/__init__.py", "copies": "1", "size": "6394", "license": "mit", "hash": 4076014219317205000, "line_mean": 29.5933014354, "line_max": 91, "alpha_frac": 0.6127619643, "autogenerated": false, "ratio": 4.279785809906292, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00027818456512296405, "num_lines": 209 }
from functools import wraps from copy import deepcopy import hashlib import sys import inspect import operator from ..workflow import (from_call, get_workflow) from .maybe import (maybe) from ..lib import (decorator) from noodles.config import config def scheduled_function(f, hints=None): """The Noodles schedule function decorator. The decorated function will return a workflow in stead of being applied immediately. This workflow can then be passed to a job scheduler in order to be run on any architecture supporting the current python environment.""" if hints is None: hints = {} if 'version' not in hints: try: source_bytes = inspect.getsource(f).encode() except Exception: pass else: m = hashlib.md5() m.update(source_bytes) hints['version'] = m.hexdigest() @wraps(f) def wrapped(*args, **kwargs): return PromisedObject(from_call( f, args, kwargs, deepcopy(hints), call_by_value=config['call_by_value'])) # add *(scheduled)* to the beginning of the docstring. if hasattr(wrapped, '__doc__') and wrapped.__doc__ is not None: wrapped.__doc__ = "*(scheduled)* " + wrapped.__doc__ return wrapped @decorator def schedule(f, **hints): """Decorator; schedule calls to function `f` into a workflow, in stead of running them at once. The decorated function returns a :class:`PromisedObject`.""" return scheduled_function(f, hints=hints) def has_scheduled_methods(cls): """Decorator; use this on a class for which some methods have been decorated with :func:`schedule` or :func:`schedule_hint`. Those methods are then tagged with the attribute `__member_of__`, so that we may serialise and retrieve the correct method. This should be considered a patch to a flaw in the Python object model.""" for member in cls.__dict__.values(): if hasattr(member, '__wrapped__'): member.__wrapped__.__member_of__ = cls return cls def schedule_hint(**hints): """Decorator; same as :func:`schedule`, with added hints. These hints can be anything.""" return lambda f: scheduled_function(f, hints) @schedule @maybe def getitem(obj, ix): return obj[ix] @schedule def setitem(obj, attr, value): try: obj = deepcopy(obj) obj[attr] = value except TypeError as err: tb = sys.exc_info()[2] from pprint import PrettyPrinter pp = PrettyPrinter() obj_repr = "<" + obj.__class__.__name__ + ">: " \ + pp.pformat(obj.__dict__) msg = "In `_setattr` we deepcopy the object *during runtime*. " \ "If you're sure that what you're doing is safe, you can " \ " overload `__deepcopy__` to get more efficient code. " \ "However, something went " \ "wrong here: \n" + err.args[0] + '\n' + obj_repr raise TypeError(msg).with_traceback(tb) return obj @schedule @maybe def _getattr(obj, attr): return getattr(obj, attr) @schedule def _setattr(obj, attr, value): try: obj = deepcopy(obj) obj.__setattr__(attr, value) except TypeError as err: tb = sys.exc_info()[2] from pprint import PrettyPrinter pp = PrettyPrinter() obj_repr = "<" + obj.__class__.__name__ + ">: " \ + pp.pformat(obj.__dict__) msg = "In `_setattr` we deepcopy the object *during runtime*. " \ "If you're sure that what you're doing is safe, you can " \ " overload `__deepcopy__` to get more efficient code. " \ "However, something went " \ "wrong here: \n" + err.args[0] + '\n' + obj_repr raise TypeError(msg).with_traceback(tb) return obj @schedule @maybe def _do_call(obj, *args, **kwargs): return obj(*args, **kwargs) def update_hints(obj, data): """Update the hints on the root-node of a workflow. Usually, schedule hints are fixed per function. Sometimes a user may want to set hints manually on a specific promised object. :func:`update_hints` uses the `update` method on the hints dictionary with `data` as its argument. :param obj: a :py:class:`PromisedObject`. :param data: a :py:class:`dict` containing additional hints. The hints are modified, in place, on the node. All workflows that contain the node are affected.""" root = obj._workflow.root obj._workflow.nodes[root].hints.update(data) def result(obj): """Results are stored on the nodes in the workflow at run time. This function can be used to get at a result of a node in a workflow after run time. This is not a recommended way of getting at results, but can help with debugging.""" return obj.__result__() class PromisedObject(object): """ Wraps a :py:class:`Workflow`. The workflow represents the future promise of a Python object. By wrapping the workflow, we can mock the behaviour of this future object and schedule methods that were called by the user as if nothing weird is going on. """ def __init__(self, workflow): self._workflow = workflow def __call__(self, *args, **kwargs): return _do_call(self._workflow, *args, **kwargs) def __getattr__(self, attr): return _getattr(self, attr) def __setattr__(self, attr, value): if attr[0] == '_': self.__dict__[attr] = value return self._workflow = get_workflow( _setattr(self, attr, value)) def __result__(self): return self._workflow.root_node.result # predicates def __lt__(self, other): return schedule(operator.lt)(self, other) def __gt__(self, other): return schedule(operator.gt)(self, other) def __eq__(self, other): return schedule(operator.eq)(self, other) def __ne__(self, other): return schedule(operator.ne)(self, other) def __ge__(self, other): return schedule(operator.ge)(self, other) def __le__(self, other): return schedule(operator.le)(self, other) # boolean operations def __bool__(self): return schedule(operator.truth)(self) # numerical operations def __abs__(self): return schedule(operator.abs)(self) def __sub__(self, other): return schedule(operator.sub)(self, other) def __add__(self, other): return schedule(operator.add)(self, other) def __mul__(self, other): return schedule(operator.mul)(self, other) def __rmul__(self, other): return schedule(operator.mul)(other, self) def __truediv__(self, other): return schedule(operator.truediv)(self, other) def __floordiv__(self, other): return schedule(operator.floordiv)(self, other) def __mod__(self, other): return schedule(operator.mod)(self, other) def __pow__(self, other): return schedule(operator.pow)(self, other) def __pos__(self): return schedule(operator.pos)(self) def __neg__(self): return schedule(operator.neg)(self) def __matmul__(self, other): return schedule(operator.matmul)(self, other) def __index__(self): return schedule(operator.index)(self) # bit operations def __inv__(self): return schedule(operator.inv)(self) def __lshift__(self, n): return schedule(operator.lshift)(self, n) def __rshift__(self, n): return schedule(operator.rshift)(self, n) def __and__(self, other): return schedule(operator.and_)(self, other) def __or__(self, other): return schedule(operator.or_)(self, other) def __xor__(self, other): return schedule(operator.xor)(self, other) # container operations def __contains__(self, item): return schedule(operator.contains)(self, item) def __getitem__(self, name): return getitem(self, name) def __setitem__(self, attr, value): self._workflow = get_workflow( setitem(self, attr, value)) def __iter__(self): raise TypeError( "You have tried to iterate (or unpack) a PromisedObject. " "There is currently no possible way to learn the " "length of a PromisedObject so, sadly, this is not " "implemented. You may use the `noodles.unpack` function " "to unpack a promised tuple.") def __deepcopy__(self, _): raise TypeError( "A PromisedObject cannot be deepcopied. Most probably, you " "have a promise stored in another object, which you passed to " "a scheduled function. To transform an object with nested " "promises to a top-level promise, apply the ``lift`` function.")
{ "repo_name": "NLeSC/noodles", "path": "noodles/interface/decorator.py", "copies": "1", "size": "8862", "license": "apache-2.0", "hash": -3147033515550601700, "line_mean": 29.3493150685, "line_max": 78, "alpha_frac": 0.6131798691, "autogenerated": false, "ratio": 4.050274223034735, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 292 }
from functools import wraps from copy import deepcopy # On every entry to the function the tree grows downward. # At any time there exist a pointer to a current tree node. # When a node is first created it becomes the current node. # Once a function returns the current node changes. # The next current node is the parent of the current current node. # If the current node has no parent, the tree is complete tree = None _done = False class ExecTree: def __init__(self,parent=None,args=None,kwargs=None,ret=None): if args is None: self.args = [] else: self.args = args if kwargs is None: self.kwargs = {} else: self.kwargs = kwargs self.ret = ret self.childs = [] self.parent = parent # TODO add options to specify which kwargs # are to be recorded def exectree(indices=None): global tree def dec(func): @wraps(func) def wrapper(*args, **kwargs): init() push() ret = func(*args, **kwargs) args = list(args) select_args(args, indices) tree.args = deepcopy(args) tree.kwargs = deepcopy(kwargs) tree.ret = deepcopy(ret) pop() return ret return wrapper return dec def push(): global tree frame = ExecTree(parent=tree) if tree is None: tree = frame else: tree.childs.append(frame) tree = frame def pop(): global tree,_done if tree.parent is not None: tree = tree.parent else: _done = True def init(): global tree,_done if _done: tree = None def select_args(args,indices): if indices is not None: to_remove = set(range(len(args))) - set(indices) for idx in to_remove: del args[idx] def get_tree(): global tree return tree
{ "repo_name": "FelixMartel/exectree", "path": "exectree/exectree.py", "copies": "1", "size": "1909", "license": "mit", "hash": 5111978732951579000, "line_mean": 23.7922077922, "line_max": 66, "alpha_frac": 0.5830277632, "autogenerated": false, "ratio": 4.010504201680672, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.008909718632676287, "num_lines": 77 }
from functools import wraps from couchdbkit.exceptions import ResourceNotFound from couchdbkit.ext.django.schema import * from django.contrib.auth.models import check_password from django.http import HttpResponse from django.conf import settings import os from corehq.util.hash_compat import make_password PERMISSION_POST_SMS = "POST_SMS" PERMISSION_POST_WISEPILL = "POST_WISEPILL" class ApiUser(Document): password = StringProperty() permissions = ListProperty(StringProperty) @property def username(self): if self['_id'].startswith("ApiUser-"): return self['_id'][len("ApiUser-"):] else: raise Exception("ApiUser _id has to be 'ApiUser-' + username") def set_password(self, raw_password): salt = os.urandom(5).encode('hex') self.password = make_password(raw_password, salt=salt) def check_password(self, raw_password): return check_password(raw_password, self.password) def has_permission(self, permission): return permission in self.permissions @classmethod def create(cls, username, password, permissions=None): """ To create a new ApiUser on the server: ./manage.py shell $ from corehq.apps.api.models import * $ ApiUser.create('buildserver', 'RANDOM').save() """ self = cls() self['_id'] = "ApiUser-%s" % username self.set_password(password) self.permissions = permissions or [] return self @classmethod def get_user(cls, username): return cls.get("ApiUser-%s" % username) @classmethod def auth(cls, username, password, permission=None): try: user = cls.get_user(username) if user.check_password(password): if permission is not None: return user.has_permission(permission) else: return True else: return False except ResourceNotFound: return False def _require_api_user(permission=None): def _outer2(fn): from django.views.decorators.http import require_POST if settings.DEBUG: return fn @require_POST @wraps(fn) def _outer(request, *args, **kwargs): if ApiUser.auth(request.POST.get('username', ''), request.POST.get('password', ''), permission): response = fn(request, *args, **kwargs) else: response = HttpResponse() response.status_code = 401 return response return _outer return _outer2 require_api_user = _require_api_user() require_api_user_permission = _require_api_user
{ "repo_name": "benrudolph/commcare-hq", "path": "corehq/apps/api/models.py", "copies": "1", "size": "2733", "license": "bsd-3-clause", "hash": 8152446807061186000, "line_mean": 29.7078651685, "line_max": 108, "alpha_frac": 0.6121478229, "autogenerated": false, "ratio": 4.230650154798762, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.014116640383520087, "num_lines": 89 }
from functools import wraps from couchdbkit.exceptions import ResourceNotFound from dimagi.ext.couchdbkit import * from django.contrib.auth.models import check_password from django.http import HttpResponse from django.conf import settings import os from corehq.util.hash_compat import make_password PERMISSION_POST_SMS = "POST_SMS" PERMISSION_POST_WISEPILL = "POST_WISEPILL" class ApiUser(Document): password = StringProperty() permissions = ListProperty(StringProperty) @property def username(self): if self['_id'].startswith("ApiUser-"): return self['_id'][len("ApiUser-"):] else: raise Exception("ApiUser _id has to be 'ApiUser-' + username") def set_password(self, raw_password): salt = os.urandom(5).encode('hex') self.password = make_password(raw_password, salt=salt) def check_password(self, raw_password): return check_password(raw_password, self.password) def has_permission(self, permission): return permission in self.permissions @classmethod def create(cls, username, password, permissions=None): """ To create a new ApiUser on the server: ./manage.py shell $ from corehq.apps.api.models import * $ ApiUser.create('buildserver', 'RANDOM').save() """ self = cls() self['_id'] = "ApiUser-%s" % username self.set_password(password) self.permissions = permissions or [] return self @classmethod def get_user(cls, username): return cls.get("ApiUser-%s" % username) @classmethod def auth(cls, username, password, permission=None): try: user = cls.get_user(username) if user.check_password(password): if permission is not None: return user.has_permission(permission) else: return True else: return False except ResourceNotFound: return False def _require_api_user(permission=None): def _outer2(fn): from django.views.decorators.http import require_POST if settings.DEBUG: return fn @require_POST @wraps(fn) def _outer(request, *args, **kwargs): if ApiUser.auth(request.POST.get('username', ''), request.POST.get('password', ''), permission): response = fn(request, *args, **kwargs) else: response = HttpResponse() response.status_code = 401 return response return _outer return _outer2 require_api_user = _require_api_user() require_api_user_permission = _require_api_user
{ "repo_name": "puttarajubr/commcare-hq", "path": "corehq/apps/api/models.py", "copies": "1", "size": "2726", "license": "bsd-3-clause", "hash": -8220834246174839000, "line_mean": 29.6292134831, "line_max": 108, "alpha_frac": 0.6115187087, "autogenerated": false, "ratio": 4.213292117465224, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5324810826165224, "avg_score": null, "num_lines": null }
from functools import wraps from ..data import RemoteData from ..data import datarpc from ..data.routing import inspect from .. import settings def memoize(func): func.ks_memoize = True return func def reconcile(obj, infos): if isinstance(obj, RemoteData): if obj._obj is not None: return obj.obj() elif obj._local_path is not None: return obj.local_path() elif infos[-1][obj.data_url][1].get('data_type', 'object') == 'object': obj = obj.obj() else: obj = obj.local_path() return obj def remote(func): """This decorator makes it easy to write functions that can be run locally on the client or the server. """ @wraps(func) def wrapper(*args, **kwargs): urls = inspect(args, kwargs) if settings.is_server: infos = datarpc.get_info_bulk(urls) else: c = settings.client() infos = c.data_info(urls) new_args = [] for idx, arg in enumerate(args): arg = reconcile(arg, infos) new_args.append(arg) for k, v in kwargs.items(): kwargs[k] = reconcile(v, infos) result = func(*new_args, **kwargs) assert isinstance(result, RemoteData) return result wrapper.ks_remote = True return wrapper
{ "repo_name": "hhuuggoo/kitchensink", "path": "kitchensink/utils/decorators.py", "copies": "1", "size": "1351", "license": "bsd-3-clause", "hash": 2000770398345995800, "line_mean": 28.3695652174, "line_max": 79, "alpha_frac": 0.5817912657, "autogenerated": false, "ratio": 3.882183908045977, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4963975173745977, "avg_score": null, "num_lines": null }
from functools import wraps from datetime import datetime from flask.ext.restful import Resource, reqparse, abort, marshal from cred.database import db from cred.exceptions import NotAuthenticated, InsufficientPermissions from cred.models.client import Client parser = reqparse.RequestParser() parser.add_argument( 'sessionKey', type=str, location=['cookies', 'json'] ) def get_db_items(request, Model=None, default_fields=None, full_fields=None, base_query=None): """Generalized database retrieval with support for parameters.""" # Either use an already initated query, or start a standard query if base_query is not None: query = base_query else: query = Model.query query = query.order_by(db.desc(Model.id)) # Add filters to the query, based on the request if request.args.get('before', False): query = query.filter( Model.id < request.args.get('before', 0) ) if request.args.get('after', False): query = query.filter( Model.id > request.args.get('after', 0) ) if request.args.get('limit', False): query = query.limit(request.args.get('limit', 0)) if request.args.get('offset', False): query = query.offset(request.args.get('offset', 0)) # Retrive the rows from the database query = query.all() # Finally, marshal it before returning the result if request.args.get('full', False) and full_fields is not None: return marshal(query, full_fields) else: return marshal(query, default_fields) def add_nested_arguments(top_pargs, location, args): """Quickly add arguments multiple nested arguments to a parser.""" parser = reqparse.RequestParser() for name, arg_type in args.items(): parser.add_argument( name, type=arg_type, location=location ) return parser.parse_args(req=top_pargs) class AuthenticatedResource(Resource): """Base class for a resource that requires authentication.""" def __init__(self): """Automatically try to authenticate the client.""" super(AuthenticatedResource, self).__init__() self.client = None self.authenticated = False self.authenticate() def require_admin_permission(self): if self.client.apikey.permission != 'admin': raise InsufficientPermissions() def require_write_permission(self): if self.client.apikey.permission not in ['admin', 'write']: raise InsufficientPermissions() def require_read_permission(self): if self.client.apikey.permission not in ['admin', 'write', 'read']: raise InsufficientPermissions() def authenticate(self): """ Get the client from the session key in the cookies, and update the time that the client was last active. """ pargs = parser.parse_args() session_key = pargs['sessionKey'] client = Client.query.filter_by(session=session_key).first() if not client: raise NotAuthenticated() client.last_active = datetime.utcnow() self.client = client self.authenticated = True
{ "repo_name": "Tehnix/cred-server", "path": "cred/common/util.py", "copies": "1", "size": "3213", "license": "bsd-3-clause", "hash": 7999031726864877000, "line_mean": 32.8210526316, "line_max": 94, "alpha_frac": 0.648303766, "autogenerated": false, "ratio": 4.216535433070866, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5364839199070865, "avg_score": null, "num_lines": null }
from functools import wraps from datetime import datetime import tempfile import contextlib import subprocess from threading import Timer import getpass from pssh import exceptions as pssh_exceptions import os, sys from pssh.clients.native import SSHClient as PSSHClient import gevent import io import logging from . import state, common from .common import ( PromptedException, merge, subdict, rename, cwd, sudo_wrap_command, cwd_wrap_command, shell_wrap_command, ensure, ) LOG = logging.getLogger(__name__) class SSHClient(PSSHClient): def __deepcopy__(self, memo): # do not copy.deepcopy ourselves or the pssh SSHClient object, just # return a reference to the object (self) # - https://docs.python.org/3/library/copy.html return self class NetworkError(BaseException): """generic 'died while doing something ssh-related' catch-all exception class. calling str() on this exception will return the results of calling str() on the wrapped exception.""" def __init__(self, wrapped_exception_inst): self.wrapped = wrapped_exception_inst def __str__(self): # for cases where we want the convenient: # `raise NetworkError("some network problem")` if isinstance(self.wrapped, str): return self.wrapped # we have the opportunity here to tweak the error messages to make them # similar to their equivalents in Fabric. # original error messages are still available via `str(excinst.wrapped)` space = " " custom_error_prefixes = { # builder: https://github.com/elifesciences/builder/blob/master/src/buildercore/core.py#L345-L347 # pssh: https://github.com/ParallelSSH/parallel-ssh/blob/8b7bb4bcb94d913c3b7da77db592f84486c53b90/pssh/clients/native/parallel.py#L272-L274 pssh_exceptions.Timeout: "Timed out trying to connect.", # builder: https://github.com/elifesciences/builder/blob/master/src/buildercore/core.py#L348-L350 # fabric: https://github.com/mathiasertl/fabric/blob/master/fabric/network.py#L601-L605 # pssh: https://github.com/ParallelSSH/parallel-ssh/blob/2e9668cf4b58b38316b1d515810d7e6c595c76f3/pssh/exceptions.py pssh_exceptions.SSHException: "Low level socket error connecting to host.", pssh_exceptions.SessionError: "Low level socket error connecting to host.", pssh_exceptions.ConnectionErrorException: "Low level socket error connecting to host.", } new_error = custom_error_prefixes.get(type(self.wrapped)) or "" original_error = str(self.wrapped) return new_error + space + original_error def pem_key(): """returns the first private key found in a list of common private keys. if none of the keys exist, the default (first) key will be returned.""" id_list = ["id_rsa", "id_dsa", "identity", "id_ecdsa"] id_list = [os.path.expanduser("~/.ssh/" + idstr) for idstr in id_list] for id_path in id_list: if os.path.isfile(id_path): return id_path LOG.debug("key not found: %s" % id_path) default = id_list[0] return default def handle(base_kwargs, kwargs): """handles the merging of the base set of function keyword arguments and their possible overrides. `base_kwargs` is a map of the function's keyword arguments and their defaults. `kwargs` are the keyword arguments used when executing the function. the keys from `base_kwargs` are used to determine which keys to extract from the `kwargs` and any global settings. returns a triple of (`global_kwargs`, `user_kwargs`, `final_kwargs`) where `global_kwargs` is the subset of keyword arguments extracted from `state.env`, `user_kwargs` is the subset of keyword arguments extracted from the given kwargs and `final_kwargs` is the result of merging `base_kwargs` <- `global_kwargs` <- `user_kwargs` 'user' keyword arguments that are explicitly passed in take precedence over all others and 'global' keyword arguments take precedence over the function's defaults kwargs.""" key_list = base_kwargs.keys() global_kwargs = subdict(state.ENV, key_list) user_kwargs = subdict(kwargs, key_list) final_kwargs = merge(base_kwargs, global_kwargs, user_kwargs) return global_kwargs, user_kwargs, final_kwargs # api @contextlib.contextmanager def lcd(local_dir): "temporarily changes the local working directory" ensure(os.path.isdir(local_dir), "not a directory: %s" % local_dir) with state.settings(): current_dir = cwd() state.add_cleanup(lambda: os.chdir(current_dir)) os.chdir(local_dir) yield @contextlib.contextmanager def rcd(remote_working_dir): "ensures all commands run are done from the given remote directory. if remote directory doesn't exist, command will not be run" with state.settings(remote_working_dir=remote_working_dir): yield @contextlib.contextmanager def hide(what=None): "hides *all* output, regardless of `what` type of output is to be hidden." with state.settings(quiet=True): yield def _ssh_default_settings(): "default settings for dealing with ssh." return { # current user. sensible default but probably not what you want "user": getpass.getuser(), "host_string": None, # looks for the same ~4 possible keys as Fabric and ParallelSSH. # uses the first one it finds or the most common if none found. "key_filename": pem_key(), "port": 22, "use_shell": True, "use_sudo": False, "combine_stderr": True, "quiet": False, "remote_working_dir": None, "timeout": None, "warn_only": False, # https://github.com/mathiasertl/fabric/blob/master/fabric/state.py#L301-L305 "abort_exception": RuntimeError, } def _ssh_client(**kwargs): """returns an instance of pssh.clients.native.SSHClient if within a state context, looks for a client already in use and returns that if found. if not found, creates a new one and stores it for later use.""" # parameters we're interested in and their default values base_kwargs = subdict( _ssh_default_settings(), ["user", "host_string", "key_filename", "port"] ) global_kwargs, user_kwargs, final_kwargs = handle(base_kwargs, kwargs) final_kwargs["password"] = None # always private keys rename(final_kwargs, [("key_filename", "pkey"), ("host_string", "host")]) # if we're not using global state, return the new client as-is env = state.ENV if env.read_only: return SSHClient(**final_kwargs) client_map_key = "ssh_client" client_key = subdict(final_kwargs, ["user", "host", "pkey", "port", "timeout"]) client_key = tuple(sorted(client_key.items())) # otherwise, check to see if a previous client is available for this host client_map = env.get(client_map_key, {}) if client_key in client_map: return client_map[client_key] # if not, create a new one and store it in the state # https://parallel-ssh.readthedocs.io/en/latest/native_single.html#pssh.clients.native.single.SSHClient client = SSHClient(**final_kwargs) # disconnect session when leaving context manager state.add_cleanup(lambda: client.disconnect()) client_map[client_key] = client env[client_map_key] = client_map return client def _execute(command, user, key_filename, host_string, port, use_pty, timeout): """creates an SSHClient object and executes given `command` with the given parameters.""" client = _ssh_client( user=user, host_string=host_string, key_filename=key_filename, port=port ) shell = False # handled ourselves sudo = False # handled ourselves user = None # user to sudo to encoding = "utf-8" # used everywhere try: # https://parallel-ssh.readthedocs.io/en/latest/native_single.html#pssh.clients.native.single.SSHClient.run_command channel, host_string, stdout, stderr, stdin = client.run_command( command, sudo, user, use_pty, shell, encoding, timeout ) def get_exit_code(): client.wait_finished(channel) return channel.get_exit_status() return { # defer executing as it consumes output entirely before returning. this # removes our chance to display/transform output as it is streamed to us "return_code": get_exit_code, "command": command, "stdout": stdout, "stderr": stderr, } except BaseException as ex: # *probably* a network error: # - https://github.com/ParallelSSH/parallel-ssh/blob/master/pssh/exceptions.py raise NetworkError(ex) def _print_line(output_pipe, line, **kwargs): """writes the given `line` (string) to the given `output_pipe` (file-like object) if `quiet` is True, `line` is *not* written to `output_pipe`. if `discard_output` is True, `line` is *not* returned and output does *not* accumulate in memory.""" if not common.PY3: # in python2, assume the data we're reading is utf-8 otherwise the call to `.format` # below will attempt to encode the string as ascii and fail with an `UnicodeEncodeError` line = line.encode("utf-8") base_kwargs = { "discard_output": False, "quiet": False, "line_template": "[{host}] {pipe}: {line}\n", # "1.2.3.4 err: Foo not found\n" "display_prefix": True, # strips everything in `line_template` before "{line}" "custom_pipe": None, } global_kwargs, user_kwargs, final_kwargs = handle(base_kwargs, kwargs) if not final_kwargs["quiet"]: # useful values that can be part of the template pipe_type = "err" if output_pipe == sys.stderr else "out" if final_kwargs["custom_pipe"]: pipe_type = final_kwargs["custom_pipe"] # like "run" dt = datetime.now() template_kwargs = { "line": line, "year": dt.year, "month": dt.month, "day": dt.day, "hour": dt.hour, "minute": dt.minute, "second": dt.second, "ms": dt.microsecond, "host": state.ENV.get("host_string", ""), "pipe": pipe_type, } # render template and write to given pipe template = final_kwargs["line_template"] if not final_kwargs["display_prefix"]: try: template = template[template.index("{line}"):] except ValueError: # "substring not found" msg = "'display_prefix' option ignored: '{line}' not found in 'line_template' setting" LOG.warning(msg) pass output_pipe.write(template.format(**template_kwargs)) if not final_kwargs["discard_output"]: return line # free of any formatting def _process_output(output_pipe, result_list, **kwargs): "calls `_print_line` on each result in `result_list`." # always process the results as soon as we have them # use `quiet=True` to hide the printing of output to stdout/stderr # use `discard_output=True` to discard the results as soon as they are read. # `stderr` results may be empty if `combine_stderr` in call to `remote` was `True` new_results = [_print_line(output_pipe, line, **kwargs) for line in result_list] output_pipe.flush() if "discard_output" in kwargs and not kwargs["discard_output"]: return new_results def _print_running(command, output_pipe, **kwargs): """Prints the command to be run on a line of output prior to executing a command. Obeys the formatting and rules of the context in which the command is being exected. Deprecated. This is to mimic Fabric's command output until we're sure nothing depends on it. It will be replaced with a standard LOG.info output eventually.""" keepers = ["display_running", "quiet", "discard_output", "line_template"] kwargs = subdict(kwargs, keepers) if kwargs["display_running"]: if not isinstance(command, list): command = [command] command = " ".join(command) return _print_line(output_pipe, command, custom_pipe="run", **kwargs) def abort(result, err_msg, **kwargs): """raises a `RuntimeError` with the given `err_msg` and the given `result` attached to it's `.result` property. issues a warning and returns the given `result` if `settings.warn_only` is `True`. raises a SystemExit with a return code of `1` if `settings.abort_exception` is set to None.""" base_kwargs = { "quiet": False, "warn_only": False, "display_aborts": True, "abort_exception": RuntimeError, } global_kwargs, user_kwargs, final_kwargs = handle(base_kwargs, kwargs) if final_kwargs["warn_only"]: if not final_kwargs["quiet"]: LOG.warning(err_msg) return result if final_kwargs["display_aborts"]: if not final_kwargs["quiet"]: LOG.error("Fatal error: %s" % err_msg) abort_exc_klass = final_kwargs["abort_exception"] if abort_exc_klass: exc = abort_exc_klass(err_msg) setattr(exc, "result", result) raise exc # https://docs.python.org/3/library/exceptions.html#SystemExit # # https://github.com/mathiasertl/fabric/blob/master/fabric/utils.py#L30-L63 exc = SystemExit(1) exc.message = err_msg raise exc # https://github.com/mathiasertl/fabric/blob/master/fabric/state.py#L338 # https://github.com/mathiasertl/fabric/blob/master/fabric/operations.py#L898-L901 # https://github.com/mathiasertl/fabric/blob/master/fabric/operations.py#L975 def remote(command, **kwargs): "preprocesses given `command` and options before sending it to `_execute` to be executed on remote host" # Fabric function signature for `run` # shell=True # done # pty=True # mutually exclusive with `combine_stderr` in pssh. not sure how Fabric/Paramiko is doing it # combine_stderr=None # mutually exclusive with use_pty. 'True' in global env. # quiet=False, # done # warn_only=False # done # stdout=None # done, stdout/stderr always available unless explicitly discarded. 'see discard_output' # stderr=None # done, stderr not available when combine_stderr is `True` # timeout=None # done # shell_escape=None # ignored. shell commands are always escaped # capture_buffer_size=None # correlates to `ssh2.channel.read` and the `size` parameter. Ignored. # parameters we're interested in and their default values base_kwargs = _ssh_default_settings() base_kwargs.update({"display_running": True, "discard_output": False}) global_kwargs, user_kwargs, final_kwargs = handle(base_kwargs, kwargs) # wrap the command up # https://github.com/mathiasertl/fabric/blob/master/fabric/operations.py#L920-L925 if final_kwargs["remote_working_dir"]: command = cwd_wrap_command(command, final_kwargs["remote_working_dir"]) if final_kwargs["use_shell"]: command = shell_wrap_command(command) if final_kwargs["use_sudo"]: command = sudo_wrap_command(command) # if use_pty is True, stdout and stderr are combined and stderr will yield nothing. # - https://parallel-ssh.readthedocs.io/en/latest/advanced.html#combined-stdout-stderr use_pty = final_kwargs["combine_stderr"] # values `remote` specifically passes to `_execute` execute_kwargs = {"command": command, "use_pty": use_pty} execute_kwargs = merge(final_kwargs, execute_kwargs) execute_kwargs = subdict( execute_kwargs, [ "command", "user", "key_filename", "host_string", "port", "use_pty", "timeout", ], ) # TODO: validate `_execute`s args. `host_string` can't be None for example # run command _print_running(command, sys.stdout, **final_kwargs) result = _execute(**execute_kwargs) # handle stdout/stderr streams output_kwargs = subdict(final_kwargs, ["quiet", "discard_output"]) stdout = _process_output(sys.stdout, result["stdout"], **output_kwargs) stderr = _process_output(sys.stderr, result["stderr"], **output_kwargs) # command must have finished before we have access to return code return_code = result["return_code"]() result.update( { "stdout": stdout, "stderr": stderr, "return_code": return_code, "failed": return_code > 0, "succeeded": return_code == 0, } ) if result["succeeded"]: return result err_msg = "remote() encountered an error (return code %s) while executing %r" % ( result["return_code"], command, ) # if `warn_only` is True this function may still return a result return abort(result, err_msg, **final_kwargs) # https://github.com/mathiasertl/fabric/blob/master/fabric/operations.py#L1100 def remote_sudo(command, **kwargs): "exactly the same as `remote`, but the given command is run as the root user" # user=None # ignore # group=None # ignore kwargs["use_sudo"] = True return remote(command, **kwargs) # https://github.com/mathiasertl/fabric/blob/master/fabric/contrib/files.py#L15 def remote_file_exists(path, **kwargs): "returns True if given path exists on remote system" # note: Fabric is doing something weird and clever here: # - https://github.com/mathiasertl/fabric/blob/master/fabric/contrib/files.py#L474-L485 # but their examples don't work: # $ /bin/sh # sh-5.0$ foo="$(echo /usr/\*/share)" # sh-5.0$ echo $foo # /usr/*/share # sh-5.0$ exit # $ echo $SHELL # $ /bin/bash # $ foo="$(echo /usr/\*/share)" # $ echo $foo # /usr/*/share # TODO: revisit # update 2020/01: it does work, I just had no "/usr/[anything]/share" directories. # this works for me: # foo=$(echo /\*/share/) # echo $foo # /usr/share/ base_kwargs = { "use_sudo": False, } global_kwargs, user_kwargs, final_kwargs = handle(base_kwargs, kwargs) # do not raise an exception if remote file doesn't exist final_kwargs["warn_only"] = True remote_fn = remote_sudo if final_kwargs["use_sudo"] else remote command = "test -e %s" % path return remote_fn(command, **final_kwargs)["return_code"] == 0 # https://github.com/mathiasertl/fabric/blob/master/fabric/operations.py#L1157 def local(command, **kwargs): "preprocesses given `command` and options before executing it locally using Python's `subprocess.Popen`" base_kwargs = { "use_sudo": False, "use_shell": True, "combine_stderr": True, "capture": False, "timeout": None, "quiet": False, "display_running": True, "warn_only": False, # https://github.com/mathiasertl/fabric/blob/master/fabric/state.py#L301-L305 "abort_exception": RuntimeError, } global_kwargs, user_kwargs, final_kwargs = handle(base_kwargs, kwargs) # TODO: once py2 support has been dropped, move this back to file head devnull_opened = False try: from subprocess import DEVNULL # py3 except ImportError: devnull_opened = True DEVNULL = open(os.devnull, "wb") if final_kwargs["capture"]: if final_kwargs["combine_stderr"]: out_stream = subprocess.PIPE err_stream = subprocess.STDOUT else: out_stream = subprocess.PIPE err_stream = subprocess.PIPE else: if final_kwargs["quiet"]: # we're not capturing and we've been told to be quiet # send everything to /dev/null out_stream = DEVNULL err_stream = DEVNULL else: out_stream = None err_stream = None if not final_kwargs["use_shell"] and not isinstance(command, list): raise ValueError("when shell=False, given command *must* be a list") if final_kwargs["use_shell"]: command = shell_wrap_command(command) if final_kwargs["use_sudo"]: if final_kwargs["use_shell"]: command = sudo_wrap_command(command) else: # lsh@2020-04: is this a good enough sudo command? # nothing uses local+noshell+sudo (at time of writing) command = ["sudo", "--non-interactive"] + command proc = subprocess.Popen( command, shell=final_kwargs["use_shell"], stdout=out_stream, stderr=err_stream ) _print_running(command, sys.stdout, **final_kwargs) if final_kwargs["timeout"]: timer = Timer(final_kwargs["timeout"], proc.kill) try: timer.start() # proximity matters stdout, stderr = proc.communicate() finally: timer.cancel() else: stdout, stderr = proc.communicate() # https://github.com/mathiasertl/fabric/blob/master/fabric/operations.py#L1240-L1244 result = { "return_code": proc.returncode, "failed": proc.returncode != 0, "succeeded": proc.returncode == 0, "command": command, "stdout": (stdout or b"").decode("utf-8").splitlines(), "stderr": (stderr or b"").decode("utf-8").splitlines(), } if devnull_opened: DEVNULL.close() if result["succeeded"]: return result err_msg = "local() encountered an error (return code %s) while executing %r" % ( result["return_code"], command, ) # if `warn_only` is True this function may still return a result return abort(result, err_msg, **final_kwargs) def single_command(cmd_list): "given a list of commands to run, returns a single command." # `remote` and `local` will do any escaping as necessary if cmd_list in [None, []]: return None return " && ".join(map(str, cmd_list)) def prompt(msg): """issues a prompt for input. raises a `PromptedException` if `abort_on_prompts` in `state.ENV` is `True` or executing within another process using `execute.parallel` where input can't be supplied. if `abort_exception` is set in `state.ENV`, then that exception is raised instead""" if state.ENV.get("abort_on_prompts", False): abort_ex = state.ENV.get("abort_exception", PromptedException) raise abort_ex("prompted with: %s" % (msg,)) print(msg) try: return raw_input("> ") except NameError: return input("> ") # # uploads and downloads # def execute_rsync_command(cmd): """executes given rsync `cmd`, catching rsync errors and improving any errors raised. rsync commands can be generated with `_rsync_upload` and `_rsync_download` functions. """ try: return local(cmd) except Exception as uncaught_exc: if hasattr(uncaught_exc, "result"): # this is a threadbare error and we may be able to improve it result = uncaught_exc.result # taken straight from the `man` page, authored "28 Jan 2018" error_map = { 1: "Syntax or usage error", 2: "Protocol incompatibility", 3: "Errors selecting input/output files, dirs", 4: "Requested action not supported: an attempt was made to manipulate 64-bit files on a platform that cannot support them; or an option was specified that is supported by the client and not by the server.", 5: "Error starting client-server protocol", 6: "Daemon unable to append to log-file", 10: "Error in socket I/O", 11: "Error in file I/O", 12: "Error in rsync protocol data stream", 13: "Errors with program diagnostics", 14: "Error in IPC code", 20: "Received SIGUSR1 or SIGINT", 21: "Some error returned by waitpid()", 22: "Error allocating core memory buffers", 23: "Partial transfer due to error", 24: "Partial transfer due to vanished source files", 25: "The --max-delete limit stopped deletions", 30: "Timeout in data send/receive", 35: "Timeout waiting for daemon connection", } if result["return_code"] in error_map: raise NetworkError( "rsync returned error %s: %s" % (result["return_code"], error_map[result["return_code"]]) ) raise uncaught_exc def _rsync_upload(local_path, remote_path, **kwargs): """generates an rsync command to copy `local_path` to `remote_path` using values in the current `state.ENV`. does *not* execute command. see `rsync_upload` and `execute_rsync_command`.""" base_kwargs = subdict( _ssh_default_settings(), ["user", "host_string", "key_filename", "port"] ) global_kwargs, user_kwargs, final_kwargs = handle(base_kwargs, kwargs) cmd = [ "rsync", # '-i' is 'identity file' # note: without 'StrictHostKeyChecking' we'll be given a prompt during testing. is this solvable? "--rsh='ssh -i %s -p %s -o StrictHostKeyChecking=no'" % (final_kwargs["key_filename"], final_kwargs["port"]), local_path, "%s@%s:%s" % (final_kwargs["user"], final_kwargs["host_string"], remote_path), ] return " ".join(cmd) def rsync_upload(local_path, remote_path, **kwargs): "copies `local_path` to `remote_path` using values in the current `state.ENV`." remote_dir = os.path.dirname(remote_path) if not remote_file_exists(remote_dir): remote("mkdir -p %r" % remote_dir) return execute_rsync_command(_rsync_upload(local_path, remote_path, **kwargs)) def _rsync_download(remote_path, local_path, **kwargs): """generates an rsync command to copy `remote_path` to `local_path` using values in the current `state.ENV`. does *not* execute command. see `rsync_download` and `execute_rsync_command`.""" base_kwargs = subdict( _ssh_default_settings(), ["user", "host_string", "key_filename", "port"] ) global_kwargs, user_kwargs, final_kwargs = handle(base_kwargs, kwargs) cmd = [ "rsync", # '-i' is 'identity file' # without 'StrictHostKeyChecking' we'll be given a prompt during testing. "--rsh='ssh -i %s -p %s -o StrictHostKeyChecking=no'" % (final_kwargs["key_filename"], final_kwargs["port"]), "%s@%s:%s" % (final_kwargs["user"], final_kwargs["host_string"], remote_path), local_path, ] return " ".join(cmd) def rsync_download(remote_path, local_path, **kwargs): "copies `remote_path` to `local_path` using values in the current `state.ENV`." abs_local_path = os.path.abspath(os.path.expanduser(local_path)) abs_local_dir = os.path.dirname(abs_local_path) if not os.path.exists(abs_local_dir): # replicates behaviour of downloading via scp and sftp (via parallel-ssh) local("mkdir -p %r" % (abs_local_dir,)) return execute_rsync_command(_rsync_download(remote_path, local_path, **kwargs)) def _transfer_fn(client, direction, **kwargs): """returns the `client` object's appropriate transfer *method* given a `direction`. `direction` is either 'upload' or 'download'. Also accepts the `transfer_protocol` keyword parameter that is either 'scp' (default) or 'sftp'.""" base_kwargs = { "overwrite": True, # sftp is *exceptionally* slow. # Paramiko's implementation is faster than native SFTP but slower than SCP: # - https://github.com/ParallelSSH/parallel-ssh/issues/177 # however, SCP is buggy and may randomly hang or complete without uploading anything. # take slow and reliable over fast and buggy. "transfer_protocol": "rsync", # "sftp", # "scp" } global_kwargs, user_kwargs, final_kwargs = handle(base_kwargs, kwargs) def upload_fn(fn): @wraps(fn) def wrapper(local_file, remote_file): if remote_file_exists(remote_file) and not final_kwargs["overwrite"]: raise NetworkError( "Remote file exists and 'overwrite' is set to 'False'. Refusing to write: %s" % (remote_file,) ) if final_kwargs["transfer_protocol"] == "rsync": fn(local_file, remote_file) else: # https://github.com/ParallelSSH/parallel-ssh/blob/8b7bb4bcb94d913c3b7da77db592f84486c53b90/pssh/clients/native/parallel.py#L524 gevent.joinall(fn(local_file, remote_file), raise_error=True) # lsh@2020-04, local testing didn't reveal anything but small files uploaded via SCP SCP during CI # were either missing or had empty bodies. SFTP seemed to be fine. # This sanity check seems to fix the issue (lending more credence to my theory it's an unflushed buffer somewhere), # when waiting 3 seconds between upload of file and check of file was still failing. ensure( remote_file_exists(remote_file, **kwargs), "failed to upload file, remote file does not exist: %s" % (remote_file,), ) return wrapper def download_fn(fn): @wraps(fn) def wrapper(remote_file, local_file): if not final_kwargs["overwrite"] and os.path.exists(local_file): raise NetworkError( "Local file exists and 'overwrite' is set to 'False'. Refusing to write: %s" % (local_file,) ) if final_kwargs["transfer_protocol"] == "rsync": fn(remote_file, local_file) else: # https://github.com/ParallelSSH/parallel-ssh/blob/8b7bb4bcb94d913c3b7da77db592f84486c53b90/pssh/clients/native/parallel.py#L560 gevent.joinall(fn(remote_file, local_file), raise_error=True) return wrapper upload_backends = { "sftp": client.copy_file, "scp": client.scp_send, "rsync": rsync_upload, } download_backends = { "sftp": client.copy_remote_file, "scp": client.scp_recv, "rsync": rsync_download, } direction_map = {"upload": upload_backends, "download": download_backends} ensure( direction in direction_map, "you can 'upload' or 'download' but not %r" % (direction,), ) backend_map = direction_map[direction] transfer_protocol = final_kwargs["transfer_protocol"] ensure( transfer_protocol in backend_map, "unhandled transfer protocol %r; supported protocols: %s" % (transfer_protocol, ", ".join(backend_map.keys())), ) transfer_fn = direction_map[direction][transfer_protocol] direction_wrapper_map = {"upload": upload_fn, "download": download_fn} wrapper_fn = direction_wrapper_map[direction] return wrapper_fn(transfer_fn) # https://github.com/mathiasertl/fabric/blob/master/fabric/operations.py#L419 # use_sudo hack: https://github.com/mathiasertl/fabric/blob/master/fabric/operations.py#L453-L458 def _download_as_root_hack(remote_path, local_path, **kwargs): """as root, creates a temporary copy of the file that can be downloaded by a regular user and then removes the temporary file. warning: don't try to download anything huge `with_sudo` as the file is duplicated. warning: the privileged file will be available in /tmp until the download is complete""" if not remote_file_exists(remote_path, use_sudo=True, **kwargs): raise EnvironmentError("remote file does not exist: %s" % (remote_path,)) client = _ssh_client(**kwargs) cmd = single_command( [ # create a temporary file with the suffix '-threadbare' 'tempfile=$(mktemp --suffix "-threadbare")', # copy the target file to this temporary file 'cp "%s" "$tempfile"' % remote_path, # ensure it's readable by the user doing the downloading 'chmod +r "$tempfile"', # emit the name of the temporary file so we can find it to download it 'echo "$tempfile"', ] ) result = remote_sudo(cmd, **kwargs) remote_tempfile = result["stdout"][-1] remote_path = remote_tempfile transfer_fn = _transfer_fn(client, "download", **kwargs) try: transfer_fn(remote_tempfile, local_path) return local_path except (pssh_exceptions.SFTPError, pssh_exceptions.SCPError) as exc: # permissions or network issues may cause these raise NetworkError(exc) finally: remote_sudo('rm -f "%s"' % remote_tempfile, **kwargs) # https://github.com/mathiasertl/fabric/blob/master/fabric/operations.py#L419 # use_sudo hack: https://github.com/mathiasertl/fabric/blob/master/fabric/operations.py#L453-L458 def download(remote_path, local_path, use_sudo=False, **kwargs): """downloads file at `remote_path` to `local_path`, overwriting the local path if it exists. avoid `use_sudo` if at all possible""" with state.settings(quiet=True): if remote_path.endswith("/"): raise ValueError("directory downloads are not supported") # do not raise an exception if remote path is a directory result = remote( 'test -d "%s"' % remote_path, use_sudo=use_sudo, warn_only=True, quiet=True ) remote_path_is_dir = result["succeeded"] if remote_path_is_dir: raise ValueError("directory downloads are not supported") temp_file, data_buffer = None, None if hasattr(local_path, "read"): # given a file-like object to download file into. # 1. write the remote file to local temporary file # 2. read temporary file into the given buffer # 3. delete the temporary file data_buffer = local_path temp_file, local_path = tempfile.mkstemp(suffix="-threadbare") if not os.path.isabs(local_path): local_path = os.path.abspath(local_path) if os.path.isdir(local_path): local_path = os.path.join(local_path, os.path.basename(remote_path)) if use_sudo: local_path = _download_as_root_hack(remote_path, local_path, **kwargs) else: if not remote_file_exists(remote_path, **kwargs): raise EnvironmentError( "remote file does not exist: %s" % (remote_path,) ) client = _ssh_client(**kwargs) transfer_fn = _transfer_fn(client, "download", **kwargs) try: transfer_fn(remote_path, local_path) except (pssh_exceptions.SFTPError, pssh_exceptions.SCPError) as exc: # permissions or network issues may cause these raise NetworkError(exc) if temp_file: flags = "r" if isinstance(data_buffer, io.StringIO) else "rb" data = open(local_path, flags).read() data_buffer.write(data) # deletes the *temporary file*. `temp_file` is a file descriptor os.unlink(local_path) return data_buffer return local_path def _upload_as_root_hack(local_path, remote_path, **kwargs): """uploads file at `local_path` to a remote temporary file then moves the file to `remote_path` as root. does not alter any permissions or attributes on the file""" client = _ssh_client(**kwargs) cmd = single_command( [ # create a temporary file with the suffix '-threadbare' 'tempfile=$(mktemp --suffix "-threadbare")', 'echo "$tempfile"', ] ) result = remote(cmd, **kwargs) remote_temp_path = result["stdout"][-1] ensure( remote_file_exists(remote_temp_path, **kwargs), "remote temporary file %r (%s) does not exist" % (remote_temp_path, remote_path), ) transfer_fn = _transfer_fn(client, "upload", **kwargs) try: transfer_fn(local_path, remote_temp_path) move_file_into_place = 'mv "%s" "%s"' % (remote_temp_path, remote_path) remote_sudo(move_file_into_place, **kwargs) ensure( remote_file_exists(remote_path, use_sudo=True, **kwargs), "remote path does not exist: %s" % (remote_path), ) except (pssh_exceptions.SFTPError, pssh_exceptions.SCPError) as exc: # permissions or network issues may cause these raise NetworkError(exc) def _write_bytes_to_temporary_file(local_path): """if `local_path` is a file-like object, write the contents to an *actual* file and return a pair of new local filename and a function that removes the temporary file when called.""" if hasattr(local_path, "read"): # `local_path` is a file-like object local_bytes = local_path local_bytes.seek(0) # reset internal pointer temp_file, local_path = tempfile.mkstemp(suffix="-threadbare") with os.fdopen(temp_file, "wb") as fh: data = local_bytes.getvalue() # data may be a string or it may be bytes. # if it's a string we assume it's a UTF-8 string. if isinstance(data, str): data = bytes(data, "utf-8") fh.write(data) cleanup = lambda: os.unlink(local_path) return local_path, cleanup return local_path, None def upload(local_path, remote_path, use_sudo=False, **kwargs): "uploads file at `local_path` to the given `remote_path`, overwriting anything that may be at that path" # todo: this setting is dubious, don't count on it hanging around with state.settings(quiet=True): # bytes handling local_path, cleanup_fn = _write_bytes_to_temporary_file(local_path) if cleanup_fn: state.add_cleanup(cleanup_fn) if os.path.isdir(local_path): raise ValueError("folders cannot be uploaded") if use_sudo: return _upload_as_root_hack(local_path, remote_path, **kwargs) if not os.path.exists(local_path): raise EnvironmentError("local file does not exist: %s" % (local_path,)) client = _ssh_client(**kwargs) try: transfer_fn = _transfer_fn(client, "upload", **kwargs) transfer_fn(local_path, remote_path) except (pssh_exceptions.SFTPError, pssh_exceptions.SCPError) as exc: # permissions or network issues may cause these raise NetworkError(exc)
{ "repo_name": "elifesciences/builder", "path": "src/buildercore/threadbare/operations.py", "copies": "1", "size": "38849", "license": "mit", "hash": 2477796869664445000, "line_mean": 38.4806910569, "line_max": 224, "alpha_frac": 0.6302607532, "autogenerated": false, "ratio": 3.8384546981523564, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4968715451352356, "avg_score": null, "num_lines": null }
from functools import wraps from datetime import datetime import time import traceback import math import xbmc #@UnresolvedImport import xbmcgui #@UnresolvedImport from constants import WEATHER_WINDOW_ID, SETTINGS_WINDOW_ID, DIALOG, WINDOW, TEMPERATUREUNITS, ADDON #by importing utilities all messages in xbmc log will be prepended with LOGPREFIX def log(msg, level=xbmc.LOGNOTICE): xbmc.log('weather.metoffice: {0}'.format(msg), level) #python datetime.strptime is not thread safe: sometimes causes 'NoneType is not callable' error def strptime(dt, fmt): return datetime.fromtimestamp(time.mktime(time.strptime(dt, fmt))) def failgracefully(f): @wraps(f) def wrapper(*args, **kwds): try: return f(*args, **kwds) except Exception as e: e.args = map(str, e.args) log(traceback.format_exc(), xbmc.LOGSEVERE) if len(e.args) == 0 or e.args[0] == '': e.args = ('Error',) if len(e.args) == 1: e.args = e.args + ('See log file for details',) if xbmcgui.getCurrentWindowId() == WEATHER_WINDOW_ID or xbmcgui.getCurrentWindowId() == SETTINGS_WINDOW_ID: args = (e.args[0].title(),) + e.args[1:4] DIALOG.ok(*args)#@UndefinedVariable return wrapper def xbmcbusy(f): @wraps(f) def wrapper(*args, **kwds): if xbmcgui.getCurrentWindowId() == WEATHER_WINDOW_ID or xbmcgui.getCurrentWindowId() == SETTINGS_WINDOW_ID: xbmc.executebuiltin( "ActivateWindow(busydialog)" ) try: return f(*args, **kwds) finally: xbmc.executebuiltin( "Dialog.Close(busydialog)" ) return wrapper def panelbusy(pane): def decorate(f): @wraps(f) def wrapper(*args, **kwargs): WINDOW.setProperty('{0}.IsBusy'.format(pane), 'true')#@UndefinedVariable try: return f(*args, **kwargs) finally: WINDOW.clearProperty('{0}.IsBusy'.format(pane))#@UndefinedVariable return wrapper return decorate def minutes_as_time(minutes): """ Takes an integer number of minutes and returns it as a time, starting at midnight. """ return time.strftime('%H:%M', time.gmtime(minutes*60)) def haversine_distance(lat1, lon1, lat2, lon2): """ Calculate the distance between two coords using the haversine formula http://en.wikipedia.org/wiki/Haversine_formula """ EARTH_RADIUS = 6371 lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2]) dlat = lat2-lat1 dlon = lon2-lon1 a = math.sin(dlat/2)**2 + \ math.cos(lat1) * math.cos(lat2) * \ math.sin(dlon/2)**2 c = 2 * math.asin(math.sqrt(a)) return EARTH_RADIUS * c def rownd(x): try: return str(round(float(x))).split('.')[0] except ValueError: return '' def localised_temperature(t): if TEMPERATUREUNITS[-1] == 'C': return t else: try: return str(int(float(t)*9)/5+32) except ValueError: return '' def gettext(s): """ gettext() gets around XBMCs cryptic "Ints For Strings" translation mechanism requires the translatable table is kept up to date with the contents of strings.po """ translatable = {"Observation Location" : 32000, "Forecast Location": 32001, "Regional Location": 32002, "API Key": 32003, "Use IP address to determine location": 32004, "GeoIP Provider": 32005, "Erase Cache": 32006, "No API Key.": 32007, "Enter your Met Office API Key under settings.": 32008, "No Matches": 32009, "No locations found containing": 32010, "Matching Sites": 32011} try: translation = ADDON.getLocalizedString(translatable[s]) #@UndefinedVariable if not translation: raise TranslationError else: return translation except (KeyError, TranslationError): log('String "{0}" not translated.'.format(s), level=xbmc.LOGWARNING) return s class TranslationError(Exception): pass
{ "repo_name": "aplicatii-romanesti/allinclusive-kodi-pi", "path": ".kodi/addons/weather.metoffice/src/metoffice/utilities.py", "copies": "1", "size": "4292", "license": "apache-2.0", "hash": 1975368852600201500, "line_mean": 33.6129032258, "line_max": 119, "alpha_frac": 0.5976234856, "autogenerated": false, "ratio": 3.808340727595386, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4905964213195386, "avg_score": null, "num_lines": null }
from functools import wraps from datetime import datetime, time import os import sys from werkzeug.contrib.atom import AtomFeed from flask import Flask, render_template, Blueprint, abort, url_for, make_response from jinja2 import TemplateNotFound, ChoiceLoader, FileSystemLoader from flask.ext.flatpages import FlatPages, pygments_style_defs from flask_frozen import Freezer from BeautifulSoup import BeautifulSoup from htmlmin import minify from html5print import HTMLBeautifier app = Flask(__name__, static_folder=os.path.join(os.getcwd(), 'static')) # Load default config app.config.from_pyfile('config.py') # Override defaults try: app.config.from_pyfile(os.path.join(os.getcwd(), 'config.py')) except IOError: print 'Can not find config.py' sys.exit() # To avoid full paths in config.py app.config['FLATPAGES_ROOT'] = os.path.join(os.getcwd(), app.config.get('POSTS_FOLDER')) app.config['FREEZER_DESTINATION'] = os.path.join(os.getcwd(), app.config.get('BUILD_FOLDER')) app.config['FLATPAGES_EXTENSION'] = app.config.get('POSTS_EXTENSION') app.config['INCLUDE_JS'] = 'combined.min.js' in os.listdir(app.static_folder) app.config['INCLUDE_CSS'] = 'combined.min.css' in os.listdir(app.static_folder) posts = FlatPages(app) freezer = Freezer(app) # Allow config settings (even new user created ones) to be used in templates for key in app.config: app.jinja_env.globals[key] = app.config[key] def truncate_post_html(post_html): return BeautifulSoup(post_html[:255]).prettify() app.jinja_env.globals['truncate_post_html'] = truncate_post_html app.jinja_loader = ChoiceLoader([ FileSystemLoader(os.path.join(os.getcwd(), 'templates/')), app.jinja_loader ]) MONTHS = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'} pages = Blueprint('pages', __name__, template_folder=os.path.join(os.getcwd(), app.config.get('PAGES_FOLDER'))) @app.after_request def format_html(response): if response.mimetype == "text/html": if app.config.get('PRETTY_HTML', False): response.data = HTMLBeautifier.beautify(response.data, 2) elif app.config.get('MINIFY_HTML', False): response.data = minify(response.data) return response @pages.route('/<path:path>/') def page(path): try: return render_template(path + '.html') except TemplateNotFound: abort(404) app.register_blueprint(pages) @app.route('/pygments.css') def pygments_css(): return pygments_style_defs('tango'), 200, {'Content-Type': 'text/css'} @app.route('/') def index(): latest = sorted(posts, reverse=True, key=lambda p: p.meta.get('published')) return render_template('index.html', posts=latest[:4]) @app.route('/feed.atom/') def feed(): name = app.config.get('SITE_NAME') subtitle = app.config.get('SITE_DESCRIPTION') or 'Recent Blog Posts' url = app.config.get('URL') feed = AtomFeed(title=name, subtitle=subtitle, feed_url=url_for('all_posts'), url=url) for post in posts: feed.add(post.meta.get('title'), unicode(post.html), content_type='html', author=post.meta.get('author', app.config.get('DEFAULT_AUTHOR')), url=url_for('post', year=post.meta.get('published').year, month=post.meta.get('published').month, day=post.meta.get('published').day, path=post.path), updated=datetime.combine(post.meta.get('updated') or post.meta.get('published'), time())) return make_response(feed.to_string().encode('utf-8') + '\n') @app.route('/all/') def all_posts(): latest = sorted(posts, reverse=True, key=lambda p: p.meta.get('published')) return render_template('all_posts.html', posts=latest) @app.route('/<int:year>/<int:month>/<int:day>/<path:path>/') def post(year, month, day, path): post = posts.get_or_404(path) date = '%04d-%02d-%02d' % (year, month, day) if str(post.meta.get('published')) != date: abort(404) return render_template('post.html', post=post) def tag_in_list(list_of_tags, tag): for i in list_of_tags: if i['tag'] == tag: return True return False def increment_tag_count(list_of_tags, tag): for i in list_of_tags: if i['tag'] == tag: i['count'] += 1 return list_of_tags @app.route('/tags/') def all_tags(): tags = [] for post in posts: for tag in post.meta.get('tags', []): if tag_in_list(tags, tag) is False: tags.append({'tag': tag, 'count': 1}) else: increment_tag_count(tags, tag) return render_template('all_tags.html', tags=tags) @app.route('/tags/<string:tag>/') def tag(tag): tagged = [p for p in posts if tag in p.meta.get('tags', [])] sorted_posts = sorted(tagged, reverse=True, key=lambda p: p.meta.get('published')) return render_template('tag.html', posts=sorted_posts, tag=tag) @app.route('/author/<author>/') def author(author): author_posts = [p for p in posts if author == p.meta.get('author', '')] sorted_posts = sorted(author_posts, reverse=True, key=lambda p: p.meta.get('published')) return render_template('author.html', author=author, posts=sorted_posts) @app.route('/<int:year>/') def year(year): year_posts = [p for p in posts if year == p.meta.get('published', []).year] sorted_posts = sorted(year_posts, reverse=False, key=lambda p: p.meta.get('published')) return render_template('year.html', year=year, posts=sorted_posts) @app.route('/<int:year>/<int:month>/') def month(year, month): month_posts = [p for p in posts if year == p.meta.get('published').year and month == p.meta.get('published').month == month] sorted_posts = sorted(month_posts, reverse=False, key=lambda p: p.meta.get('published')) month_string = MONTHS[month] return render_template('month.html', year=year, month_string=month_string, posts=sorted_posts) @app.route('/<int:year>/<int:month>/<int:day>/') def day(year, month, day): day_posts = [p for p in posts if year == p.meta.get('published').year and month == p.meta.get('published').month == month] month_string = MONTHS[month] return render_template('day.html', year=year, month_string=month_string, day=day, posts=day_posts) # Telling Frozen-Flask about routes that are not linked to in templates @freezer.register_generator def year(): for post in posts: yield {'year': post.meta.get('published').year} @freezer.register_generator def month(): for post in posts: yield {'year': post.meta.get('published').year, 'month': post.meta.get('published').month} @freezer.register_generator def day(): for post in posts: yield {'year': post.meta.get('published').year, 'month': post.meta.get('published').month, 'day': post.meta.get('published').day}
{ "repo_name": "Siecje/htmd", "path": "htmd/site.py", "copies": "1", "size": "7022", "license": "mit", "hash": -6602808896706679000, "line_mean": 33.7623762376, "line_max": 170, "alpha_frac": 0.6513813728, "autogenerated": false, "ratio": 3.293621013133208, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44450023859332083, "avg_score": null, "num_lines": null }
from functools import wraps from datetime import timedelta from django.contrib import messages from django.contrib.auth.decorators import permission_required from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.db.models import Max, Min from django.forms.models import model_to_dict from django.forms.models import inlineformset_factory from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.shortcuts import render_to_response from django.template import RequestContext from django.views.generic.edit import FormView from paypal.standard.forms import PayPalPaymentsForm from .forms import TicketPurchaseForm, TicketFormSet, TicketsForm from .models import TicketPurchase, TicketType, Ticket, Coupon from .utils import daterange def index(request): """ Index view: shows a form with a list of ticket that one can buy """ ticket_types = TicketType.objects.all() form = TicketsForm(ticket_types,[], request.POST) if form.is_valid(): data = form.cleaned_data p = TicketPurchase() print data if data['coupon']: coupon = Coupon.objects.get(data['coupon']) p.coupon = coupon p.additional_contribution = data['donation'] or 0 tickets = [] for type_ in ticket_types: key = 'quantity:%d'%type_.id if key in data: for i in range(data[key]): tickets.append(Ticket(ticket_type=type_)) request.session['purchase'] = p request.session['tickets'] = tickets return redirect('/register/') return render_to_response( "index.html", dict(form=form), context_instance=RequestContext(request)) def details(request): """ Once the user has selected what tickets she wants to buy, this view will let her enter the details. """ p = TicketPurchase() form = TicketPurchaseForm( request.POST or None, instance=request.session['purchase'] ) formset = TicketFormSet( request.POST or None, instances=request.session['tickets'] ) if form.is_valid() and formset.is_valid(): purchase = form.instance purchase.save() for f in formset: purchase.tickets.add(f.instance) return render_to_response( "details.html", dict(form=form, formset=formset), context_instance=RequestContext(request)) def purchase_tickets(request): """ This view displays the form to purchase tickets """ if request.POST: form = TicketPurchaseForm(request.POST) n = int(request.POST['ticket_count']) # Number of ticket. ticket_forms = [TicketForm( request.POST, prefix="ticket%d" % i ) for i in range(n) ] if 'plus' in request.POST: ticket_forms.append( TicketForm( prefix="ticket%d" % len(ticket_forms) ) ) elif 'minus' in request.POST: if len(ticket_forms) > 1: ticket_forms.pop() else: messages.warning(request, 'Your have to buy at least one ticket.') elif form.is_valid() and all( tf.is_valid() for tf in ticket_forms ): purchase = form.save() print ticket_forms for tf in ticket_forms: ticket = tf.save( commit = False ) ticket.purchase = purchase ticket.save() print "ticket saved: %s" % ticket request.session['invoice_id'] = purchase.invoice_id return HttpResponseRedirect('/confirm/') else: form = TicketPurchaseForm() ticket_forms = [ TicketForm( prefix = "ticket0" ) ] # By default, 1 ticket return render_to_response("form.html", { "ticket_types": TicketType.objects.all(), "form": form, "ticket_forms": ticket_forms, }, context_instance=RequestContext(request)) def purchase_required(view): """ This is a decorator that indicates that a view requires a purchase to be in progress to work. """ def _decorator(request, *args, **kwargs): if 'invoice_id' in request.session: purchase = TicketPurchase.objects.get( invoice_id = request.session['invoice_id']) return view(request, purchase, *args, **kwargs) else: messages.error(request, 'Your session has expired.') return redirect('/') return wraps(view)(_decorator) def confirmation(request): """ This view shows the user what she is about to buy """ # Create the paypal url to redirect the user. # This a a bit convoluted because the django app that we use to handle # PayPal payments only generates POST forms to send the user to paypal. # So we have to convert the form to a query string print request.session['purchase'] purchase = TicketPurchase.objects.get(request.session['purchase'].invoice_id) site = Site.objects.get_current() paypal_dict = { "business": "paypal@fscons.org", "amount": purchase.price, "currency_code": "SEK", "item_name": "FSCONS 2013 tickets", "invoice": purchase.invoice_id, "notify_url": "http://%s%s" % (site.domain, reverse('paypal-ipn')), "return_url": "http://%s%s" % (site.domain, reverse('paypal-return')), "cancel_return": "http://%s%s" % (site.domain, reverse('confirm')), } form = PayPalPaymentsForm(initial=paypal_dict) return render_to_response("confirm.html", { "purchase": purchase, "paypal": form, }, context_instance=RequestContext(request)) def success(self): pass def cancel(request): pass @permission_required('ticketapp.view_report') def report(request): data = {} # Total number of tickets tickets = Ticket.objects.filter(purchase__paid = True) data['ticket_total'] = tickets.count() # Tickets by type data['bytype'] = [] for type_ in TicketType.objects.all(): data['bytype'].append( ( unicode(type_), tickets.filter( ticket_type = type_ ).count() ) ) # By day data['by_day'] = [] minmax = TicketPurchase.objects.aggregate(Max('creation_date'), Min('creation_date')) min_day = minmax['creation_date__min'] max_day = minmax['creation_date__max'] if min_day is not None: for day in daterange(min_day, max_day): # we want tickets created in this one day range drange = (day, day + timedelta( days = 1 ) ) # counting the tickets count = tickets.filter( purchase__creation_date__range = drange ).count() data['by_day'].append( (day, count ) ) ## Money data['money'] = {} data['money']['total'] = 0 data['money']['donations'] = 0 for p in TicketPurchase.objects.filter( paid = True ): data['money']['total'] += p.price() data['money']['donations'] += p.additional_contribution data['money']['tickets'] = data['money']['total'] - data['money']['donations'] return render_to_response("report.html", data)
{ "repo_name": "gdetrez/fscons-ticketshop", "path": "ticketshop/ticketapp/views.py", "copies": "1", "size": "7249", "license": "mit", "hash": 8920238330209586000, "line_mean": 36.1743589744, "line_max": 94, "alpha_frac": 0.6166367775, "autogenerated": false, "ratio": 4.065619742007852, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.007485616881691382, "num_lines": 195 }
from functools import wraps from dateutil.relativedelta import relativedelta from django.utils import timezone from rest_framework_captcha.models import Captcha from rest_framework_captcha.helpers import get_settings, get_request_from_args from rest_framework.response import Response from rest_framework.exceptions import ValidationError def protected_view(func): @wraps(func) def wrapper(*args, **kwargs): request = get_request_from_args(*args) uuid = request.META.get("HTTP_X_CAPTCHA_UUID", None) secret = request.META.get("HTTP_X_CAPTCHA_SECRET", None) time_limit = get_settings().get("EXPIRE_IN", 5*60) if not uuid or not secret: return Response({"error": True, "detail": "invalid_captcha_headers", "message": "This view is protected by captcha. You have to set headers X-Captcha-UUID and X-Captcha-Secret with valid values."}, status=400) try: captcha = Captcha.objects.get(uuid=uuid, secret__iexact=secret, fresh=True, created_at__gte=timezone.now() - relativedelta(seconds=time_limit)) except (Captcha.DoesNotExist, ValueError): return Response({"error": True, "detail": "invalid_captcha", "message": "Invalid/expired captcha or incorrect secret."}, status=400) captcha.fresh = False captcha.save() return func(*args, **kwargs) return wrapper
{ "repo_name": "leonardoarroyo/rest-framework-captcha", "path": "rest_framework_captcha/decorators.py", "copies": "1", "size": "1322", "license": "mit", "hash": 111455111478303780, "line_mean": 41.6451612903, "line_max": 215, "alpha_frac": 0.7329803328, "autogenerated": false, "ratio": 3.7988505747126435, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9994382066167289, "avg_score": 0.007489768269070824, "num_lines": 31 }
from functools import wraps from defer import defer as maybe_deferred from pycloudia.reactive.queues import ReactiveQueueScope __all__ = [ 'synchronized', ] class Spec(object): """ :type strategy: C{object} :type scope: C{object} :type args: C{int} :type key: C{str} """ ATTRIBUTE = '__sync__' class STRATEGY(object): LOCK = 'lock' WHEN = 'when' class SCOPE(object): SELF = object() FUNC = object() strategy = None scope = None args = None key = None @classmethod def get_or_create_spec(cls, func): """ :rtype: L{pycloudia.reactive.decorators.Spec} """ if not hasattr(func, cls.ATTRIBUTE): setattr(func, cls.ATTRIBUTE, cls()) return getattr(func, cls.ATTRIBUTE) class Decorator(object): ATTRIBUTE = '__sync_queue__' queue_factory = ReactiveQueueScope @classmethod def create_instance(cls, instance, func, spec, io_loop): return cls(instance, func, spec, io_loop) def __init__(self, instance, func, spec, io_loop): """ :type instance: C{object} :type func: C{Callable} :type spec: L{pycloudia.reactive.synchronized.Spec} """ self.instance = instance self.func = func self.spec = spec self.io_loop = io_loop def __call__(self, *args, **kwargs): """ :rtype: L{defer.Deferred} """ queue = self._get_queue() key = self._create_queue_key(args) if not queue.is_empty(self.spec.key) or (self.spec.strategy is self.spec.STRATEGY.LOCK): return queue.call(self.spec.key, self.func, *args, **kwargs) return maybe_deferred(self.func, *args, **kwargs) def _get_queue(self): """ :rtype: L{pycloudia.reactive.queues.ReactiveQueueScope} :raise: C{ValueError} """ if self.spec.scope is self.spec.SCOPE.FUNC: return self._get_or_create_queue(self.func) elif self.spec.scope is self.spec.SCOPE.SELF: return self._get_or_create_queue(self.instance) else: raise ValueError('Unexpected spec scope: {0}'.format(self.spec.scope)) def _get_or_create_queue(self, scope): """ :type scope: C{object} :rtype: L{pycloudia.reactive.queues.ReactiveQueueScope} """ if not hasattr(scope, self.ATTRIBUTE): setattr(scope, self.ATTRIBUTE, self.queue_factory(self.io_loop)) return getattr(scope, self.ATTRIBUTE) def _create_queue_key(self, args): return '.'.join([self.spec.key] + map(str, args[:self.spec.args])) class Factory(object): decorator_factory = Decorator.create_instance class Self(object): @staticmethod def lock(key=None, args=0): def decorator(func): spec = Spec.get_or_create_spec(func) spec.strategy = spec.STRATEGY.LOCK spec.scope = spec.SCOPE.SELF spec.args = args spec.key = key return func return decorator @staticmethod def when(key=None, args=0): def decorator(func): spec = Spec.get_or_create_spec(func) spec.strategy = spec.STRATEGY.WHEN spec.scope = spec.SCOPE.SELF spec.args = args spec.key = key return func return decorator class Func(object): @staticmethod def lock(key=None): def decorator(func, args=0): spec = Spec.get_or_create_spec(func) spec.strategy = spec.STRATEGY.LOCK spec.scope = spec.SCOPE.FUNC spec.args = args spec.key = key return func return decorator @staticmethod def when(key=None): def decorator(func, args=0): spec = Spec.get_or_create_spec(func) spec.strategy = spec.STRATEGY.WHEN spec.scope = spec.SCOPE.FUNC spec.args = args spec.key = key return func return decorator self = Self() func = Func() @classmethod def patch(cls, instance, io_loop=None): io_loop = io_loop or cls._get_io_loop() for method_name in dir(instance): method = getattr(instance, method_name) try: spec = getattr(method, Spec.ATTRIBUTE) except AttributeError: continue else: decorator = cls.decorator_factory(instance, method, spec, io_loop) decorator = wraps(method)(decorator) setattr(instance, method_name, decorator) return instance @staticmethod def _get_io_loop(): from tornado.ioloop import IOLoop return IOLoop.instance() synchronized = Factory()
{ "repo_name": "cordis/pycloudia", "path": "pycloudia/reactive/synchronized.py", "copies": "1", "size": "5011", "license": "mit", "hash": -5182875564479986000, "line_mean": 27.9653179191, "line_max": 96, "alpha_frac": 0.5533825584, "autogenerated": false, "ratio": 3.9992019154030327, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00019887666989990832, "num_lines": 173 }
from functools import wraps from django.apps import apps from django.conf import settings from django.utils.module_loading import import_string from .channel import MultitenantUser, MultitenantOrg, MultitenantOrgGroup, MultitenantPublicGroup from channels.generic.base import BaseConsumer from channels.message import Message from copy import copy import json #Special permissions SUPER_ADMIN_ONLY = 'SUPER_ADMIN_ONLY' PRACTICE_ADMIN_ONLY = 'PRACTICE_ADMIN_ONLY' NOBODY = 'NOBODY' #used for methods that aren't supported by view. import logging logger = logging.getLogger(__name__) def send_error(message, error_message): message.reply_channel.send({ "text": 'ERROR: {}'.format(error_message), #daphne does not appear to support key 'error'. }) if hasattr(settings, 'MULTITENANT_SOCKETS_PERMISSIONS_ADAPTER'): adapter_module = import_string(settings.MULTITENANT_SOCKETS_PERMISSIONS_ADAPTER) has_role = adapter_module.has_role has_permission = adapter_module.has_permission SUPERADMIN_ROLE_NAME = adapter_module.SUPERADMIN_ROLE_NAME PRACTICEADMIN_ROLE_NAME = adapter_module.PRACTICEADMIN_ROLE_NAME else: from .permissions_adapter import has_role, has_permission, SUPERADMIN_ROLE_NAME, PRACTICEADMIN_ROLE_NAME if hasattr(settings, 'MULTITENANT_SOCKETS_USER_ORG_FK_ATTR_NAME'): user_org_fk_attr_name = getattr(settings, 'MULTITENANT_SOCKETS_USER_ORG_FK_ATTR_NAME') else: user_org_fk_attr_name = 'org' def get_user_org_pk(user): user_org = getattr(user, user_org_fk_attr_name, None) if user_org is not None: return user_org.pk else: return None def connect(): def dec(f): @wraps(f) def wrapper(*args, **kwargs): message = None #find the message parameter. for arg in args: if isinstance(arg, Message): message = arg break if message is not None: try: # user must be authenticated already if message.user.is_authenticated(): orgid = get_user_org_pk(message.user) #add user's reply_channel to user's group MultitenantUser(message.user.pk, orgid).add(message.reply_channel) #Get all public groups the user is a member of and add user's reply_channel to each public group PublicGroup = apps.get_model('django_multitenant_sockets.PublicGroup') public_groups = PublicGroup.objects.filter(members__id=message.user.pk) for public_group in public_groups: MultitenantPublicGroup(public_group.name).add(message.reply_channel) if orgid is not None: #add user's reply_channel to org MultitenantOrg(orgid).add(message.reply_channel) #Get all org groups the user is a member of and add user's reply_channel to each org group OrgGroup = apps.get_model('django_multitenant_sockets.OrgGroup') org_groups = OrgGroup.objects.filter(members__id=message.user.pk, org=orgid) for org_group in org_groups: MultitenantOrgGroup(org_group.name, orgid).add(message.reply_channel) message.reply_channel.send({'accept': True}) return f(*args, **kwargs) else: message.reply_channel.send({'close': True}) return except Exception: message.reply_channel.send({'close': True}) return else: message.reply_channel.send({'close': True}) return return wrapper return dec def disconnect(): def dec(f): @wraps(f) def wrapper(*args, **kwargs): message = None #find the message parameter. for arg in args: if ( hasattr(arg, '__class__') and '{}.{}'.format(arg.__class__.__module__, arg.__class__.__name__) == 'channels.message.Message' ): message = arg break if message is not None: orgid = get_user_org_pk(message.user) multitenant_user = MultitenantUser(message.user.pk, orgid) #for cases where connect() did not add reply channel if message.reply_channel.name in multitenant_user.get_channels(): ret_val = f(*args, **kwargs) #remove user's reply_channel from user's group MultitenantUser(message.user.pk, orgid).discard(message.reply_channel) #Get all public groups the user is a member of and discard user's reply_channel to each public group PublicGroup = apps.get_model('django_multitenant_sockets.PublicGroup') public_groups = PublicGroup.objects.filter(members__id=message.user.pk) for public_group in public_groups: MultitenantPublicGroup(public_group.name).discard(message.reply_channel) if orgid is not None: #remove user's reply_channel from org MultitenantOrg(orgid).discard(message.reply_channel) #Get all org groups the user is a member of and discard user's reply_channel to each org group OrgGroup = apps.get_model('django_multitenant_sockets.OrgGroup') org_groups = OrgGroup.objects.filter(members__id=message.user.pk, org=orgid) for org_group in org_groups: MultitenantOrgGroup(org_group.name, orgid).discard(message.reply_channel) return ret_val return return wrapper return dec def disconnect_if_http_logged_out(): def dec(f): @wraps(f) def wrapper(*args, **kwargs): message = None #find the message parameter. for arg in args: if ( hasattr(arg, '__class__') and '{}.{}'.format(arg.__class__.__module__, arg.__class__.__name__) == 'channels.message.Message' ): message = arg break if message is not None: if message.http_session.get('_auth_user_id', None) is None: if ( hasattr(message, 'user') and message.user is not None ): orgid = get_user_org_pk(message.user) multitenant_user = MultitenantUser(message.user.pk, orgid) #Get all public groups the user is a member of and discard user's reply_channel to each public group PublicGroup = apps.get_model('django_multitenant_sockets.PublicGroup') public_groups = PublicGroup.objects.filter(members__id=message.user.pk) if orgid is not None: #Get all org groups the user is a member of and discard user's reply_channel to each org group OrgGroup = apps.get_model('django_multitenant_sockets.OrgGroup') org_groups = OrgGroup.objects.filter(members__id=message.user.pk, org=orgid) channels = copy(multitenant_user.get_channels()) for channel in channels: #remove channels from user multitenant_user.discard(channel) #remove each user channel from each public group for public_group in public_groups: MultitenantPublicGroup(public_group.name).discard(channnel) if orgid is not None: #remove each user channel from org MultitenantOrg(orgid).discard(channel) #remove each user channel from each org group for org_group in org_groups: MultitenantOrgGroup(org_group.name, orgid).discard(message.reply_channel) #close each user channel message.reply_channel.send({'close': True}) return else: #session _auth_user_id set return f(*args, **kwargs) return return wrapper return dec def has_permission_and_org(op_to_permission_name_map): def dec(f): @wraps(f) def wrapper(*args, **kwargs): message = None for arg in args: if isinstance(arg, Message): message = arg break if isinstance(arg, BaseConsumer): message = arg.message break if message is not None: user = message.user text_dict = json.loads(message.content['text']) for_org = text_dict.get('for_org', None) op = text_dict.get('op', None) #location for genericconsumer if op is None: payload = text_dict.get('payload', None) if payload is not None: op = payload.get('op', None) #location for consumer for_org = payload.get('for_org', None) if op is None: #require an op send_error(message, 'no op provided') return else: permission_name = op_to_permission_name_map.get(op, None) if permission_name is None: send_error(message, 'no permission for op') return if is_authorized(user, for_org, permission_name): return f(*args, **kwargs) else: send_error(message, 'not authorized') return else: logger.error('has_permission_and_org called but couldn\'t find a message param') return return wrapper return dec def is_authorized(user, for_org, permission_name): if user.is_authenticated(): user_org = get_user_org_pk(user) if has_role(user, SUPERADMIN_ROLE_NAME): return True elif permission == SUPER_ADMIN_ONLY: return False elif ((for_org is not None) and (user_org == for_org)) or (for_org is None): if for_org and for_org.is_inactive: return False elif has_role(user, ORGADMIN_ROLE_NAME): return True elif permission == ORG_ADMIN_ONLY: return False elif has_permission(user, permission_name): return True else: return False else: return False else: return False
{ "repo_name": "russellmorley/django_multitenant", "path": "django_multitenant_sockets/decorators.py", "copies": "1", "size": "9752", "license": "mit", "hash": -8154327667495264000, "line_mean": 37.6984126984, "line_max": 112, "alpha_frac": 0.6247949139, "autogenerated": false, "ratio": 3.9950839819746005, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.51198788958746, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.contrib import messages import requests def check_recaptcha(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): debug = kwargs.get('debug', False) request.recaptcha_is_valid = None if request.method == 'POST': recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if debug and data.get('response') == settings.GOOGLE_RECAPTCHA_RESPONSE_TEST: result['success'] = True if result['success']: request.recaptcha_is_valid = True messages.success(request, 'Success. Thanks for voting. You can vote as many times as you want my dear ' 'troll! 🙈', extra_tags='alert alert-success') else: request.recaptcha_is_valid = False messages.error(request, 'Invalid reCAPTCHA. Please check the reCAPTCHA at the end of this site and ' 'verify you are human! 🤖', extra_tags='alert alert-danger') return view_func(request, *args, **kwargs) return _wrapped_view
{ "repo_name": "guiem/metaphor", "path": "metaphor/decorators.py", "copies": "1", "size": "1474", "license": "mit", "hash": -5061337383267352000, "line_mean": 44.875, "line_max": 119, "alpha_frac": 0.5824250681, "autogenerated": false, "ratio": 4.1120448179271705, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5194469886027171, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.http import HttpResponseBadRequest from django.template.loader import render_to_string def honeypot_equals(val): """ Default verifier used if HONEYPOT_VERIFIER is not specified. Ensures val == HONEYPOT_VALUE or HONEYPOT_VALUE() if it's a callable. """ expected = getattr(settings, "HONEYPOT_VALUE", "") if callable(expected): expected = expected() return val == expected def verify_honeypot_value(request, field_name): """ Verify that request.POST[field_name] is a valid honeypot. Ensures that the field exists and passes verification according to HONEYPOT_VERIFIER. """ verifier = getattr(settings, "HONEYPOT_VERIFIER", honeypot_equals) if request.method == "POST": field = field_name or settings.HONEYPOT_FIELD_NAME if field not in request.POST or not verifier(request.POST[field]): resp = render_to_string( "honeypot/honeypot_error.html", {"fieldname": field} ) return HttpResponseBadRequest(resp) def check_honeypot(func=None, field_name=None): """ Check request.POST for valid honeypot field. Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if not specified. """ # hack to reverse arguments if called with str param if isinstance(func, str): func, field_name = field_name, func def decorated(func): def inner(request, *args, **kwargs): response = verify_honeypot_value(request, field_name) if response: return response else: return func(request, *args, **kwargs) return wraps(func)(inner) if func is None: def decorator(func): return decorated(func) return decorator return decorated(func) def honeypot_exempt(view_func): """ Mark view as exempt from honeypot validation """ # borrowing liberally from django's csrf_exempt def wrapped(*args, **kwargs): return view_func(*args, **kwargs) wrapped.honeypot_exempt = True return wraps(view_func)(wrapped)
{ "repo_name": "jamesturk/django-honeypot", "path": "honeypot/decorators.py", "copies": "1", "size": "2191", "license": "bsd-2-clause", "hash": -1573867982530307000, "line_mean": 28.6081081081, "line_max": 74, "alpha_frac": 0.6508443633, "autogenerated": false, "ratio": 3.933572710951526, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5084417074251526, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings from django.http import HttpResponseForbidden, JsonResponse from django.shortcuts import redirect from djing.lib import check_sign # Allow to view only admins def only_admins(fn): @wraps(fn) def wrapped(request, *args, **kwargs): if request.user.is_admin: return fn(request, *args, **kwargs) else: return redirect('client_side:home') return wrapped # hash auth for functional views def hash_auth_view(fn): @wraps(fn) def wrapped(request, *args, **kwargs): api_auth_secret = getattr(settings, 'API_AUTH_SECRET') sign = request.GET.get('sign') if sign is None or sign == '': return HttpResponseForbidden('Access Denied') # Transmittent get list without sign get_values = request.GET.copy() del get_values['sign'] values_list = [l for l in get_values.values() if l] values_list.sort() values_list.append(api_auth_secret) if check_sign(values_list, sign): return fn(request, *args, **kwargs) else: return HttpResponseForbidden('Access Denied') return wrapped # Lazy initialize metaclass class LazyInitMetaclass(type): """ Type this metaclass if you want to make your object with lazy initialize. Method __init__ called only when you try to call something method from object of your class. """ def __new__(mcs, name: str, bases: tuple, attrs: dict): new_class_new = super(LazyInitMetaclass, mcs).__new__ def _lazy_call_decorator(fn): def wrapped(self, *args, **kwargs): if not self._is_initialized: self._lazy_init(*self._args, **self._kwargs) return fn(self, *args, **kwargs) return wrapped # Apply decorator to all public class methods new_attrs = {k: _lazy_call_decorator(v) for k, v in attrs.items() if not k.startswith('__') and not k.endswith('__') and callable(v)} if new_attrs: attrs.update(new_attrs) attrs['_is_initialized'] = False new_class = new_class_new(mcs, name, bases, attrs) real_init = getattr(new_class, '__init__') def _lazy_init(self, *args, **kwargs): self._args = args self._kwargs = kwargs setattr(new_class, '__init__', _lazy_init) setattr(new_class, '_lazy_init', real_init) return new_class # Wraps return data to JSON def json_view(fn): @wraps(fn) def wrapped(request, *args, **kwargs): r = fn(request, *args, **kwargs) if isinstance(r, dict) and not isinstance(r.get('text'), str): r['text'] = str(r.get('text')) return JsonResponse(r, safe=False, json_dumps_params={ 'ensure_ascii': False }) return wrapped
{ "repo_name": "bashmak/djing", "path": "djing/lib/decorators.py", "copies": "2", "size": "2900", "license": "unlicense", "hash": 3332037096072028700, "line_mean": 31.5842696629, "line_max": 141, "alpha_frac": 0.6020689655, "autogenerated": false, "ratio": 3.9030955585464335, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5505164524046433, "avg_score": null, "num_lines": null }
from functools import wraps from django.conf import settings import requests def check_recaptcha(view_func): """Chech that the entered recaptcha data is correct""" @wraps(view_func) def _wrapped_view(request, *args, **kwargs): request.recaptcha_is_valid = None if request.method == 'POST': recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post( 'https://www.google.com/recaptcha/api/siteverify', data=data ) result = r.json() if result['success']: request.recaptcha_is_valid = True else: request.recaptcha_is_valid = False error_message = 'Invalid reCAPTCHA. Please try again. ' error_message += str(result['error-codes']) print(error_message) return view_func(request, *args, **kwargs) return _wrapped_view
{ "repo_name": "lotrekagency/djlotrek", "path": "djlotrek/decorators.py", "copies": "1", "size": "1107", "license": "mit", "hash": -183340000744580380, "line_mean": 34.7096774194, "line_max": 73, "alpha_frac": 0.5609756098, "autogenerated": false, "ratio": 4.193181818181818, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5254157427981818, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib.auth.backends import ModelBackend from django.shortcuts import render from django.conf import settings from django.core.urlresolvers import reverse from jmbovlive.utils import pml_redirect_timer_view def pin_required(function): """ Decorator to ask people to verify their pin before being able to access a view. """ @wraps(function) def wrapper(request, *args, **kwargs): msisdn = request.META.get('HTTP_X_UP_CALLING_LINE_ID', None) if not msisdn: return function(request, *args, **kwargs) auth_backend = ModelBackend() if request.session.get(settings.UMMELI_PIN_SESSION_KEY): return function(request, *args, **kwargs) if request.user.password: return pml_redirect_timer_view(request, settings.LOGIN_URL, redirect_time = 0, redirect_message = 'You need to login first.') else: return pml_redirect_timer_view(request, reverse('register'), redirect_time = 0, redirect_message = 'You need to create a pin first.') return wrapper def phone_number_to_international(phone_number): if phone_number.startswith('27') and len(phone_number) == 11: return phone_number elif phone_number.startswith('0') and len(phone_number) == 10: return '27' + phone_number[1:] else: return 'invalid no' def process_post_data_username(post): """ converts username(phone number) to valid international phone number (27821234567) """ if not post.get('username', None): return post post_data = post.copy() post_data['username'] = phone_number_to_international(post_data['username']) return post_data from PIL import Image from PIL.ExifTags import TAGS, GPSTAGS def get_exif_data(file): exif_data = {} file.open() with file as f: image = Image.open(f) """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags""" info = image._getexif() if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "GPSInfo": gps_data = {} for t in value: sub_decoded = GPSTAGS.get(t, t) gps_data[sub_decoded] = value[t] exif_data[decoded] = gps_data else: exif_data[decoded] = value return exif_data def _convert_to_degress(value): """Helper function to convert the GPS coordinates stored in the EXIF to degress in float format""" d0 = value[0][0] d1 = value[0][1] d = float(d0) / float(d1) m0 = value[1][0] m1 = value[1][1] m = float(m0) / float(m1) s0 = value[2][0] s1 = value[2][1] s = float(s0) / float(s1) return d + (m / 60.0) + (s / 3600.0) def get_lat_lon(file): exif_data = get_exif_data(file) """Returns the latitude and longitude, if available, from the provided exif_data (obtained through get_exif_data above)""" lat = None lon = None if "GPSInfo" in exif_data: gps_info = exif_data["GPSInfo"] gps_latitude = gps_info.get('GPSLatitude', None) gps_latitude_ref = gps_info.get('GPSLatitudeRef', None) gps_longitude = gps_info.get('GPSLongitude', None) gps_longitude_ref = gps_info.get('GPSLongitudeRef', None) if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref: lat = _convert_to_degress(gps_latitude) if gps_latitude_ref != "N": lat = 0 - lat lon = _convert_to_degress(gps_longitude) if gps_longitude_ref != "E": lon = 0 - lon return lat, lon
{ "repo_name": "praekelt/ummeli", "path": "ummeli/vlive/utils.py", "copies": "1", "size": "3866", "license": "bsd-3-clause", "hash": -803229734224592600, "line_mean": 31.7627118644, "line_max": 126, "alpha_frac": 0.5949301604, "autogenerated": false, "ratio": 3.57631822386679, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.467124838426679, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.views import login from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from api.processors import get_event_by_id from web.processors.user import get_user_profile def can_edit_event(func): def decorator(request, *args, **kwargs): event = get_event_by_id(kwargs['event_id']) if request.user.id == event.creator.id: return func(request, *args, **kwargs) else: return HttpResponseRedirect(reverse('web.index')) return decorator def can_moderate_event(func): def decorator(request, *args, **kwargs): event = get_event_by_id(kwargs['event_id']) user = get_user_profile(request.user.id) if user.is_ambassador(): return func(request, *args, **kwargs) else: return HttpResponseRedirect(reverse('web.index')) return decorator def is_ambassador(func): def decorator(request, *args, **kwargs): user = get_user_profile(request.user.id) if user.is_ambassador(): return func(request, *args, **kwargs) else: return HttpResponseRedirect(reverse('web.index')) return decorator def login_required_ajax(function=None, redirect_field_name=None): """ Just make sure the user is authenticated to access a certain ajax view Otherwise return a HttpResponse 401 - authentication required instead of the 302 redirect of the original Django decorator """ def _decorator(view_func): def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) else: print 'open modal' # return HttpResponse(status=401) return _wrapped_view if function: return _decorator(function) return _decorator def login_required(view_callable): def check_login(request, *args, **kwargs): if request.user.is_authenticated(): return view_callable(request, *args, **kwargs) assert hasattr(request, 'session'), 'Session middleware needed.' login_kwargs = { 'extra_context': { REDIRECT_FIELD_NAME: request.get_full_path(), 'modal': True, }, } # return login(request, template_name='pages/add_event.html', # **login_kwargs) request.session['modal'] = True return HttpResponseRedirect(reverse('web.index')) return wraps(view_callable)(check_login)
{ "repo_name": "michelesr/coding-events", "path": "web/decorators/events.py", "copies": "2", "size": "2654", "license": "mit", "hash": 6155014316431317000, "line_mean": 29.5057471264, "line_max": 74, "alpha_frac": 0.6345139412, "autogenerated": false, "ratio": 4.192733017377567, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5827246958577568, "avg_score": null, "num_lines": null }
from functools import wraps from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from .models import ApiKey def api_key_required(): def deny(request): raise PermissionDenied def decorator(view_function): @wraps(view_function) def _inner(request, *args, **kwargs): if "HTTP_X_AUTHORIZATION" not in request.META: deny(request) # X-AUTHORIZATION: user api_key authorization = request.META["HTTP_X_AUTHORIZATION"] user = authorization.split(" ", 1)[0] key = authorization.split(" ", 1)[1] if not User.objects.filter(username=user).exists(): deny(request) user_object = User.objects.get(username=user) if not ApiKey.objects.filter(user=user_object).exists(): deny(request) api_key = ApiKey.objects.get(user=user_object).key if len(api_key) != len(key): deny(request) result = True for x, y in zip(api_key, key): if x != y: result = False if not result: deny(request) return view_function(request, *args, **kwargs) return _inner return decorator
{ "repo_name": "ConstellationApps/Forms", "path": "constellation_forms/util.py", "copies": "1", "size": "1323", "license": "isc", "hash": -2771644907743923000, "line_mean": 28.4, "line_max": 68, "alpha_frac": 0.5616024187, "autogenerated": false, "ratio": 4.281553398058253, "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.contrib.auth.models import User from django.test.testcases import TestCase from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium.common.exceptions import TimeoutException, NoSuchElementException, StaleElementReferenceException from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait def retry(func): # noqa C901 @wraps(func) def retry_test(self, countdown=30, *args, **kwargs): try: result = func(self, *args, **kwargs) except Exception: if countdown <= 0: raise self.tearDown() self._post_teardown() self._pre_setup() self.setUp() result = retry_test(self, countdown=countdown - 1, *args, **kwargs) return result return retry_test class Retry(type): def __new__(cls, name, bases, attrs): for test in filter(lambda i: i.startswith('test_'), attrs): attrs[test] = retry(attrs[test]) return super(Retry, cls).__new__(cls, name, bases, attrs) class AjaxAdminTests(TestCase, StaticLiveServerTestCase): __metaclass__ = Retry fixtures = ['initial_data.json'] @classmethod def setUpClass(cls): super(AjaxAdminTests, cls).setUpClass() caps = webdriver.DesiredCapabilities.CHROME caps['platform'] = 'Windows XP' caps['version'] = '31' caps['name'] = 'django-admin-ext' cls.driver = webdriver.Remote( desired_capabilities=caps, command_executor=( "http://imtappswebadmin:841f95a0-c21d-4cb4-a7f4-288ed88a4b18@ondemand.saucelabs.com:80/wd/hub" ) ) cls.driver.implicitly_wait(30) @classmethod def tearDownClass(cls): print("Link to your job: https://saucelabs.com/jobs/%s" % cls.driver.session_id) cls.driver.quit() def setUp(self): list(User.objects.all()) self.login() def _get_element(self, context, method, argument): return getattr(context, method)(argument) def find_element(self, context=None, name=None, selector=None, tag=None): # noqa C901 argument = name or selector or tag context = context or self.driver if name: method = 'find_element_by_name' elif selector: method = 'find_element_by_css_selector' elif tag: method = 'find_elements_by_tag_name' else: raise Exception("No Selector") WebDriverWait(context, 60, 1).until(lambda d: self._get_element(d, method, argument)) return self._get_element(context, method, argument) def click_element(self, **kwargs): element = self.find_element(**kwargs) element.click() def login(self): self.driver.get("%s/admin/" % self.live_server_url) # new_user = User.objects.create_user(username='admin', is_superuser=True, is_staff=True) # new_user.set_password('test') # new_user.save() user = self.find_element(selector='#id_username') user.send_keys("admin") pswd = self.find_element(selector='#id_password') pswd.send_keys("test") self.click_element(selector=".submit-row>[type='submit']") def assert_selected_option(self, element_id, value): option = self.find_element(selector='#' + element_id + ' option[selected]') self.assertEqual(value, option.text) def assert_select_has_options(self, element_id, expected_ingredients): details = self.find_element(selector='#' + element_id) options = self.find_element(context=details, tag='option') self.assertCountEqual(expected_ingredients, [o.text for o in options]) def change_value_for_element(self, element_id, value): element = self.find_element(selector='#' + element_id) element.send_keys(value) # click off of the element to trigger the change event try: self.click_element(selector='label[for="' + element_id + '"]') except Exception: pass def test_main_ingredient_element_not_present_initially(self): self.driver.get("%s/admin/sample/meal/add/" % self.live_server_url) self.find_element(selector='#id_food_type') with self.assertRaises(TimeoutException): self.find_element(selector='#id_main_ingredient') def test_main_ingredient_element_shows_when_pizza_food_type_is_selected(self): self.driver.get("%s/admin/sample/meal/add/" % self.live_server_url) self.change_value_for_element('id_food_type', 'pizza') self.assert_select_has_options( 'id_main_ingredient', [u'---------', u'pepperoni', u'mushrooms', u'beef', u'anchovies'] ) def test_main_ingredient_element_shows_when_burger_food_type_is_selected(self): self.driver.get("%s/admin/sample/meal/add/" % self.live_server_url) self.change_value_for_element('id_food_type', 'burger') self.assert_select_has_options('id_main_ingredient', [u'---------', u'mushrooms', u'beef', u'lettuce']) def test_ingredient_details_is_shown_when_beef_is_selected(self): self.driver.get("%s/admin/sample/meal/add/" % self.live_server_url) self.change_value_for_element('id_food_type', 'burger') self.change_value_for_element('id_main_ingredient', 'beef') self.assert_select_has_options('id_ingredient_details', [u'---------', u'Grass Fed', u'Cardboard Fed']) def test_ingredient_details_is_reset_when_main_ingredient_changes(self): self.driver.get("%s/admin/sample/meal/add/" % self.live_server_url) self.change_value_for_element('id_food_type', 'burger') self.change_value_for_element('id_main_ingredient', 'beef') details = self.find_element(selector='#id_ingredient_details') self.assertTrue(details.is_displayed()) self.change_value_for_element('id_main_ingredient', 'lettuce') try: self.find_element(selector='#id_ingredient_details') except (NoSuchElementException, TimeoutException, StaleElementReferenceException): pass else: self.fail("Expected not to find #id_ingredient_details") def test_ingredient_details_change_when_main_ingredient_changes(self): self.driver.get("%s/admin/sample/meal/add/" % self.live_server_url) self.change_value_for_element('id_food_type', 'pizza') self.change_value_for_element('id_main_ingredient', 'beef') self.assert_select_has_options('id_ingredient_details', [u'---------', u'Grass Fed', u'Cardboard Fed']) self.change_value_for_element('id_main_ingredient', 'pepperoni') self.assert_select_has_options( 'id_ingredient_details', [u'---------', u'Grass Fed Goodness', u'Cardboard Not So Goodness'] ) def test_main_ingredient_does_not_change_when_food_type_changes_if_valid_option(self): self.driver.get("%s/admin/sample/meal/add/" % self.live_server_url) self.change_value_for_element('id_food_type', 'pizza') self.change_value_for_element('id_main_ingredient', 'beef') self.assert_selected_option('id_main_ingredient', 'beef') self.change_value_for_element('id_food_type', 'burger') self.assert_selected_option('id_main_ingredient', 'beef') def test_shows_dynamic_field_on_existing_instance(self): self.driver.get("%s/admin/sample/meal/1/" % self.live_server_url) self.assert_selected_option('id_main_ingredient', 'anchovies') def test_sets_ingredient_details_when_available(self): self.driver.get("%s/admin/sample/meal/add/" % self.live_server_url) self.change_value_for_element('id_food_type', 'burger') self.change_value_for_element('id_main_ingredient', 'beef') self.change_value_for_element('id_ingredient_details', 'Grass Fed') self.click_element(name='_continue') self.assert_selected_option('id_ingredient_details', 'Grass Fed') def test_allows_changing_dynamic_field_on_existing_instance(self): self.driver.get("%s/admin/sample/meal/add/" % self.live_server_url) self.change_value_for_element('id_food_type', 'burger') # create new meal main_ingredient = self.find_element(selector='#id_main_ingredient') main_ingredient.send_keys('mushrooms') self.click_element(name='_continue') # change main_ingredient for new meal main_ingredient2 = self.find_element(selector='#id_main_ingredient') main_ingredient2.send_keys('lettuce') self.click_element(name='_continue') # make sure there are no errors with self.assertRaises(TimeoutException): self.find_element(selector=".errors") # make sure our new main_ingredient was saved self.assert_selected_option('id_main_ingredient', 'lettuce') # delete our meal when we're done self.click_element(selector='.deletelink') self.click_element(selector='[type="submit"]') def test_gives_field_required_error_when_dynamic_field_not_chosen(self): self.driver.get("%s/admin/sample/meal/add/" % self.live_server_url) food_type = self.find_element(selector='#id_food_type') food_type.send_keys('burger') self.click_element(name='_save') error_item = self.find_element(selector=".errors.field-main_ingredient li") self.assertEqual("This field is required.", error_item.text)
{ "repo_name": "imtapps/django-admin-ext", "path": "example/sample/tests.py", "copies": "1", "size": "9590", "license": "bsd-2-clause", "hash": 832694896334177400, "line_mean": 39.4641350211, "line_max": 111, "alpha_frac": 0.643274244, "autogenerated": false, "ratio": 3.482207697893972, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4625481941893972, "avg_score": null, "num_lines": null }
from functools import wraps from django.core.cache import cache from django.http import HttpRequest from django.utils.cache import get_cache_key from django.views.decorators.cache import cache_page from django.utils.decorators import available_attrs TIME_TO_CACHE = 172800 # 2 days * 24 hours * 60 minutes * 60 seconds = 172800 def expire_page(path): request = HttpRequest() request.path = path key = get_cache_key(request) if key and cache.has_key(key): cache.delete(key) def cache_page_in_group(group): def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): key_prefix = get_group_key(group) return cache_page(TIME_TO_CACHE, key_prefix=key_prefix)(view_func)(request, *args, **kwargs) return _wrapped_view return decorator def get_group_key(group): key = cache.get("cache_group_" + str(group), 1) return str(group) + str(key) def expire_cache_group(group): group_key = "cache_group_" + str(group) value = int(cache.get(group_key, 1)) + 1 cache.set(group_key, value, TIME_TO_CACHE) return value
{ "repo_name": "cfpb/django-cache-tools", "path": "cache_tools/tools.py", "copies": "1", "size": "1176", "license": "cc0-1.0", "hash": 6173417796989011000, "line_mean": 33.5882352941, "line_max": 104, "alpha_frac": 0.6836734694, "autogenerated": false, "ratio": 3.398843930635838, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4582517400035838, "avg_score": null, "num_lines": null }
from functools import wraps from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponseBadRequest from django.shortcuts import redirect from django.core.urlresolvers import reverse from models import CanvasApiToken import logging log = logging.getLogger(__name__) def api_token_required(completed_view=None): def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): # handle request from existing consumer session if 'CANVAS_API_OAUTH_TOKEN' in request.session: return view_func(request, *args, **kwargs) # handle loading existing token based on username try: token = CanvasApiToken.objects.get(user=request.user) request.session['CANVAS_API_OAUTH_TOKEN'] = token.token return view_func(request, *args, **kwargs) except CanvasApiToken.DoesNotExist, e: pass if request.method != 'POST': log.error("Invalid request. Token generation can only " \ + "happen at lti launch.") return HttpResponseBadRequest() # get the registered developer key client_id for this consumer and # save it so we can look up the client id/secret in the next step consumer_key = request.POST.get('oauth_consumer_key', None) request.session['OAUTH_CONSUMER_KEY'] = consumer_key request.session['CANVAS_API_TOKEN_COMPLETE_REDIRECT_VIEW'] = \ completed_view or view_func.__name__ # initiate token generation return redirect(reverse('token_init')) return _wrapped_view return decorator
{ "repo_name": "harvard-dce/django-canvas-api-token", "path": "canvas_api_token/decorators.py", "copies": "1", "size": "1762", "license": "bsd-3-clause", "hash": 1999605474783461000, "line_mean": 38.1555555556, "line_max": 78, "alpha_frac": 0.6333711691, "autogenerated": false, "ratio": 4.624671916010499, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0012669406995648132, "num_lines": 45 }
from functools import wraps from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse_lazy from django.utils.decorators import available_attrs from django.shortcuts import redirect from django_auth_lti import const from .verification import has_roles, has_course_authorization def role_required(allowed_roles, redirect_url=reverse_lazy("not_authorized"), raise_exception=False): def decorator(view): @wraps(view, assigned=available_attrs(view)) def _wrapper(request, *args, **kwargs): if has_roles(request, allowed_roles): return view(request, *args, **kwargs) if raise_exception: raise PermissionDenied return redirect(redirect_url) return _wrapper return decorator def course_authorization_required(**decorator_kwargs): def decorator(view): source = decorator_kwargs.get('source', None) valid_sources = ('arguments', 'query') if not (source in valid_sources): raise Exception("invalid source: %s" % source) @wraps(view, assigned=available_attrs(view)) def _wrapper(request, *args, **kwargs): course_id = None if source == valid_sources[0]: argname = decorator_kwargs.get('argname', 'course_id') course_id = kwargs.get(argname, None) elif source == valid_sources[1]: method = decorator_kwargs.get('method', 'GET') param = decorator_kwargs.get('param', 'course_id') course_id = getattr(request, method).get(param, None) if not has_course_authorization(request, course_id): raise PermissionDenied return view(request, *args, **kwargs) return _wrapper return decorator
{ "repo_name": "Harvard-ATG/HarmonyLab", "path": "lab/decorators.py", "copies": "1", "size": "1834", "license": "bsd-3-clause", "hash": -1407640723515863600, "line_mean": 40.7045454545, "line_max": 101, "alpha_frac": 0.6374045802, "autogenerated": false, "ratio": 4.462287104622871, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5599691684822872, "avg_score": null, "num_lines": null }
from functools import wraps from django.core.exceptions import PermissionDenied from django.http import HttpResponseRedirect from django.template.response import TemplateResponse class ImproperResponse(Exception): "An unexpected response type was returned from the view" pass def redirect_on_deny(redirect_uri): def redirect(response): redirect = HttpResponseRedirect(redirect_uri) response.status_code = redirect.status_code response['Location'] = redirect['Location'] return response return redirect def render_on_deny(template_name): def rerender(response): response.template_name = template_name return response return rerender def raise_on_deny(response): raise PermissionDenied def protect(view, permission_check, permission_denied=raise_on_deny, template_object_name=None): @wraps(view) def wrapped(request, *args, **kwargs): response = view(request, *args, **kwargs) if response.status_code != 200: # Redirects, errors, etc. should pass through. return response # Can't handle non-template responses if not isinstance(response, TemplateResponse): raise ImproperResponse('Protected view must return' ' a TemplateResponse object') if template_object_name is None: content_object = view.get_object() else: content_object = response.context_data[template_object_name] if not permission_check(request, content_object): return permission_denied(response) else: return response return wrapped
{ "repo_name": "armstrong/armstrong.core.arm_access", "path": "armstrong/core/arm_access/paywalls/base.py", "copies": "1", "size": "1716", "license": "apache-2.0", "hash": -5927317961680231000, "line_mean": 28.0847457627, "line_max": 72, "alpha_frac": 0.6567599068, "autogenerated": false, "ratio": 4.820224719101123, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5976984625901123, "avg_score": null, "num_lines": null }
from functools import wraps from django.core.exceptions import PermissionDenied, ObjectDoesNotExist def is_creator_permission_required(model, pk_name='pk'): def decorator(view_func): def wrap(request, *args, **kwargs): pk = kwargs.get(pk_name, None) if pk is None: raise RuntimeError('decorator requires pk argument to be set (got {} instead)'.format(kwargs)) is_creator_func = getattr(model, 'is_creator', None) if is_creator_func is None: raise RuntimeError('decorator requires model {} to provide is_owner function)'.format(model)) o=model.objects.get(pk=pk) #raises ObjectDoesNotExist if o.is_creator(request.user): return view_func(request, *args, **kwargs) else: raise PermissionDenied return wraps(view_func)(wrap) return decorator def public_or_admin_permission_required(model, pk_name='pk'): def decorator(view_func): def wrap(request, *args, **kwargs): pk = kwargs.get(pk_name, None) if pk is None: raise RuntimeError('decorator requires pk argument to be set (got {} instead)'.format(kwargs)) is_creator_func = getattr(model, 'is_creator', None) if is_creator_func is None: raise RuntimeError('decorator requires model {} to provide is_owner function)'.format(model)) o=model.objects.get(pk=pk) #raises ObjectDoesNotExist if o.private == False or o.is_admin(request.user): return view_func(request, *args, **kwargs) else: raise PermissionDenied return wraps(view_func)(wrap) return decorator ### Deprecated def public_or_creator_permission_required(model, pk_name='pk'): def decorator(view_func): def wrap(request, *args, **kwargs): pk = kwargs.get(pk_name, None) if pk is None: raise RuntimeError('decorator requires pk argument to be set (got {} instead)'.format(kwargs)) is_creator_func = getattr(model, 'is_creator', None) if is_creator_func is None: raise RuntimeError('decorator requires model {} to provide is_owner function)'.format(model)) o=model.objects.get(pk=pk) #raises ObjectDoesNotExist if o.private == False or o.is_creator(request.user): return view_func(request, *args, **kwargs) else: raise PermissionDenied return wraps(view_func)(wrap) return decorator
{ "repo_name": "actionpods/django-action-hub", "path": "hub/views/decorators/permissions.py", "copies": "1", "size": "2605", "license": "apache-2.0", "hash": 5706137170220467000, "line_mean": 47.2407407407, "line_max": 110, "alpha_frac": 0.6107485605, "autogenerated": false, "ratio": 4.348914858096828, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.006257140379534739, "num_lines": 54 }
from functools import wraps from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import get_object_or_404 from sentry.conf import settings from sentry.models import Project, Team, Group from sentry.web.helpers import get_project_list, render_to_response, \ get_login_url, get_team_list def has_access(group_or_func=None): """ Tests and transforms project_id for permissions based on the requesting user. Passes the actual project instance to the decorated view. The default permission scope is 'user', which allows both 'user' and 'owner' access, but not 'system agent'. >>> @has_access(MEMBER_OWNER) >>> def foo(request, project): >>> return >>> @has_access >>> def foo(request, project): >>> return """ if callable(group_or_func): return has_access(None)(group_or_func) def wrapped(func): @wraps(func) def _wrapped(request, project_id=None, *args, **kwargs): # If we're asking for anything other than implied access, the user # must be authenticated if group_or_func and not request.user.is_authenticated(): request.session['_next'] = request.build_absolute_uri() return HttpResponseRedirect(get_login_url()) # XXX: if project_id isn't set, should we only allow superuser? if not project_id: return func(request, None, *args, **kwargs) if project_id.isdigit(): lookup_kwargs = {'id': int(project_id)} else: lookup_kwargs = {'slug': project_id} if request.user.is_superuser: if project_id: try: project = Project.objects.get_from_cache(**lookup_kwargs) except Project.DoesNotExist: if project_id.isdigit(): # It could be a numerical slug try: project = Project.objects.get_from_cache(slug=project_id) except Project.DoesNotExist: return HttpResponseRedirect(reverse('sentry')) else: return HttpResponseRedirect(reverse('sentry')) else: project = None return func(request, project, *args, **kwargs) if project_id: key, value = lookup_kwargs.items()[0] project_list = get_project_list(request.user, group_or_func, key=key) try: project = project_list[value] except (KeyError, ValueError): return HttpResponseRedirect(reverse('sentry')) else: project = None return func(request, project, *args, **kwargs) return _wrapped return wrapped def has_team_access(group_or_func=None): """ Tests and transforms team_id for permissions based on the requesting user. Passes the actual project instance to the decorated view. The default permission scope is 'user', which allows both 'user' and 'owner' access, but not 'system agent'. >>> @has_team_access(MEMBER_OWNER) >>> def foo(request, team): >>> return >>> @has_team_access >>> def foo(request, team): >>> return """ if callable(group_or_func): return has_team_access(None)(group_or_func) def wrapped(func): @wraps(func) def _wrapped(request, team_slug, *args, **kwargs): if request.user.is_superuser: try: team = Team.objects.get_from_cache(slug=team_slug) except Team.DoesNotExist: return HttpResponseRedirect(reverse('sentry')) return func(request, team, *args, **kwargs) team_list = get_team_list(request.user, group_or_func) try: team = team_list[team_slug] except (KeyError, ValueError): return HttpResponseRedirect(reverse('sentry')) return func(request, team, *args, **kwargs) return _wrapped return wrapped def has_group_access(func): """ Tests and transforms project_id and group_id for permissions based on the requesting user. Passes the actual project and group instances to the decorated view. >>> @has_group_access >>> def foo(request, project, group): >>> return """ prv_func = login_required(has_access(func)) @wraps(func) def wrapped(request, project_id, group_id, *args, **kwargs): group = get_object_or_404(Group, pk=group_id) if group.project and project_id not in (group.project.slug, str(group.project.id)): return HttpResponse(status=404) if group.is_public: return func(request, group.project, group, *args, **kwargs) return prv_func(request, group.project.slug, group, *args, **kwargs) return wrapped def login_required(func): @wraps(func) def wrapped(request, *args, **kwargs): if not settings.PUBLIC: if not request.user.is_authenticated(): request.session['_next'] = request.build_absolute_uri() return HttpResponseRedirect(get_login_url()) return func(request, *args, **kwargs) return wrapped def requires_admin(func): @wraps(func) def wrapped(request, *args, **kwargs): if not request.user.is_authenticated(): request.session['_next'] = request.build_absolute_uri() return HttpResponseRedirect(get_login_url()) if not request.user.is_staff: return render_to_response('sentry/missing_permissions.html', status=400) return func(request, *args, **kwargs) return wrapped def permission_required(perm): def wrapped(func): @wraps(func) def _wrapped(request, *args, **kwargs): if not request.user.is_authenticated(): request.session['_next'] = request.build_absolute_uri() return HttpResponseRedirect(get_login_url()) if not request.user.has_perm(perm): return render_to_response('sentry/missing_permissions.html', status=400) return func(request, *args, **kwargs) return _wrapped return wrapped
{ "repo_name": "alex/sentry", "path": "sentry/web/decorators.py", "copies": "1", "size": "6506", "license": "bsd-3-clause", "hash": 5035632313834686000, "line_mean": 34.9447513812, "line_max": 91, "alpha_frac": 0.5848447587, "autogenerated": false, "ratio": 4.419836956521739, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00038013461986187197, "num_lines": 181 }
from functools import wraps from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import get_object_or_404 from sentry.models import Project, Team, Group from sentry.web.helpers import ( render_to_response, get_login_url) def has_access(access_or_func=None, team=None, access=None): """ Tests and transforms project_id for permissions based on the requesting user. Passes the actual project instance to the decorated view. The default permission scope is 'user', which allows both 'user' and 'owner' access, but not 'system agent'. >>> @has_access(MEMBER_OWNER) >>> def foo(request, project): >>> return >>> @has_access >>> def foo(request, project): >>> return """ if callable(access_or_func): return has_access(None)(access_or_func) access = access_or_func def wrapped(func): @wraps(func) def _wrapped(request, *args, **kwargs): # All requests require authentication if not request.user.is_authenticated(): request.session['_next'] = request.get_full_path() return HttpResponseRedirect(get_login_url()) has_team = 'team_slug' in kwargs has_project = 'project_id' in kwargs team_slug = kwargs.pop('team_slug', None) project_id = kwargs.pop('project_id', None) # Pull in team if it's part of the URL arguments if team_slug: if request.user.is_superuser: try: team = Team.objects.get_from_cache(slug=team_slug) except Team.DoesNotExist: return HttpResponseRedirect(reverse('sentry')) else: team_list = Team.objects.get_for_user(request.user, access) try: team = team_list[team_slug] except KeyError: return HttpResponseRedirect(reverse('sentry')) else: team = None if project_id: # Support project id's if request.user.is_superuser: if project_id.isdigit(): lookup_kwargs = {'id': int(project_id)} elif team: lookup_kwargs = {'slug': project_id, 'team': team} else: return HttpResponseRedirect(reverse('sentry')) try: project = Project.objects.get_from_cache(**lookup_kwargs) except Project.DoesNotExist: if project_id.isdigit(): # It could be a numerical slug try: project = Project.objects.get_from_cache(slug=project_id) except Project.DoesNotExist: return HttpResponseRedirect(reverse('sentry')) else: return HttpResponseRedirect(reverse('sentry')) else: project_list = Project.objects.get_for_user(request.user, access, team=team) if project_id.isdigit(): key = 'id' value = int(project_id) elif team: key = 'slug' value = project_id else: return HttpResponseRedirect(reverse('sentry')) for p in project_list: if getattr(p, key) == value: project = p break else: return HttpResponseRedirect(reverse('sentry')) else: project = None if has_project: # ensure we're accessing this url correctly if project and team: if project.team_id != team.id: return HttpResponseRedirect(reverse('sentry')) project._team_cache = team kwargs['project'] = project if has_team: kwargs['team'] = team return func(request, *args, **kwargs) return _wrapped return wrapped def has_group_access(func=None, **kwargs): """ Tests and transforms project_id and group_id for permissions based on the requesting user. Passes the actual project and group instances to the decorated view. >>> @has_group_access(allow_public=True) >>> def foo(request, project, group): >>> return """ if func: return has_group_access(**kwargs)(func) allow_public = kwargs.get('allow_public') def decorator(func): prv_func = login_required(has_access(func)) @wraps(func) def wrapped(request, team_slug, project_id, group_id, *args, **kwargs): group = get_object_or_404(Group, pk=group_id) if project_id not in (group.project.slug, str(group.project.id)): return HttpResponse(status=404) if team_slug != group.team.slug: return HttpResponse(status=404) if allow_public and (group.is_public or group.project.public): team = Team.objects.get_from_cache(slug=team_slug) return func(request, team=team, project=group.project, group=group, *args, **kwargs) return prv_func(request, team_slug=team_slug, project_id=project_id, group=group, *args, **kwargs) return wrapped return decorator def login_required(func): @wraps(func) def wrapped(request, *args, **kwargs): if not request.user.is_authenticated(): request.session['_next'] = request.get_full_path() return HttpResponseRedirect(get_login_url()) return func(request, *args, **kwargs) return wrapped def requires_admin(func): @wraps(func) def wrapped(request, *args, **kwargs): if not request.user.is_authenticated(): request.session['_next'] = request.get_full_path() return HttpResponseRedirect(get_login_url()) if not request.user.is_staff: return render_to_response('sentry/missing_permissions.html', status=400) return func(request, *args, **kwargs) return wrapped
{ "repo_name": "rdio/sentry", "path": "src/sentry/web/decorators.py", "copies": "1", "size": "6524", "license": "bsd-3-clause", "hash": 7920755009958100000, "line_mean": 35.8587570621, "line_max": 110, "alpha_frac": 0.5378602085, "autogenerated": false, "ratio": 4.751638747268754, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5789498955768755, "avg_score": null, "num_lines": null }
from functools import wraps from django.db import IntegrityError, transaction from rest_framework import exceptions, filters, permissions, viewsets from nodeconductor.core.exceptions import IncorrectStateException from nodeconductor.structure.filters import GenericRoleFilter from nodeconductor.structure.models import Resource from nodeconductor.structure import views as structure_views from .backend import SaltStackBackendError from . import models, serializers def track_exceptions(view_fn): @wraps(view_fn) def wrapped(*args, **kwargs): try: return view_fn(*args, **kwargs) except (SaltStackBackendError, IntegrityError) as e: raise exceptions.APIException(e.traceback_str) return wrapped class SaltStackServiceViewSet(structure_views.BaseServiceViewSet): queryset = models.SaltStackService.objects.all() serializer_class = serializers.ServiceSerializer class SaltStackServiceProjectLinkViewSet(structure_views.BaseServiceProjectLinkViewSet): queryset = models.SaltStackServiceProjectLink.objects.all() serializer_class = serializers.ServiceProjectLinkSerializer class BasePropertyViewSet(viewsets.ModelViewSet): queryset = NotImplemented serializer_class = NotImplemented lookup_field = 'uuid' permission_classes = (permissions.IsAuthenticated, permissions.DjangoObjectPermissions) filter_backends = (GenericRoleFilter, filters.DjangoFilterBackend,) backend_name = NotImplemented def get_backend(self, tenant): backend = tenant.get_backend() return getattr(backend, self.backend_name) def pre_create(self, serializer): pass def post_create(self, obj, serializer, backend_obj): pass def pre_update(self, obj, serializer): pass def post_update(self, obj, serializer): pass def post_destroy(self, obj): pass @track_exceptions def perform_create(self, serializer): tenant = serializer.validated_data['tenant'] backend = self.get_backend(tenant) if tenant.state != Resource.States.ONLINE: raise IncorrectStateException( "Tenant must be in stable state to perform this operation") valid_args = [arg for arg in backend.Methods.create['input'] if arg != 'tenant'] backend_obj = backend.create( **{k: v for k, v in serializer.validated_data.items() if k in valid_args and v is not None}) with transaction.atomic(): self.pre_create(serializer) obj = serializer.save(backend_id=backend_obj.id) self.post_create(obj, serializer, backend_obj) @track_exceptions def perform_update(self, serializer): obj = self.get_object() backend = self.get_backend(obj.tenant) changed = { k: v for k, v in serializer.validated_data.items() if v and k in backend.Methods.change['input'] and getattr(obj, k) != v} if changed: backend.change(id=obj.backend_id, **changed) with transaction.atomic(): self.pre_update(obj, serializer) serializer.save() self.post_update(obj, serializer) @track_exceptions def perform_destroy(self, obj): backend = self.get_backend(obj.tenant) backend.delete(id=obj.backend_id) obj.delete() self.post_destroy(obj)
{ "repo_name": "opennode/nodeconductor-saltstack", "path": "src/nodeconductor_saltstack/saltstack/views.py", "copies": "1", "size": "3406", "license": "mit", "hash": 4233559080282839000, "line_mean": 33.404040404, "line_max": 104, "alpha_frac": 0.6881972989, "autogenerated": false, "ratio": 4.289672544080605, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5477869842980605, "avg_score": null, "num_lines": null }
from functools import wraps from django.db import transaction from guardian.models import UserObjectPermission, GroupObjectPermission from .shortcuts import (get_users_eligible_for_object, get_groups_eligible_for_object, get_objects_eligible_for_user, get_objects_eligible_for_group) from . import utils def setup_users_eligible_for_object(*perms): """Post-save signal receiver producer to setup a new object Since this is the first time permissions are being setup, the `bulk_create` manager method is used for performance. """ @transaction.commit_on_success @wraps(setup_users_eligible_for_object) def receiver(sender, instance, created, raw, **kwargs): if raw or not created: return obj_perms = [] for perm in perms: perm = utils.get_perm(perm) users = get_users_eligible_for_object(perm, instance) for user in users: obj_perms.append(UserObjectPermission(user=user, permission=perm, content_object=instance)) UserObjectPermission.objects.bulk_create(obj_perms) return receiver def setup_groups_eligible_for_object(*perms): """Post-save signal receiver producer to associate a eligible groups to a new object. Since this is the first time permissions are being setup, the `bulk_create` manager method is used for performance. """ @transaction.commit_on_success @wraps(setup_groups_eligible_for_object) def receiver(sender, instance, created, raw, **kwargs): if raw or not created: return obj_perms = [] for perm in perms: perm = utils.get_perm(perm) groups = get_groups_eligible_for_object(perm, instance) for group in groups: obj_perms.append(GroupObjectPermission(group=group, permission=perm, content_object=instance)) GroupObjectPermission.objects.bulk_create(obj_perms) return receiver def setup_objects_eligible_for_user(*perms): "Post-save signal receiver producer to associate objects to a new user." @transaction.commit_on_success @wraps(setup_objects_eligible_for_user) def receiver(sender, instance, created, raw, **kwargs): if raw or not created: return obj_perms = [] for perm in perms: perm = utils.get_perm(perm) objs = get_objects_eligible_for_user(perm, instance) for obj in objs: obj_perms.append(UserObjectPermission(user=instance, permission=perm, content_object=obj)) UserObjectPermission.objects.bulk_create(obj_perms) return receiver def setup_objects_eligible_for_group(*perms): "Post-save signal receiver producer to associate objects to a new group." @transaction.commit_on_success @wraps(setup_objects_eligible_for_group) def receiver(sender, instance, created, raw, **kwargs): if raw or not created: return obj_perms = [] for perm in perms: perm = utils.get_perm(perm) objs = get_objects_eligible_for_group(perm, instance) for obj in objs: obj_perms.append(GroupObjectPermission(group=instance, permission=perm, content_object=obj)) GroupObjectPermission.objects.bulk_create(obj_perms) return receiver
{ "repo_name": "bruth/django-governor", "path": "governor/receivers.py", "copies": "1", "size": "3445", "license": "bsd-2-clause", "hash": -4363056753152496000, "line_mean": 30.6055045872, "line_max": 85, "alpha_frac": 0.6513788099, "autogenerated": false, "ratio": 4.180825242718447, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5332204052618447, "avg_score": null, "num_lines": null }
from functools import wraps from django.db.models.query import QuerySet import itertools def requires_prep(func): @wraps(func) def wrapper(*args, **kwargs): if args[0].needs_prep: args[0]._prep() assert(not args[0].needs_prep) return func(*args, **kwargs) return wrapper class FilterException(Exception): pass class MergeQuerySet(object): """ This class provides a queryset-like object that merges two querysets and de-duplicates """ def __init__(self, queryset, queryset2): self.queryset = queryset self.queryset2 = queryset2 self.needs_prep = True def _prep(self): exclude_ids = [] query_model = self.queryset2.model for obj in self.queryset: if query_model == obj.__class__: exclude_ids.append(obj.id) elif query_model in obj.__class__._meta.parents: parent_field = obj.__class__._meta.parents[query_model] exclude_ids.append(parent_field.value_from_object(obj)) self.queryset2 = self.queryset2.exclude(id__in=exclude_ids) self.needs_prep = False @requires_prep def __iter__(self): return itertools.chain(self.queryset, self.queryset2) @requires_prep def __len__(self): return len(self.queryset) + len(self.queryset2) @requires_prep def __getitem__(self, i): if type(i) is slice: start, stop, step = i.indices(len(self)) if step != 1: raise TypeError('MergeQuerySet only supports simple slices') return self.__getslice__(start, stop) elif type(i) is not int: raise TypeError if i < len(self.queryset): return self.queryset[i] elif i < len(self): return self.queryset2[i - len(self.queryset)] else: raise IndexError("list index out of range") def filter(self, *args, **kwargs): if not self.needs_prep: raise FilterException("Filter called after queryset already merged") return MergeQuerySet(self.queryset.filter(*args, **kwargs), self.queryset2.filter(*args, **kwargs)) @requires_prep def count(self): return self.__len__() @requires_prep def __getslice__(self, i, j): qs_len = len(self.queryset) if j <= qs_len: return self.queryset[i:j] end = j - qs_len if i >= qs_len: start = i - qs_len return self.queryset2[start:end] return list(itertools.chain(self.queryset[i:], self.queryset2[0:end])) def __getattr__(self, key): try: return getattr(super(MergeQuerySet, self), key) except AttributeError: if key != 'queryset' and hasattr(QuerySet, key): raise NotImplementedError() raise class GenericForeignKeyQuerySet(object): def __init__(self, queryset, gfk='content_object'): self.queryset = queryset model = self.queryset.model for field in model._meta.virtual_fields: if field.name == gfk: self.ct_field = field.ct_field self.fk_field = field.fk_field break else: raise ValueError("No GenericForeignKey named %s on the %s model" \ % (gfk, model)) self.needs_prep = True def _prep(self): managers = {} ordering = {} for i, obj in enumerate(self.queryset): obj_ct = getattr(obj, self.ct_field) obj_fk = getattr(obj, self.fk_field) model_class = obj_ct.model_class() key = "%s.%s" % (model_class.__module__, obj_ct.model) if not key in managers: managers[key] = { "name": obj_ct.model, # _default_manager is undocumented. If django ever # changes/documents a way to get the default # manager, this will need to change too "manager": model_class._default_manager, "object_ids": [], } node_key = "%s.%i" % (obj_ct.model, obj_fk) ordering.setdefault(node_key, []).append(i) managers[key]["object_ids"].append(obj_fk) self.content = [None] * len(self.queryset) for model_data in managers.values(): node_content = model_data["manager"].filter( pk__in=model_data["object_ids"]) for obj in node_content: node_key = "%s.%i" % (model_data['name'], obj.pk) for idx in ordering[node_key]: self.content[idx] = obj self.needs_prep = False @requires_prep def __iter__(self): return self.content.__iter__() @requires_prep def __len__(self): return len(self.content) def count(self): return self.__len__() @requires_prep def __getitem__(self, i): return self.content.__getitem__(i) def filter(self, *args, **kwargs): if kwargs: raise FilterException("GenericForeignKeyQuerySets cannot be filtered") return self def __getattr__(self, key): try: return getattr(super(GenericForeignKeyQuerySet, self), key) except AttributeError: if key != 'queryset' and hasattr(QuerySet, key): raise NotImplementedError() raise
{ "repo_name": "dmclain/armstrong.core.arm_wells", "path": "armstrong/core/arm_wells/querysets.py", "copies": "1", "size": "5550", "license": "apache-2.0", "hash": -7543823431728437000, "line_mean": 32.4337349398, "line_max": 82, "alpha_frac": 0.5506306306, "autogenerated": false, "ratio": 4.201362604087812, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009064144460495764, "num_lines": 166 }
from functools import wraps from django.db.models.query import QuerySet # Multiple admin sites only currently work in Django 1.11 due to use of all_sites try: from django.contrib.admin.sites import all_sites except ImportError: from django.contrib import admin all_sites = [admin.site] class QuerySetIsh(QuerySet): """Takes an instance and mimics it coming from a QuerySet""" def __init__(self, instance=None, *args, **kwargs): try: model = instance._meta.model except AttributeError: # Django 1.5 does this instead, getting the model may be overkill # we may be able to throw away all this logic model = instance._meta.concrete_model self._doa_instance = instance super(QuerySetIsh, self).__init__(model, *args, **kwargs) self._result_cache = [instance] def _clone(self, *args, **kwargs): # don't clone me, bro return self def get(self, *args, **kwargs): # Starting in Django 1.7, `QuerySet.get` started slicing to `MAX_GET_RESULTS`, # so to avoid messing with `__getslice__`, override `.get`. return self._doa_instance def takes_instance_or_queryset(func): """Decorator that makes standard actions compatible""" @wraps(func) def decorated_function(self, request, queryset): # Function follows the prototype documented at: # https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#writing-action-functions if not isinstance(queryset, QuerySet): queryset = QuerySetIsh(queryset) return func(self, request, queryset) return decorated_function def get_django_model_admin(model): """Search Django ModelAdmin for passed model. Returns instance if found, otherwise None. """ for admin_site in all_sites: registry = admin_site._registry if model in registry: return registry[model] return None
{ "repo_name": "DjangoAdminHackers/django-admin-row-actions", "path": "django_admin_row_actions/utils.py", "copies": "1", "size": "1990", "license": "mit", "hash": 2739000033328423000, "line_mean": 32.7288135593, "line_max": 99, "alpha_frac": 0.651758794, "autogenerated": false, "ratio": 4.2703862660944205, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.542214506009442, "avg_score": null, "num_lines": null }
from functools import wraps from django.db.models.query import QuerySet class QuerySetIsh(QuerySet): """Takes an instance and mimics it coming from a QuerySet""" def __init__(self, instance=None, *args, **kwargs): try: model = instance._meta.model except AttributeError: # Django 1.5 does this instead, getting the model may be overkill # we may be able to throw away all this logic model = instance._meta.concrete_model self._doa_instance = instance super(QuerySetIsh, self).__init__(model, *args, **kwargs) self._result_cache = [instance] def _clone(self, *args, **kwargs): # don't clone me, bro return self def get(self, *args, **kwargs): # Starting in Django 1.7, `QuerySet.get` started slicing to `MAX_GET_RESULTS`, # so to avoid messing with `__getslice__`, override `.get`. return self._doa_instance def takes_instance_or_queryset(func): """Decorator that makes standard actions compatible""" @wraps(func) def decorated_function(self, request, queryset): # Function follows the prototype documented at: # https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#writing-action-functions if not isinstance(queryset, QuerySet): queryset = QuerySetIsh(queryset) return func(self, request, queryset) return decorated_function
{ "repo_name": "phpdude/django-admin-row-actions", "path": "django_admin_row_actions/utils.py", "copies": "1", "size": "1467", "license": "mit", "hash": 7363944631039208000, "line_mean": 34.7804878049, "line_max": 99, "alpha_frac": 0.6380368098, "autogenerated": false, "ratio": 4.2894736842105265, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.01979254275301374, "num_lines": 41 }
from functools import wraps from django.http import Http404 from corehq import toggles, Domain from corehq.apps.domain.decorators import (login_and_domain_required, domain_admin_required) from .models import SQLLocation from .util import get_xform_location def locations_access_required(view_fn): """ Decorator controlling domain-level access to locations. Mostly a placeholder, soon this will also check for standard plan """ return login_and_domain_required(view_fn) def is_locations_admin(view_fn): """ Decorator controlling write access to locations. """ return locations_access_required(domain_admin_required(view_fn)) def user_can_edit_any_location(user, project): return user.is_domain_admin(project.name) or not project.location_restriction_for_users def can_edit_any_location(view_fn): """ Decorator determining whether a user has permission to edit all locations in a project """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): if user_can_edit_any_location(request.couch_user, request.project): return view_fn(request, domain, *args, **kwargs) raise Http404() return locations_access_required(_inner) def user_can_edit_location(user, sql_location, project): if user_can_edit_any_location(user, project): return True user_loc = user.get_location(sql_location.domain) if user_loc: user_loc = user_loc.sql_location return user_loc is None or user_loc.is_direct_ancestor_of(sql_location) def user_can_view_location(user, sql_location, project): if (user.is_domain_admin(project.name) or not project.location_restriction_for_users): return True user_loc = user.get_location(sql_location.domain) if not user_loc: return True if user_can_edit_location(user, sql_location, project): return True return sql_location.location_id in user_loc.lineage def can_edit_location(view_fn): """ Decorator controlling a user's access to a specific location. The decorated function must be passed a loc_id arg (eg: from urls.py) """ @wraps(view_fn) def _inner(request, domain, loc_id, *args, **kwargs): try: # pass to view? location = SQLLocation.objects.get(location_id=loc_id) except SQLLocation.DoesNotExist: raise Http404() else: if user_can_edit_location(request.couch_user, location, request.project): return view_fn(request, domain, loc_id, *args, **kwargs) raise Http404() return locations_access_required(_inner) def user_can_edit_location_types(user, project): if (user.is_domain_admin(project.name) or not project.location_restriction_for_users): return True return not user.get_domain_membership(project.name).location_id def can_edit_location_types(view_fn): """ Decorator controlling a user's access to a location types. """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): if user_can_edit_location_types(request.couch_user, request.project): return view_fn(request, domain, *args, **kwargs) raise Http404() return locations_access_required(_inner) def can_edit_form_location(domain, user, form): if not toggles.RESTRICT_FORM_EDIT_BY_LOCATION.enabled(domain): return True location = get_xform_location(form) if not location: return True return user_can_edit_location(user, location, Domain.get_by_name(domain))
{ "repo_name": "puttarajubr/commcare-hq", "path": "corehq/apps/locations/permissions.py", "copies": "1", "size": "3627", "license": "bsd-3-clause", "hash": 7335150703235377000, "line_mean": 31.3839285714, "line_max": 91, "alpha_frac": 0.6732837055, "autogenerated": false, "ratio": 3.7585492227979276, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4931832928297928, "avg_score": null, "num_lines": null }
from functools import wraps from django.http import Http404 from toggle.shortcuts import toggle_enabled class StaticToggle(object): def __init__(self, slug, label, namespaces=None): self.slug = slug self.label = label if namespaces: self.namespaces = [None if n == NAMESPACE_USER else n for n in namespaces] else: self.namespaces = [None] def enabled(self, item, **kwargs): return any([toggle_enabled(self.slug, item, namespace=n, **kwargs) for n in self.namespaces]) def required_decorator(self): """ Returns a view function decorator that checks to see if the domain or user in the request has the appropriate toggle enabled. """ def decorator(view_func): @wraps(view_func) def wrapped_view(request, *args, **kwargs): if ( (hasattr(request, 'user') and self.enabled(request.user.username)) or (hasattr(request, 'domain') and self.enabled(request.domain)) ): return view_func(request, *args, **kwargs) raise Http404() return wrapped_view return decorator # if no namespaces are specified the user namespace is assumed NAMESPACE_USER = object() NAMESPACE_DOMAIN = 'domain' APP_BUILDER_CUSTOM_PARENT_REF = StaticToggle( 'custom-parent-ref', 'Custom case parent reference' ) APP_BUILDER_CAREPLAN = StaticToggle( 'careplan', 'Careplan module' ) APP_BUILDER_ADVANCED = StaticToggle( 'advanced-app-builder', 'Advanced Module in App-Builder' ) APP_BUILDER_INCLUDE_MULTIMEDIA_ODK = StaticToggle( 'include-multimedia-odk', 'Include multimedia in ODK deploy' ) PRBAC_DEMO = StaticToggle( 'prbacdemo', 'Roles and permissions' ) ACCOUNTING_PREVIEW = StaticToggle( 'accounting_preview', 'Accounting preview', [NAMESPACE_DOMAIN, NAMESPACE_USER] ) BOOTSTRAP3_PREVIEW = StaticToggle( 'bootstrap3_preview', 'Bootstrap 3 Preview', [NAMESPACE_USER] ) INVOICE_TRIGGER = StaticToggle( 'invoice_trigger', 'Accounting Trigger Invoices', [NAMESPACE_USER] ) OFFLINE_CLOUDCARE = StaticToggle( 'offline-cloudcare', 'Offline Cloudcare' ) REMINDERS_UI_PREVIEW = StaticToggle( 'reminders_ui_preview', 'New reminders UI' ) CASE_REBUILD = StaticToggle( 'case_rebuild', 'Show UI-based case rebuild option', ) IS_DEVELOPER = StaticToggle( 'is_developer', 'Is developer' ) PATHWAYS_PREVIEW = StaticToggle( 'pathways_preview', 'Is Pathways preview' ) CUSTOM_PRODUCT_DATA = StaticToggle( 'custom_product_data', 'Custom Product Data', [NAMESPACE_DOMAIN, NAMESPACE_USER] ) MM_CASE_PROPERTIES = StaticToggle( 'mm_case_properties', 'Multimedia Case Properties', ) DASHBOARD_PREVIEW = StaticToggle( 'dashboard_preview', 'HQ Dashboard Preview' )
{ "repo_name": "SEL-Columbia/commcare-hq", "path": "corehq/toggles.py", "copies": "1", "size": "2937", "license": "bsd-3-clause", "hash": 5019502141478303000, "line_mean": 23.2727272727, "line_max": 101, "alpha_frac": 0.6503234593, "autogenerated": false, "ratio": 3.630407911001236, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9777414369519732, "avg_score": 0.0006634001563007647, "num_lines": 121 }
from functools import wraps from django.http import HttpResponseForbidden from django.shortcuts import redirect import service __author__ = 'Luis' def istuple(value, n): return isinstance(value, tuple) and len(value) == n class ifban(object): def __init__(self, allow_anonymous, ban_attr_name='current_ban', service_attr_name='service', view_attr_name='view'): self.allow_anonymous = allow_anonymous self.ban_attr_name = ban_attr_name self.service_attr_name = service_attr_name self.view_attr_name = view_attr_name def on_anonymous(self, request, *args, **kwargs): """ This method must be defined to define what to do if a request comes to this view and no user is logged in or the "auth" app is not installed. The following params must be specified: 1. 1 (one) positional parameter: request. request.<view> will hold the wrapped view. The attribute name is determined in this decorator constructor. 2. *args and **kwargs as they will serve to generic purposes. It must return a response as any view would do. """ raise NotImplementedError() def on_banned(self, request, *args, **kwargs): """ What to do when the user is banned. The following params must be specified: 1. 1 (one) positional parameter: request. request.<view> will hold the wrapped view. The attribute name is determined in this decorator constructor. request.<service> will hold the current user wrapper. The attribute name is determined in this decorator constructor. request.<ban> will hold the current ban (or None). The attribute name is determined in this decorator constructor. 2. *args and **kwargs as they will serve to generic purposes. It must return a response as any view would do. """ return NotImplementedError() def _get_ban(self, request): """ Checks the ban for the logged user in a request and returns a result: None: there's no ban for the logged user (i.e. it's not banned). <ban>: there's a ban for the logged user (i.e. it's banned). False: there's no user logged in or the request has no "user" attribute (i.e. "auth" app isn't installed). returns a tuple with the result and the service instance. """ if not hasattr(request, 'user') or not request.user.is_authenticated(): #the auth application is not installed or the user is not authenticated return False, None #get the service from the user and call it. service_ = service.DetentionService(request.user) return service_.my_current_ban(), service_ def _dispatch(self, view, args, kwargs): """ Dispatches the view processing according to: 1. (No auth app or No user logged in) & not "allowing" anonymous users: trigger on_anonymous. 2. ((No auth app or No user logged in) & "allowing" anonymous users): trigger view. 3. User is not banned: trigger view. 4. User is banned: trigger on_banned. """ result, service_ = self._get_ban(args[0]) setattr(args[0], self.service_attr_name, service_) setattr(args[0], self.ban_attr_name, result) setattr(args[0], self.view_attr_name, view) if result is False and not self.allow_anonymous: return self.on_anonymous(args[0], *args[1:], **kwargs) elif not result: return view(*args, **kwargs) else: return self.on_banned(args[0], *args[1:], **kwargs) def __call__(self, view): """ Takes the current view and returns a wrapper that does the dispatch. """ @wraps(view) def wrapper(*args, **kwargs): return self._dispatch(view, args, kwargs) return wrapper class ifban_forbid(ifban): def on_banned(self, request, *args, **kwargs): """ You should not redefine this method. This is a convenient method defined for you in this class. """ result = self.get_content(request, *args, **kwargs) if istuple(result, 2): content, content_type = result elif istuple(result, 1): content, content_type = result + ('text/plain',) elif isinstance(result, basestring): content, content_type = result, 'text/plain' else: raise TypeError("Response content must be a 1 or 2 items tuple, or a string type value") return HttpResponseForbidden(content=content, content_type=content_type) def get_content(self, request, *args, **kwargs): """ Must process the request, view, and ban parameter in **kwargs (as specified in base on_banned method) to yield the content and content_type for the 403 response. Defaults to a void string and a 'text/plain' type in a (content, content_type) tuple. """ return '', 'text/plain' class ifban_redirect(ifban): def on_banned(self, request, *args, **kwargs): """ You should not redefine this method. This is a convenient method defined for you in this class. """ result = self.get_redirection(request, *args, **kwargs) if istuple(result, 2): target, permanent = result elif istuple(result, 1): target, permanent = result + (False,) elif isinstance(result, basestring): target, permanent = result, False else: raise TypeError("Redirection target must be a 1 or 2 items tuple, or a string type value") return redirect(target, permanent=permanent) def get_redirection(self, request, *args, **kwargs): """ Must process the request, view, and ban parameter in **kwargs (as specified in base on_banned method) to yield the target url AND determine if it's a 302 or 301 redirection. Defaults to '/' and False in a (url, boolean) tuple, where True in the boolean means a permanent (301) redirection """ return '/', False class ifban_same(ifban): def on_banned(self, request, *args, **kwargs): """ You should not redefine this method. This is a convenient method defined for you in this class. Calls the same view for both banned or unbanned user. The request will have an attribute as defined in the constructor for the service name. Your view must handle a ban parameter as defined in the decorator's name. """ return request.view(request, *args, **kwargs)
{ "repo_name": "luismasuelli/django-detention", "path": "detention/decorators.py", "copies": "1", "size": "6643", "license": "unlicense", "hash": 6468855636978435000, "line_mean": 43, "line_max": 128, "alpha_frac": 0.6348035526, "autogenerated": false, "ratio": 4.258333333333334, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5393136885933334, "avg_score": null, "num_lines": null }
from functools import wraps from django.http import HttpResponse, Http404 from django.utils import simplejson as json def render_to_json(**jsonargs): """ renders given request in json """ def outer(f): @wraps(f) def inner_json(request, *args, **kwargs): result = f(request, *args, **kwargs) r = HttpResponse(mimetype='application/json') if result: indent = jsonargs.pop('indent', 4) r.write(json.dumps(result, indent=indent, **jsonargs)) else: r.write("{}") return r return inner_json return outer def ajax_messages(fn, success_message='Success', error_message='Error'): """ returns given success or error message according to response status_code be warned, that this decorator changes the response code for "jQuery safe" ones - 200 for success, 500 otherwise """ def process(request, *args, **kwargs): decorated = fn(request, *args, **kwargs) if decorated.status_code in [200, 301, 302, 304, 307]: message = success_message status_code = 200 else: message = error_message status_code = 500 if request.is_ajax(): return HttpResponse(content=message, status=status_code) else: return decorated return process def ajax_required(f): """AJAX required view decorator """ def wrap(request, *args, **kwargs): if not request.is_ajax(): raise Http404 return f(request, *args, **kwargs) wrap.__doc__ = f.__doc__ wrap.__name__ = f.__name__ return wrap def other_if_ajax(fn, other_fn, other_settings_dict=None): """ returns other view (with additional params) if request is ajax """ def process(request, *args, **kwargs): if request.is_ajax(): kwargs.update(other_settings_dict or {}) return other_fn(request, *args, **kwargs) else: return fn(request, *args, **kwargs) return process
{ "repo_name": "adamcupial/django-js-addons", "path": "js_addons/ajax_tools/decorators.py", "copies": "1", "size": "2106", "license": "mit", "hash": -332317422627819700, "line_mean": 29.9705882353, "line_max": 80, "alpha_frac": 0.581671415, "autogenerated": false, "ratio": 4.245967741935484, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5327639156935484, "avg_score": null, "num_lines": null }
from functools import wraps from django.http import HttpResponse, HttpResponseRedirect from django.core.exceptions import ObjectDoesNotExist from django.conf import settings from .models import User, Guest USER_UID_KEY = '_user_uid' USER_EMAIL_KEY = '_user_name' USER_NAME_KEY = '_user_email' USER_LEVEL_KEY = '_user_level' USER_AUTH_KEY = '_user_auth' def get_user(request): user = None if USER_EMAIL_KEY in request.session: uid = int(request.session[USER_UID_KEY]) email = request.session[USER_EMAIL_KEY] name = request.session[USER_NAME_KEY] level = request.session[USER_LEVEL_KEY] user = User(pk=uid, email=email, name=name, level=level) else: user = Guest() #print ('user name : '+user.name) return user def auth_user(email, password): user = None try: user = User.objects.get(email=email, password=password) except ObjectDoesNotExist: user = None return user def login(request, user): # need to do it in accounts.middleware.AuthMiddleware request.session[USER_UID_KEY] = user._meta.pk.value_to_string(user) request.session[USER_EMAIL_KEY] = user.email request.session[USER_NAME_KEY] = user.name request.session[USER_LEVEL_KEY] = user.level request.session[USER_AUTH_KEY] = True request.session.set_expiry(60*60) # 10 minutes session timeout def logout(request): request.session.flush() request.user = Guest() #request._cached_user = request.user
{ "repo_name": "amitdhiman000/dais", "path": "user/backends.py", "copies": "1", "size": "1395", "license": "apache-2.0", "hash": 3679088493241904600, "line_mean": 27.4693877551, "line_max": 68, "alpha_frac": 0.7390681004, "autogenerated": false, "ratio": 3.0726872246696035, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43117553250696034, "avg_score": null, "num_lines": null }
from functools import wraps from django.http import HttpResponse from django.conf import settings from importlib import import_module import proxy_server, json def expose_service(methods, public=False): def decorator(view_func): view_func.__dict__['_proxy_service'] = True def wrapper(request, *args, **kwargs): error_message = None code = 500 try: if hasattr(settings, 'PROXY_API_KEYS'): if request.META.get(proxy_server.HTTP_API_KEY) in settings.PROXY_API_KEYS: rest_framework = False if hasattr(settings, 'REST_FRAMEWORK_SUPPORT'): rest_framework = settings.REST_FRAMEWORK_SUPPORT if hasattr(settings, 'PROXY_TOKEN_VALIDATION_SERVICE'): if public is True: if request.META.get(proxy_server.HTTP_USER_TOKEN) is not None: error_message = 'A public service cannot receive a user token' code = 400 raise Exception else: if rest_framework: from rest_framework.decorators import api_view return api_view(methods)(view_func)(request, *args, **kwargs) else: if request.method not in methods: code = 405 error_message = 'Method Not Allowed' raise Exception setattr(request, 'DATA', dict()) if request.body: request.DATA.update(json.loads(request.body)) return view_func(request, *args, **kwargs) else: if not request.META.get(proxy_server.HTTP_USER_TOKEN): error_message = 'A private service requires a user token' code = 400 raise Exception else: try: dot = settings.PROXY_TOKEN_VALIDATION_SERVICE.rindex('.') except ValueError: error_message = 'Token validation service not properly configured' raise Exception val_module = import_module(settings.PROXY_TOKEN_VALIDATION_SERVICE[:dot]) val_func = getattr(val_module, settings.PROXY_TOKEN_VALIDATION_SERVICE[dot + 1:]) try: response = val_func(request) except Exception as e: error_message = 'Could not invoke token validation service' raise Exception if response.status_code == 403: code = 403 error_message = 'Token invalid' raise Exception response_json = json.loads(response.content) request.META[proxy_server.HTTP_USER_TOKEN] = response_json[proxy_server.USER_TOKEN] if rest_framework: from rest_framework.decorators import api_view return api_view(methods)(view_func)(request, *args, **kwargs) else: if request.method not in methods: code = 405 error_message = 'Method Not Allowed' raise Exception setattr(request, 'DATA', dict()) if request.body: request.DATA.update(json.loads(request.body)) return view_func(request, *args, **kwargs) else: error_message = 'Received API KEY not found in server API KEYS set' code = 403 raise Exception else: error_message = 'API KEYS not properly configured' raise Exception except Exception as e: if error_message is None: if e.message is not None: error_message = e.message else: error_message = 'Server encountered an error and cannot proceed with service call' error = { 'error': { 'code': code, 'type': 'ProxyServerError', 'message': error_message } } return HttpResponse(json.dumps(error), content_type='application/json', status=code, reason=error_message) return wraps(view_func)(wrapper) return decorator
{ "repo_name": "lmanzurv/django_proxy_server", "path": "proxy_server/decorators.py", "copies": "1", "size": "5563", "license": "apache-2.0", "hash": 2594346790028446700, "line_mean": 47.3739130435, "line_max": 122, "alpha_frac": 0.4161423692, "autogenerated": false, "ratio": 6.394252873563218, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002426588068977474, "num_lines": 115 }
from functools import wraps from django.http import HttpResponseNotFound from django.shortcuts import get_object_or_404, render_to_response from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponse, Http404 from apps.form_engine.forms import Survey from apps.form_engine.forms import * def authorize_form(func): @wraps(func) def decorator(request,*args, **kwargs): form_slug = kwargs.get('form_slug') form_template = get_object_or_404(Survey, slug=form_slug) # if magicform.closed: # pass # if magicform.answers_viewable_by(request.user): # return HttpResponseRedirect(reverse('survey-results', None, (), # {'survey_slug': survey_slug})) # if user has a session and have answered some questions # and the survey does not accept multiple answers, # go ahead and redirect to the answers, or a thank you # if (hasattr(request, 'session') and # magicform.has_answers_from(request.session.session_key) and # not magicform.allows_multiple_interviews and not allow_edit_existing_answers): # return _survey_redirect(request, survey,group_slug=group_slug) # if the survey is restricted to authentified user redirect anonymous user to the login page if form_template.restricted and str(request.user) == "AnonymousUser": return HttpResponseRedirect(reverse("login")+"?next=%s" % request.path) # if cookies are not enabeled, notify user if request.method == 'POST' and not hasattr(request, 'session'): return HttpResponse(unicode(_('Cookies must be enabled.')), status=403) return func(request, *args, **kwargs) return decorator
{ "repo_name": "tiabas/django-forms", "path": "form_engine/decorators.py", "copies": "2", "size": "1695", "license": "mit", "hash": 1186341342185325800, "line_mean": 48.8529411765, "line_max": 94, "alpha_frac": 0.7174041298, "autogenerated": false, "ratio": 3.7252747252747254, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5442678855074725, "avg_score": null, "num_lines": null }
from functools import wraps from django import template from django.forms.fields import TextInput from django.utils import html from django.utils.translation import gettext_lazy as _ register = template.Library() def append_attr(field, attr_name, attr_value): if field.field.widget.attrs.get(attr_name, False): field.field.widget.attrs[attr_name] += ' %s' % attr_value else: field.field.widget.attrs[attr_name] = attr_value def wrap_input_field_div(func=None, input_field=True): if input_field: template = '<div class="input-field col s{}">{}</div>' else: template = '<div class="col s{}">{}</div>' def dec(func): def wrapper(field, col=12, **flags): return html.format_html( template, col, html.mark_safe(func(field, **flags)) ) return template % (col, func(field, **flags)) return wrapper if func is None: return dec else: return dec(func) def form_field_type(field): if hasattr(field, 'field') and hasattr(field.field, 'widget') and field.field.widget: return field.field.widget.__class__.__name__.lower() return '' @register.simple_tag(takes_context=False) def materialize_form_field_label(field): id_for_label = getattr(field, 'id_for_label') label = getattr(field.field, 'label') if label is None: label = getattr(field, 'name') if field.errors: error = field.errors[0] else: error = '' if not label is None: return html.format_html( '<label for="{}" data-error="{}">{}</label>', id_for_label, error, label ) return '' @register.simple_tag(takes_context=False) @wrap_input_field_div def materialize_form_textinput(field): return html.mark_safe('%s%s' % (str(field), materialize_form_field_label(field))) @register.simple_tag(takes_context=False) @wrap_input_field_div def materialize_form_textarea(field): append_attr(field, 'class', 'materialize-textarea') return html.mark_safe('%s%s' % (materialize_form_field_label(field), str(field))) @register.simple_tag(takes_context=False) @wrap_input_field_div def materialize_form_select(field): return html.mark_safe('%s%s' % (str(field), materialize_form_field_label(field))) @register.simple_tag(takes_context=False) @wrap_input_field_div(input_field=False) def materialize_form_checkboxinput(field): append_attr(field, 'class', 'filled-in') return html.mark_safe('%s%s' % (str(field), materialize_form_field_label(field))) @register.simple_tag(takes_context=False) @register.filter(is_save=True, takes_context=False) def form_field_render(field, col=12, **kwargs): append_attr(field, 'class', 'validate') if field.errors: append_attr(field, 'class', 'invalid') append_attr(field, 'placeholder', '') return { 'textinput': materialize_form_textinput, 'textarea': materialize_form_textarea, 'select': materialize_form_select, 'checkboxinput': materialize_form_checkboxinput, }.get( form_field_type(field), materialize_form_textinput )(field, col, **kwargs) @register.simple_tag(takes_context=True) def form_add_javascript(context): return template.loader.render_to_string( 'form/javascript.html' ) @register.filter(is_safe=True) def materialize(form): return template.loader.render_to_string( 'form/form.html', { 'form': form } ) @register.simple_tag def materialize_form_submit_btn(text=None): if text is None: text = _('save') return template.loader.render_to_string( 'form/element/submit.html', { 'text': text } ) @register.simple_tag(takes_context=False) def materialize_paginator(paginator, url_name, params=None, buffer=9): current = paginator.number last = paginator.paginator.num_pages mb = 2 * buffer before_range = min( current - 1, max( mb - min(buffer, last - current), buffer ) ) after_range = min( last-current, max( mb - min(buffer, current-1), buffer ) ) return template.loader.render_to_string( 'materialize/paginator.html', { 'url_name': url_name, 'has_previous': paginator.has_previous, 'previous': paginator.previous_page_number, 'pages_before': [n + current - before_range for n in range(before_range)], 'current': paginator.number, 'pages_after': [n + current + 1 for n in range(after_range)], 'has_next': paginator.has_next, 'next': paginator.next_page_number, 'params': params } )
{ "repo_name": "IT-PM-OpenAdaptronik/Webapp", "path": "apps/materialize/templatetags/materialize.py", "copies": "1", "size": "4874", "license": "mit", "hash": -6344411095720009000, "line_mean": 28.9018404908, "line_max": 89, "alpha_frac": 0.6132540008, "autogenerated": false, "ratio": 3.555069292487236, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46683232932872354, "avg_score": null, "num_lines": null }
from functools import wraps from django.shortcuts import get_object_or_404 from app_projects.models import Project OPERATION_NOT_PERMITTED = "You don't have the permission to take this action" NO_VOTE_OWNER = "You can't vote your own project" NO_VOTE_COLLABORATOR = "You can't vote a project in which you collaborate" def must_be_owner(method_name): """ Avoid that a user can edit a project he doesn't own """ def decorator(function): @wraps(function) def _view(self, request, id, *args, **kwargs): p = get_object_or_404(Project, pk=id) if str(p.owner.user.username) == str(request.user): return function(self, request, id, p, *args, **kwargs) else: return self.show(request, id, errors=OPERATION_NOT_PERMITTED) return _view return decorator(method_name) def no_conflict_of_interests(method_name): """ Avoid that a user vote a project he own or in which he collaborate """ def decorator(function): @wraps(function) def _view(self, request, id, *args, **kwargs): p = get_object_or_404(Project, pk=id) # Check Owner if str(p.owner.user.username) == str(request.user): return self.show(request, id, errors=NO_VOTE_OWNER) # Check Collaborators collaborators = p.get_collaborators_wrapper() if str(request.user) in [x['username'] for x in collaborators]: return self.show(request, id, errors=NO_VOTE_COLLABORATOR) # Return the function return function(self, request, id, p, *args, **kwargs) return _view return decorator(method_name)
{ "repo_name": "marco-lancini/Showcase", "path": "app_projects/decorators.py", "copies": "1", "size": "1754", "license": "mit", "hash": 8562685494675324000, "line_mean": 33.3921568627, "line_max": 77, "alpha_frac": 0.6100342075, "autogenerated": false, "ratio": 3.70042194092827, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48104561484282704, "avg_score": null, "num_lines": null }
from functools import wraps from django.shortcuts import ( render, get_object_or_404, ) from django.utils.decorators import available_attrs import frontdesk def with_deposit(func): @wraps(func, assigned=available_attrs(func)) def wrapper(request, deposit_id, *args, **kwargs): deposits = frontdesk.models.Deposit.objects.order_by('-created')[:10] if deposit_id: detailed_deposit = get_object_or_404( frontdesk.models.Deposit, pk=deposit_id) else: detailed_deposit = frontdesk.models.Deposit.objects.order_by( '-created').first() context = {'deposits': deposits, 'detailed_deposit': detailed_deposit} kwargs['context'] = context return func(request, deposit_id, *args, **kwargs) return wrapper def index(request, context=None): deposits = frontdesk.models.Deposit.objects.order_by('-created')[:10] context = {'deposits': deposits} return render(request, 'penne_core/index.html', context) @with_deposit def package_report(request, deposit_id, context=None): return render(request, 'penne_core/package_report.html', context) @with_deposit def package_report_virus(request, deposit_id, context=None): return render(request, 'penne_core/package_report_virus.html', context) @with_deposit def package_report_integrity(request, deposit_id, context=None): return render(request, 'penne_core/package_report_integrity.html', context) @with_deposit def package_report_scielops(request, deposit_id, context=None): return render(request, 'penne_core/package_report_scielops.html', context)
{ "repo_name": "gustavofonseca/penne-core", "path": "penne_core/views.py", "copies": "2", "size": "1664", "license": "bsd-2-clause", "hash": 3750313213256871400, "line_mean": 26.7333333333, "line_max": 79, "alpha_frac": 0.6893028846, "autogenerated": false, "ratio": 3.4238683127572016, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0035714285714285713, "num_lines": 60 }
from functools import wraps from django.shortcuts import ( render, get_object_or_404, ) from django.utils.decorators import available_attrs import frontdesk def with_deposit(func): @wraps(func, assigned=available_attrs(func)) def wrapper(request, deposit_id, *args, **kwargs): deposits = frontdesk.models.Deposit.objects.order_by('-created')[:999] if deposit_id: detailed_deposit = get_object_or_404( frontdesk.models.Deposit, pk=deposit_id) else: detailed_deposit = frontdesk.models.Deposit.objects.order_by( '-created').first() context = {'deposits': deposits, 'detailed_deposit': detailed_deposit} kwargs['context'] = context return func(request, deposit_id, *args, **kwargs) return wrapper def index(request, context=None): deposits = frontdesk.models.Deposit.objects.order_by('-created')[:999] context = {'deposits': deposits} return render(request, 'inbox/index.html', context) @with_deposit def package_report(request, deposit_id, context=None): return render(request, 'inbox/package_report.html', context) @with_deposit def package_report_virus(request, deposit_id, context=None): return render(request, 'inbox/package_report_virus.html', context) @with_deposit def package_report_integrity(request, deposit_id, context=None): return render(request, 'inbox/package_report_integrity.html', context) @with_deposit def package_report_scielops(request, deposit_id, context=None): return render(request, 'inbox/package_report_scielops.html', context)
{ "repo_name": "fabiobatalha/inbox", "path": "inbox/views.py", "copies": "2", "size": "1626", "license": "bsd-2-clause", "hash": -1773546721906767400, "line_mean": 27.5263157895, "line_max": 78, "alpha_frac": 0.6943419434, "autogenerated": false, "ratio": 3.4522292993630574, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5146571242763057, "avg_score": null, "num_lines": null }
from functools import wraps from django.template.response import TemplateResponse import logging def body_classes(func, *classes): """ Decorates a view by adding a list of class names to the ``<body>`` tag. The prefered way to use this is to pass in a view that returns a `TemplateResponse` object, so that the decorator can modify the context variable dictionary, adding a `body_classes` list, or extending it if it already exists. :param func: A callable that returns an ``HttpResponse`` or ``TemplateResponse`` object :param classes: A list of classes to add to the ``<body>`` tag Use this decorator in your URLconf like so:: from bambu_bootstrap.decorators import body_classes from testproject.myapp import views from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^$', body_classes(views.home, 'homepage', 'index')) ) """ @wraps(func) def wrapped_func(*args, **kwargs): response = func(*args, **kwargs) if response.status_code != 200 or not any(classes): return response if not isinstance(response, TemplateResponse): logger = logging.getLogger('bambu_bootstrap') logger.warning( 'body_classes decorator applied to incompatible view %s.%s. Falling back ' \ 'to dirty HTML injection' % ( func.__module__, func.__name__ ) ) content = response.content body_start = content.find('<body') if body_start > -1: body_end = content.find('>', body_start + 1) if body_end > -1: body = content[body_start:body_end] class_start = body.find('class="') if class_start > -1: class_start += len('class="') class_end = body.find('"', class_start) if class_end > -1: classlist = body[class_start:class_end].split(' ') classlist.extend(classes) classlist = ' '.join( [c for c in classlist if c and c.strip()] ) before_class = body_start + class_start after_class = body_start + class_end response.content = ''.join( ( content[:before_class], classlist, content[after_class:] ) ) else: if not response.context_data is None: body_classes = list(response.context_data.get('body_classes', [])) else: body_classes = [] response.context_data = {} body_classes.extend(classes) response.context_data['body_classes'] = body_classes return response return wrapped_func
{ "repo_name": "iamsteadman/bambu-bootstrap", "path": "bambu_bootstrap/decorators.py", "copies": "1", "size": "3235", "license": "apache-2.0", "hash": -8041229320904487000, "line_mean": 38.4634146341, "line_max": 104, "alpha_frac": 0.4908809892, "autogenerated": false, "ratio": 5.134920634920635, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6125801624120636, "avg_score": null, "num_lines": null }
from functools import wraps from django.test import TestCase from django.test.client import Client from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.core import mail from django.conf import settings from ummeli.vlive.jobs.parsers import CategoryParser, JobsParser from ummeli.opportunities.models import Job, Province from ummeli.vlive.jobs.tasks import run_jobs_update from ummeli.vlive.tests import jobs_test_data from ummeli.vlive.tests.utils import VLiveClient, VLiveTestCase class MockCategoryParser(CategoryParser): def get_html(self, url): if "search_source=2" in url: return self.tidy_html(jobs_test_data.categories_html1) return self.tidy_html(jobs_test_data.categories_html2) class MockJobsParser(JobsParser): def get_html(self, url): if "search_source=2" in url: return self.tidy_html(jobs_test_data.articles_html1) return self.tidy_html(jobs_test_data.articles_html2) class JobsTestCase(VLiveTestCase): fixtures = [ 'fixtures/opportunities.provinces.json', ] def setUp(self): self.msisdn = '27123456789' self.pin = '1234' self.client = VLiveClient(HTTP_X_UP_CALLING_LINE_ID=self.msisdn) self.client.login(remote_user=self.msisdn) settings.CELERY_ALWAYS_EAGER = True def tearDown(self): settings.CELERY_ALWAYS_EAGER = settings.DEBUG def test_job_data_creation(self): result = run_jobs_update.delay(MockCategoryParser, MockJobsParser) result.ready() result.successful() jobs = Job.objects.filter(category=1, province__province=Province.GAUTENG).count() self.assertEquals(jobs, 4) jobs = Job.objects.filter(province__province=Province.GAUTENG).count() self.assertEquals(jobs, 4) jobs = Job.objects.all().count() self.assertEquals(jobs, 9) resp = self.client.get(reverse('jobs_list')) self.assertContains(resp, 'Admin/Clerical') resp = self.client.get(reverse('jobs', args=[1])) self.assertContains(resp, 'Isando Bcom') slug = 'accounts-administrator-west-rand-kzn-limpopo-eebcompt-accounts-qualif-mon' resp = self.client.get(reverse('job', kwargs={'slug':slug})) self.assertContains(resp, 'Accounts Administrator West') def test_category_parser(self): items = JobsParser(html_str = jobs_test_data.articles_html1).parse() self.assertEquals(len(items), 4) self.assertRaises(Exception, CategoryParser(2, html_str = 'blah', url = 'blah')) def test_job_apply_via_email(self): self.register() self.login() self.fill_in_basic_info() # setup test data result = run_jobs_update.delay(MockCategoryParser, MockJobsParser) result.ready() result.successful() # apply via email slug = 'accounts-administrator-west-rand-kzn-limpopo-eebcompt-accounts-qualif-mon' self.client.post(reverse('opportunity_apply', kwargs={'slug':slug}), {'send_via':'email', 'send_to':'me@home.com'}) self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox[0].attachments), 1) self.assertEquals(mail.outbox[0].subject, 'CV for Test User') def test_job_apply_via_fax(self): self.register() self.login() self.fill_in_basic_info() # setup test data result = run_jobs_update.delay(MockCategoryParser, MockJobsParser) result.ready() result.successful() # apply via fax resp = self.client.get(reverse('jobs', args=[1])) slug = 'accounts-administrator-west-rand-kzn-limpopo-eebcompt-accounts-qualif-mon' resp = self.client.post(reverse('opportunity_apply', kwargs={'slug':slug}), {'send_via':'fax', 'send_to':'+27123456789'}) self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox[0].attachments), 1) self.assertEquals(mail.outbox[0].subject, 'CV for Test User') self.assertEqual(mail.outbox[0].to[0], '+27123456789@faxfx.net') # test special launch special (max 2 faxes per user) self.assertEqual(self.get_user().get_profile().nr_of_faxes_sent, 1) # negative test case for require send_to resp = self.client.post(reverse('opportunity_apply', kwargs={'slug':slug}), {'send_via':'fax', 'send_to':''}) self.assertContains(resp, 'Please enter a valid email')
{ "repo_name": "praekelt/ummeli", "path": "ummeli/vlive/tests/test_jobs.py", "copies": "1", "size": "4751", "license": "bsd-3-clause", "hash": 2715372809920308000, "line_mean": 37.9426229508, "line_max": 91, "alpha_frac": 0.6333403494, "autogenerated": false, "ratio": 3.6630686198920586, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47964089692920586, "avg_score": null, "num_lines": null }
from functools import wraps from django.utils.decorators import available_attrs from django.dispatch import Signal from uppsell.exceptions import CancelTransition, BadTransition pre_transition_signal = Signal(providing_args=["model", "key", "transition", "state"]) post_transition_signal = Signal(providing_args=["model", "key", "transition", "state"]) ALL = "__all__" def pre_transition(on_key, on_model, on_transition=ALL, on_state=ALL): def decorator(func): @wraps(func, assigned=available_attrs(func)) def inner(signal, key, transition, sender, model, state, **kwargs): if key == on_key and model.__class__ == on_model and on_transition in (transition, ALL) and on_state in (state, ALL): return func(signal, key, transition, sender, model, state) pre_transition_signal.connect(inner) return inner return decorator def post_transition(on_key, on_model, on_transition=ALL, on_state=ALL): def decorator(func): @wraps(func, assigned=available_attrs(func)) def inner(signal, key, transition, sender, model, state, **kwargs): if key == on_key and model.__class__ == on_model and on_transition in (transition, ALL) and on_state in (state, ALL): return func(signal, key, transition, sender, model, state) post_transition_signal.connect(inner) return inner return decorator class State(object): _manager, _state, _transitions = None, None, None def __init__(self, manager, state): self._manager = manager self._state = state self._transitions = {} def add_transition(self, transition, end_state): if self._transitions.get(transition): raise ValueError, u"State %s already has transition %s defined" \ % (self.__unicode__(), transition) self._transitions[transition] = end_state @property def transitions(self): return self._transitions def can(self, transition): return self._transitions.has_key(transition) def next(self, transition): if self.can(transition): return self._transitions[transition] return self def __unicode__(self): return self._state def __repr__(self): return "<State %s>"%self._state class Workflow(object): _model, _key, _states = None, None, None def __init__(self, model, key=u"state", transitions=[]): self._model, self._key = model, key self.set_transitions(transitions) @property def state(self): state_id = getattr(self._model, self._key) return self._states[state_id] def add_state(self, state): if self._states.get(state) is None: self._states[state] = State(self, state) return self._states[state] def set_transitions(self, transitions): self._states = {} for (transition, start, finish) in transitions: self.add_transition(transition, start, finish) return self def add_transition(self, transition, start, finish): self.add_state(start).add_transition(transition, self.add_state(finish)) return self def can(self, transition): return self.state.can(transition) @property def available(self): return self.state.transitions def do(self, transition, autosave=False): if not self.can(transition): raise BadTransition, u"Model %s in state %s cannot apply transition %s"\ % (self._model, self.state, transition) cur_state = self.state.__unicode__() next_state = self.state.next(transition).__unicode__() try: pre_transition_signal.send(self, model=self._model, key=self._key, \ transition=transition, state=cur_state) except CancelTransition: return setattr(self._model, self._key, next_state) if autosave: self._model.save() post_transition_signal.send_robust(self, model=self._model, key=self._key, \ transition=transition, state=next_state)
{ "repo_name": "upptalk/uppsell", "path": "uppsell/workflow.py", "copies": "1", "size": "4165", "license": "mit", "hash": 498682947621202240, "line_mean": 36.8636363636, "line_max": 129, "alpha_frac": 0.6228091236, "autogenerated": false, "ratio": 4.107495069033531, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0302180932597419, "num_lines": 110 }
from functools import wraps from django.utils.decorators import decorator_from_middleware_with_args, available_attrs from django.utils.cache import patch_cache_control, add_never_cache_headers from django.middleware.cache import CacheMiddleware def cache_page(*args, **kwargs): """ Decorator for views that tries getting the page from the cache and populates the cache if the page isn't in the cache yet. The cache is keyed by the URL and some data from the headers. Additionally there is the key prefix that is used to distinguish different cache areas in a multi-site setup. You could use the get_current_site().domain, for example, as that is unique across a Django project. Additionally, all headers from the response's Vary header will be taken into account on caching -- just like the middleware does. """ # We also add some asserts to give better error messages in case people are # using other ways to call cache_page that no longer work. if len(args) != 1 or callable(args[0]): raise TypeError("cache_page has a single mandatory positional argument: timeout") cache_timeout = args[0] cache_alias = kwargs.pop('cache', None) key_prefix = kwargs.pop('key_prefix', None) if kwargs: raise TypeError("cache_page has two optional keyword arguments: cache and key_prefix") return decorator_from_middleware_with_args(CacheMiddleware)( cache_timeout=cache_timeout, cache_alias=cache_alias, key_prefix=key_prefix ) def cache_control(**kwargs): def _cache_controller(viewfunc): @wraps(viewfunc, assigned=available_attrs(viewfunc)) def _cache_controlled(request, *args, **kw): response = viewfunc(request, *args, **kw) patch_cache_control(response, **kwargs) return response return _cache_controlled return _cache_controller def never_cache(view_func): """ Decorator that adds headers to a response so that it will never be cached. """ @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view_func(request, *args, **kwargs): response = view_func(request, *args, **kwargs) add_never_cache_headers(response) return response return _wrapped_view_func
{ "repo_name": "iambibhas/django", "path": "django/views/decorators/cache.py", "copies": "35", "size": "2294", "license": "bsd-3-clause", "hash": 8758202673488223000, "line_mean": 39.2456140351, "line_max": 94, "alpha_frac": 0.700087184, "autogenerated": false, "ratio": 4.140794223826715, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
from functools import wraps from django.utils import timezone from rest_framework import decorators, exceptions, response, status from nodeconductor.core import exceptions as core_exceptions from nodeconductor.core import models as core_models from nodeconductor.structure import ServiceBackendError from nodeconductor.structure import views as structure_views from . import models, serializers, filters from .backend import OracleBackendError from .log import event_logger States = models.Deployment.States def safe_operation(valid_state=None): def decorator(view_fn): @wraps(view_fn) def wrapped(self, request, *args, **kwargs): try: resource = self.get_object() structure_views.check_operation(request.user, resource, view_fn.__name__, valid_state) return view_fn(self, request, resource, *args, **kwargs) except OracleBackendError as e: resource.error_message = unicode(e) resource.set_erred() resource.save(update_fields=['state', 'error_message']) raise exceptions.APIException(e) return wrapped return decorator class OracleServiceViewSet(structure_views.BaseServiceViewSet): queryset = models.OracleService.objects.all() serializer_class = serializers.ServiceSerializer class OracleServiceProjectLinkViewSet(structure_views.BaseServiceProjectLinkViewSet): queryset = models.OracleServiceProjectLink.objects.all() serializer_class = serializers.ServiceProjectLinkSerializer class FlavorViewSet(structure_views.BaseServicePropertyViewSet): queryset = models.Flavor.objects.order_by('cores', 'ram', 'disk') serializer_class = serializers.FlavorSerializer lookup_field = 'uuid' class DeploymentViewSet(structure_views.BaseResourceViewSet): queryset = models.Deployment.objects.all() serializer_class = serializers.DeploymentSerializer filter_class = filters.DeploymentFilter def get_serializer_class(self): if self.action == 'resize': return serializers.DeploymentResizeSerializer elif self.action == 'support': return serializers.SupportSerializer return super(DeploymentViewSet, self).get_serializer_class() # XXX: overloaded base class method to skip emitting too generic event message def perform_create(self, serializer): service_project_link = serializer.validated_data['service_project_link'] if service_project_link.service.settings.state == core_models.SynchronizationStates.ERRED: raise core_exceptions.IncorrectStateException( detail='Cannot create resource if its service is in erred state.') try: self.perform_provision(serializer) except ServiceBackendError as e: raise exceptions.APIException(e) def perform_provision(self, serializer): resource = serializer.save() backend = resource.get_backend() try: ticket = backend.provision( resource, self.request, ssh_key=serializer.validated_data.get('ssh_public_key')) event_logger.resource.info( '{resource_full_name} creation has been scheduled (%s).' % ticket.key, event_type='resource_creation_scheduled', event_context={ 'resource': serializer.instance, }) except OracleBackendError as e: resource.error_message = unicode(e) resource.set_erred() resource.save(update_fields=['state', 'error_message']) raise resource.begin_provisioning() resource.save(update_fields=['state']) @decorators.detail_route(methods=['post']) @safe_operation(valid_state=States.PROVISIONING) def provision(self, request, resource, uuid=None): """ Complete provisioning. Example: .. code-block:: http POST /api/oracle-deployments/a04a26e46def4724a0841abcb81926ac/provision/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "report": "ORACONF=TST12DB\n\nDBTYPE=single\nDBNAME='TST12DB'" } """ report = request.data.get('report') if report: resource.report = report resource.start_time = timezone.now() resource.set_online() resource.save(update_fields=['report', 'start_time', 'state']) event_logger.oracle_deployment.info( 'Oracle deployment {deployment_name} report has been updated.', event_type='oracle_deployment_report_updated', event_context={ 'deployment': resource, } ) return response.Response({'detail': "Provision complete"}) else: return response.Response({'detail': "Empty report"}, status=status.HTTP_400_BAD_REQUEST) @decorators.detail_route(methods=['post']) @safe_operation() def update_report(self, request, resource, uuid=None): """ Update provisioning report. Example: .. code-block:: http POST /api/oracle-deployments/a04a26e46def4724a0841abcb81926ac/update_report/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "report": "ORACONF=TST12DB\n\nDBTYPE=single\nDBNAME='PRD12DB'" } """ if not self.request.user.is_staff: raise exceptions.PermissionDenied report = request.data.get('report') if report: resource.report = report resource.save(update_fields=['report']) event_logger.oracle_deployment.info( 'Oracle deployment {deployment_name} report has been updated.', event_type='oracle_deployment_report_updated', event_context={ 'deployment': resource, } ) return response.Response({'detail': "Report has been updated"}) else: return response.Response({'detail': "Empty report"}, status=status.HTTP_400_BAD_REQUEST) @decorators.detail_route(methods=['post']) @safe_operation() def support(self, request, resource, uuid=None): """ File custom support request. .. code-block:: http POST /api/oracle-deployments/a04a26e46def4724a0841abcb81926ac/support/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "message": "Could you make that DB running faster?\n\nThanks." } """ serializer = self.get_serializer(resource, data=request.data) serializer.is_valid(raise_exception=True) backend = resource.get_backend() ticket = backend.support_request(resource, self.request, serializer.validated_data['message']) # XXX: Switch this and below to a more standard resource_stop_scheduled / resource_stop_succeeded for ECC release event_logger.oracle_deployment.info( 'Support for Oracle deployment {deployment_name} has been requested ({jira_issue_key}).', event_type='oracle_deployment_support_requested', event_context={ 'deployment': resource, 'jira_issue_key': ticket.key, } ) return response.Response( {'detail': "Support request accepted", 'jira_issue_uuid': ticket.uuid.hex, 'jira_issue_key': ticket.key}, status=status.HTTP_202_ACCEPTED) @decorators.detail_route(methods=['post']) @safe_operation(valid_state=(States.ONLINE, States.RESIZING)) def resize(self, request, resource, uuid=None): """ Request for DB Instance resize. Example: .. code-block:: http POST /api/oracle-deployments/a04a26e46def4724a0841abcb81926ac/resize/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "flavor": "http://example.com/api/oracle-flavors/ef86802458684056b18576a91daf7690/" } To confirm resize completion, issue an empty POST request to the same endpoint. """ if resource.state == States.RESIZING: if not self.request.user.is_staff: raise exceptions.PermissionDenied resource.set_resized() resource.save(update_fields=['state']) event_logger.oracle_deployment.info( 'Resize request for Oracle deployment {deployment_name} has been fulfilled.', event_type='oracle_deployment_resize_succeeded', event_context={ 'deployment': resource, } ) return response.Response({'detail': "Resizing complete"}) serializer = self.get_serializer(resource, data=request.data) serializer.is_valid(raise_exception=True) resource.state = States.RESIZING_SCHEDULED resource.flavor = serializer.validated_data.get('flavor') resource.save(update_fields=['flavor', 'state']) backend = resource.get_backend() ticket = backend.resize(resource, self.request) resource.begin_resizing() resource.save(update_fields=['state']) event_logger.oracle_deployment.info( 'Resize request for Oracle deployment {deployment_name} has been submitted ({jira_issue_key}).', event_type='oracle_deployment_resize_requested', event_context={ 'deployment': resource, 'jira_issue_key': ticket.key, } ) return response.Response( {'detail': "Resizing scheduled", 'jira_issue_uuid': ticket.uuid.hex, 'jira_issue_key': ticket.key}, status=status.HTTP_202_ACCEPTED) @safe_operation(valid_state=(States.OFFLINE, States.DELETING)) def destroy(self, request, resource, uuid=None): """ Request for DB Instance deletion or confirm deletion success. A proper action will be taken depending on the current deployment state. """ if resource.state == States.DELETING: if not self.request.user.is_staff: raise exceptions.PermissionDenied self.perform_destroy(resource) return response.Response({'detail': "Deployment deleted"}) resource.schedule_deletion() resource.save(update_fields=['state']) backend = resource.get_backend() ticket = backend.destroy(resource, self.request) resource.begin_deleting() resource.save(update_fields=['state']) return response.Response( {'detail': "Deletion scheduled", 'jira_issue_uuid': ticket.uuid.hex, 'jira_issue_key': ticket.key}, status=status.HTTP_202_ACCEPTED) @decorators.detail_route(methods=['post']) @safe_operation(valid_state=(States.OFFLINE, States.STARTING)) def start(self, request, resource, uuid=None): """ Request for DB Instance starting or confirm starting success. A proper action will be taken depending on the current deployment state. """ if resource.state == States.STARTING: if not self.request.user.is_staff: raise exceptions.PermissionDenied else: resource.set_online() resource.save(update_fields=['state']) event_logger.oracle_deployment.info( 'Start request for Oracle deployment {deployment_name} has been fulfilled.', event_type='oracle_deployment_start_succeeded', event_context={ 'deployment': resource, } ) return response.Response({'detail': "Deployment started"}) resource.schedule_starting() resource.save(update_fields=['state']) backend = resource.get_backend() ticket = backend.start(resource, self.request) resource.begin_starting() resource.save(update_fields=['state']) event_logger.oracle_deployment.info( 'Start request for Oracle deployment {deployment_name} has been submitted ({jira_issue_key}).', event_type='oracle_deployment_start_requested', event_context={ 'deployment': resource, 'jira_issue_key': ticket.key, } ) return response.Response( {'detail': "Starting scheduled", 'jira_issue_uuid': ticket.uuid.hex, 'jira_issue_key': ticket.key}, status=status.HTTP_202_ACCEPTED) @decorators.detail_route(methods=['post']) @safe_operation(valid_state=(States.ONLINE, States.STOPPING)) def stop(self, request, resource, uuid=None): """ Request for DB Instance stopping or confirm stopping success. A proper action will be taken depending on the current deployment state. """ if resource.state == States.STOPPING: if not self.request.user.is_staff: raise exceptions.PermissionDenied else: resource.set_offline() resource.save(update_fields=['state']) event_logger.oracle_deployment.info( 'Stop request for Oracle deployment {deployment_name} has been fulfilled.', event_type='oracle_deployment_stop_succeeded', event_context={ 'deployment': resource, } ) return response.Response({'detail': "Deployment stopped"}) resource.schedule_stopping() resource.save(update_fields=['state']) backend = resource.get_backend() ticket = backend.stop(resource, self.request) resource.begin_stopping() resource.save(update_fields=['state']) event_logger.oracle_deployment.info( 'Stop request for Oracle deployment {deployment_name} has been submitted ({jira_issue_key}).', event_type='oracle_deployment_stop_requested', event_context={ 'deployment': resource, 'jira_issue_key': ticket.key, } ) return response.Response( {'detail': "Stopping scheduled", 'jira_issue_uuid': ticket.uuid.hex, 'jira_issue_key': ticket.key}, status=status.HTTP_202_ACCEPTED) @decorators.detail_route(methods=['post']) @safe_operation(valid_state=(States.ONLINE, States.RESTARTING)) def restart(self, request, resource, uuid=None): """ Request for DB Instance restarting or confirm restarting success. A proper action will be taken depending on the current deployment state. """ if resource.state == States.RESTARTING: if not self.request.user.is_staff: raise exceptions.PermissionDenied else: resource.set_online() resource.save(update_fields=['state']) event_logger.oracle_deployment.info( 'Restart request for Oracle deployment {deployment_name} has been fulfilled.', event_type='oracle_deployment_restart_succeeded', event_context={ 'deployment': resource, } ) return response.Response({'detail': "Deployment restarted"}) resource.schedule_restarting() resource.save(update_fields=['state']) backend = resource.get_backend() ticket = backend.restart(resource, self.request) resource.begin_restarting() resource.save(update_fields=['state']) event_logger.oracle_deployment.info( 'Restart request for Oracle deployment {deployment_name} has been submitted ({jira_issue_key}).', event_type='oracle_deployment_restart_requested', event_context={ 'deployment': resource, 'jira_issue_key': ticket.key, } ) return response.Response( {'detail': "Restarting scheduled", 'jira_issue_uuid': ticket.uuid.hex, 'jira_issue_key': ticket.key}, status=status.HTTP_202_ACCEPTED)
{ "repo_name": "opennode/nodeconductor-paas-oracle", "path": "src/nodeconductor_paas_oracle/views.py", "copies": "1", "size": "17004", "license": "mit", "hash": -8698023292541689000, "line_mean": 39.5823389021, "line_max": 121, "alpha_frac": 0.6088567396, "autogenerated": false, "ratio": 4.556270096463023, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5665126836063024, "avg_score": null, "num_lines": null }
from functools import wraps from django.views.decorators.cache import cache_page from django.utils.decorators import available_attrs def cache_page_on_auth(timeout): """ uses cache_page for both logged in and logged out users but different cache if you are logged in or not """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): return cache_page(timeout, key_prefix="_auth_{key}_".format( key=request.user.is_authenticated()) )(view_func)(request, *args, **kwargs) return _wrapped_view return decorator def cache_page_for_user(timeout): """ uses cache_page for both logged in and logged out users but different cache for each logged in user """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): return cache_page(timeout, key_prefix="_auth_{key}_".format( key=request.user.pk) )(view_func)(request, *args, **kwargs) return _wrapped_view return decorator
{ "repo_name": "moshthepitt/product.co.ke", "path": "core/decorators.py", "copies": "2", "size": "1186", "license": "mit", "hash": 2811649265011421700, "line_mean": 34.9393939394, "line_max": 72, "alpha_frac": 0.6441821248, "autogenerated": false, "ratio": 3.993265993265993, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 33 }
from functools import wraps from elasticsearch.exceptions import NotFoundError from flask import abort def index_exists(es, index_name): if not es.indices.exists(index=index_name): raise Exception("Index does not exist") def needs_es(index_name=None): def inner_function(function=None): @wraps(function) def wrapper(*args, **kwargs): if index_name is not None: # TODO pre-check, might not be necessary pass try: return function(*args, **kwargs) except NotFoundError as e: not_found = getattr(e, "info", {}).get("error", {}).get("root_cause", [{}])[0].get("resource.id", None) message = "The required index does not exist in this ElasticSearch database" if not_found is not None: message = message + " (" + str(not_found) + ")" abort(404, message) return wrapper if index_name is not None and not isinstance(index_name, str): return inner_function(index_name) else: return inner_function def verify_es_response(response): # if the query took 0 it means no index could be matched! if response.took == 0: raise NotFoundError(404, 'index_not_found_exception', {}) # if no hits were found, operation_id was invalied if len(response.hits) == 0: abort(404, "Your search did not result in any hits (wrong id?)")
{ "repo_name": "oxarbitrage/bitshares-python-api-backend", "path": "api/utils.py", "copies": "1", "size": "1476", "license": "mit", "hash": -2937978983900365000, "line_mean": 35, "line_max": 119, "alpha_frac": 0.6029810298, "autogenerated": false, "ratio": 4.146067415730337, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5249048445530337, "avg_score": null, "num_lines": null }
from functools import wraps from .exceptions import PyCondition, PyConditionError from .inspector import Gadget from .stage import Stage class PostCondition(object): def __call__(self, func): stage = Stage() self.name = "%s.%s" % (func.__module__, func.__name__) gadget = Gadget(func) doc = gadget.gogoDoc() if(not doc and stage.name == "Dev"): doc = "" doc += "%s - %s\n" % (self.name, self.__class__.__name__) func.__doc__ = doc @wraps(func) def wrapper(*args, **kwargs): returnValue = func(*args, **kwargs) if(stage.name == "Dev"): self.assertCondition(returnValue) return returnValue wrapper._original_func = func return wrapper def assertCondition(self, returnValue): pass class NotNone(PostCondition): def assertCondition(self, returnValue): if(returnValue is None): raise PyCondition("The return value for %s was None" % self.name) class Custom(PostCondition): def __init__(self, custom): self.custom = custom def assertCondition(self, returnValue): if(not self.custom(returnValue)): raise PyCondition( "The custom condition did not hold for %s" % self.name) class NotEmpty(PostCondition): def assertCondition(self, returnValue): if(len(returnValue) == 0): raise PyCondition( "The return value was empty, meaning the length was 0 for %s" % self.name)
{ "repo_name": "streed/pyConditions", "path": "pyconditions/post.py", "copies": "1", "size": "1593", "license": "apache-2.0", "hash": -1595379422990112800, "line_mean": 25.1147540984, "line_max": 79, "alpha_frac": 0.5775266792, "autogenerated": false, "ratio": 4.1484375, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.52259641792, "avg_score": null, "num_lines": null }
from functools import wraps from fabric.decorators import _wrap_as_new from .ec2.api import Ec2InstanceWrapper try: unicode = unicode except NameError: basestring = (str, bytes) def _list_annotating_decorator(attribute, *values): def attach_list(func): @wraps(func) def inner_decorator(*args, **kwargs): return func(*args, **kwargs) _values = values # Allow for single iterable argument as well as *args if len(_values) == 1 and not isinstance(_values[0], basestring): _values = _values[0] setattr(inner_decorator, attribute, list(_values)) # Don't replace @task new-style task objects with inner_decorator by # itself -- wrap in a new Task object first. inner_decorator = _wrap_as_new(func, inner_decorator) return inner_decorator return attach_list def ec2instance(nametag=None, instanceid=None, tags=None, region=None): """ Wraps the decorated function to execute as if it had been invoked with ``--ec2names`` or ``--ec2ids``. """ instancewrappers = [] if instanceid: instancewrappers += [Ec2InstanceWrapper.get_by_instanceid(instanceid)] if nametag: instancewrappers += [Ec2InstanceWrapper.get_by_nametag(nametag)] if tags: instancewrappers += Ec2InstanceWrapper.get_by_tagvalue(tags, region) if not (instanceid or nametag or tags): raise ValueError('nametag, instanceid, or tags must be supplied.') return _list_annotating_decorator('hosts', [instancewrapper['public_dns_name'] for instancewrapper in instancewrappers])
{ "repo_name": "espenak/awsfabrictasks", "path": "awsfabrictasks/decorators.py", "copies": "2", "size": "1636", "license": "bsd-3-clause", "hash": -2123405500052233000, "line_mean": 35.3555555556, "line_max": 82, "alpha_frac": 0.6687041565, "autogenerated": false, "ratio": 3.9902439024390244, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.005156626506024097, "num_lines": 45 }
from functools import wraps from FFI import * from ctypes.util import find_library from weakref import WeakKeyDictionary libs = {} _wkdict_ = WeakKeyDictionary() def load_lib(api=None): ''' api's are EGL, GL, GLESv2, GLESv1_CM, GLX ''' ffi = globals()["_" + api.lower().replace('v', '') + "ffi"].ffi return ffi, ffi.dlopen(find_library(api)) def _new(api, func, args, prm_inx, prm_name): p = libs[api][1].typeof(func).args[prm_inx].cname.split() if len(libs[api][3]) != 0 and prm_name in sum(libs[api][3].values(), []): x = {i: k for k, v in libs[api][3].items() for i in v}[prm_name] n_pr = libs[api][1].new(' '.join(p[:-1]) + '[{}]'.format(args[x])) _wkdict_[n_pr] = prm_name return n_pr else: n_pr = libs[api][1].new(' '.join(p)) _wkdict_[n_pr] = prm_name return n_pr def _cast(api, func, prm_inx, prm): p = libs[api][1].typeof(func).args[prm_inx].cname.split() ptr = libs[api][1].cast(' '.join(p), prm) _wkdict_[ptr] = prm return ptr def params(*largs, **lkwargs): def decorator(func): @wraps(func) def wrapper(*args): ret_dict = {} prms = list(lkwargs['prms']) api = lkwargs['api'] f = getattr(libs[lkwargs['api']][0], func.__name__) arg_dict = dict(zip(func.func_code.co_varnames, args)) for i, pr in enumerate(prms): if pr in arg_dict.keys(): prms[i] = arg_dict[pr] else: prms[i] = _new(api, f, arg_dict, i, pr) if pr in libs[api][2]: ret_dict[pr] = prms[i] ret = f(*prms) if isinstance(ret, libs[api][1].CData): if libs[api][1].typeof(ret).kind == 'pointer': if len(ret_dict) > 0: return ret, ret_dict else: return ret else: return ret, ret_dict elif len(ret_dict) > 0: return ret_dict else: return ret return wrapper return decorator
{ "repo_name": "cydenix/OpenGLCffi", "path": "OpenGLCffi/__init__.py", "copies": "2", "size": "2196", "license": "mit", "hash": 4787526405277967000, "line_mean": 31.2941176471, "line_max": 77, "alpha_frac": 0.487704918, "autogenerated": false, "ratio": 3.302255639097744, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4789960557097744, "avg_score": null, "num_lines": null }
from functools import wraps from flask.ext.login import LoginManager, AnonymousUserMixin, login_user, logout_user, current_user from flask import jsonify from flask.ext.bcrypt import Bcrypt from flask.ext.api.status import HTTP_401_UNAUTHORIZED from project.services.database import Database from project.services.social_signin import SocialSignin from project.strings import resource_strings from bson.objectid import ObjectId from functools import wraps class Auth: GHOST = 0 USER = 1 ADMIN = 2 SUPER_ADMIN = 3 class Anonymous(AnonymousUserMixin): def __init__(self): self._id = None def get_id(self): return unicode('') def __init__(self): self.__login_manager = LoginManager() self.config = {} def init_app(self, app, config): print 'Attaching LoginManager to app.' self.__login_manager.init_app(app) self.__login_manager.anonymous_user = Auth.Anonymous self.config = config def load_user(user_id): if user_id == '': return None Users = Database['Users'] try: return Users.User.find_one({'_id': ObjectId(user_id)}) except: return None def unauthorized(): return jsonify(error='Unauthorized'), HTTP_401_UNAUTHORIZED self.__login_manager.user_loader(load_user) self.__login_manager.unauthorized_handler(unauthorized) self.__bcrypt = Bcrypt(app) def login_manager(self): return self.__login_manager def require(self, user_level): def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if current_user.is_authenticated() and current_user.get_access_level() >= user_level: return f(*args, **kwargs) return self.__login_manager.unauthorized() return decorated_function return login_required def login(self, user_object, password): if user_object is not None: if self.__bcrypt.check_password_hash(user_object['password'], password): if not login_user(user_object): return resource_strings["USER_NOT_ACTIVATED"] else: return 'Invalid password' else: return 'Invalid email' return None def login_social(self, login_type, token): user_object = None try: user_object = SocialSignin.verify(login_type, token) except SocialSignin.Invalid as e: return str(e) login_user(user_object) def logout(self): logout_user() def hash_password(self, password): return self.__bcrypt.generate_password_hash(password) # decorator that protects other users from PUT/POST/DELETE on you stuff # user_id _must_ be passed in as 'user_id' def only_me(self, function): @wraps(function) def inner(*args, **kwargs): if kwargs['user_id'] != 'me': return '{}', HTTP_401_UNAUTHORIZED return function(*args, **kwargs) return inner # singleton (soft enforcement) Auth = Auth()
{ "repo_name": "AustinStoneProjects/Founderati-Server", "path": "project/services/auth.py", "copies": "1", "size": "3239", "license": "apache-2.0", "hash": 1528732994053844700, "line_mean": 29.8476190476, "line_max": 101, "alpha_frac": 0.6023464032, "autogenerated": false, "ratio": 4.217447916666667, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0014571161798052554, "num_lines": 105 }
from functools import wraps from flask.ext.restful import unpack from flask_presst.api import PresstApi from flask_presst.resources import PresstResource, ModelResource, PolymorphicModelResource from flask_presst.nesting import Relationship, resource_method from flask_presst.parsing import PresstArgument from flask_presst.references import Reference __all__ = ( 'PresstApi', 'PresstResource', 'ModelResource', 'PolymorphicModelResource', 'Relationship', 'resource_method', 'PresstArgument', 'Reference', 'marshal_with_field', ) class marshal_with_field(object): """ A decorator that formats the return values of your methods using a single field. >>> from flask.ext.presst import marshal_with_field, fields >>> @marshal_with_field(fields.List(fields.Integer)) ... def get(): ... return ['1', 2, 3.0] ... >>> get() [1, 2, 3] """ def __init__(self, field): """ :param field: a single field with which to marshal the output. """ if isinstance(field, type): self.field = field() else: self.field = field def __call__(self, f): @wraps(f) def wrapper(*args, **kwargs): resp = f(*args, **kwargs) if isinstance(resp, tuple): data, code, headers = unpack(resp) return self.field.format(data), code, headers return self.field.format(resp) return wrapper
{ "repo_name": "svenstaro/flask-presst", "path": "flask_presst/__init__.py", "copies": "1", "size": "1499", "license": "mit", "hash": -3104492939547071500, "line_mean": 25.7857142857, "line_max": 90, "alpha_frac": 0.6164109406, "autogenerated": false, "ratio": 3.955145118733509, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5071556059333509, "avg_score": null, "num_lines": null }
from functools import wraps from flask import abort, jsonify from flask_login import current_user from threading import Thread from .models import User from .utils import Permission def token_required(parser, permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): args = parser.parse_args() user = User.verify_auth_token(args["Token"]) if user: if user.can(permission): return f(*args, **kwargs) else: abort(403) else: abort(401) return decorated_function return decorator def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def json(f): @wraps(f) def decorated_function(*args, **kwargs): rv = f(*args, **kwargs) status = None headers = None if isinstance(rv, tuple): rv, status, headers = rv + (None,) * (3 - len(rv)) if isinstance(status, (dict, list)): headers, status = status, None # if not isinstance(rv, dict): # rv = rv.export_data() rv = jsonify(rv) if status is not None: rv.status_code = status if headers is not None: rv.headers.extend(headers) return rv return decorated_function def admin_required(f): return permission_required(Permission.ADMINISTER)(f) def async(f): def wrapper(*args, **kwargs): thr = Thread(target=f, args=args, kwargs=kwargs) thr.start() return wrapper
{ "repo_name": "slobodz/TeamServices", "path": "project/server/decorators.py", "copies": "1", "size": "1823", "license": "mit", "hash": -782913734283104600, "line_mean": 27.9523809524, "line_max": 62, "alpha_frac": 0.5666483818, "autogenerated": false, "ratio": 4.279342723004695, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5345991104804695, "avg_score": null, "num_lines": null }
from functools import wraps from flask import abort from flask.ext.login import current_user from .models import Permission from datetime import timedelta from flask import make_response, request, current_app from functools import update_wrapper def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True): if methods is not None: methods = ', '.join(sorted(x.upper() for x in methods)) if headers is not None and not isinstance(headers, basestring): headers = ', '.join(x.upper() for x in headers) if not isinstance(origin, basestring): origin = ', '.join(origin) if isinstance(max_age, timedelta): max_age = max_age.total_seconds() def get_methods(): if methods is not None: return methods options_resp = current_app.make_default_options_response() return options_resp.headers['allow'] def decorator(f): def wrapped_function(*args, **kwargs): if automatic_options and request.method == 'OPTIONS': resp = current_app.make_default_options_response() else: resp = make_response(f(*args, **kwargs)) if not attach_to_all and request.method != 'OPTIONS': return resp h = resp.headers h['Access-Control-Allow-Origin'] = origin h['Access-Control-Allow-Methods'] = get_methods() h['Access-Control-Max-Age'] = str(max_age) if headers is not None: h['Access-Control-Allow-Headers'] = headers return resp f.provide_automatic_options = False return update_wrapper(wrapped_function, f) return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f)
{ "repo_name": "Spandex-at-Exeter/demography_database", "path": "app/decorators.py", "copies": "1", "size": "2156", "license": "mit", "hash": 5009657004965162000, "line_mean": 33.2380952381, "line_max": 67, "alpha_frac": 0.6196660482, "autogenerated": false, "ratio": 4.312, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005619206747026295, "num_lines": 63 }
from functools import wraps from flask import abort, request, current_app from flask.ext.login import current_user from .models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f) def jsonp(func): """Wraps JSONified output for JSONP requests.""" @wraps(func) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callback: data = str(func(*args, **kwargs).data) content = str(callback) + '(' + data + ')' mimetype = 'application/javascript' return current_app.response_class(content, mimetype=mimetype) else: return func(*args, **kwargs) return decorated_function
{ "repo_name": "codeforamerica/westsac-farm-stand", "path": "app/decorators.py", "copies": "2", "size": "1044", "license": "mit", "hash": -3036811290450667000, "line_mean": 32.7096774194, "line_max": 73, "alpha_frac": 0.6340996169, "autogenerated": false, "ratio": 4.331950207468879, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.596604982436888, "avg_score": null, "num_lines": null }
from functools import wraps from flask import Blueprint, render_template, request, redirect, session import flask_keystoneauth app = Blueprint('website', __name__, template_folder='templates') from flask import current_app keystone_auth = flask_keystoneauth.KeystoneAuth(current_app) def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ return keystone_auth.authenticate(username, password) def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth_token = session.get('authorized', None) if not auth_token: return redirect('login') return f(*args, **kwargs) return decorated @app.route("/") def index(): return render_template('index.html') @app.route('/secret') @requires_auth def secret_page(): return render_template('secret.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') if check_auth(username, password): return redirect('/') # return render_template('login.html') return render_template('login.html') @app.route("/logout") def logout(): keystone_auth.invalidate() request.authorization = None return redirect('/')
{ "repo_name": "e0ne/flask-keystone-sample", "path": "flaskkeystone/views.py", "copies": "1", "size": "1392", "license": "apache-2.0", "hash": -1863290295398214700, "line_mean": 22.593220339, "line_max": 72, "alpha_frac": 0.6602011494, "autogenerated": false, "ratio": 4.023121387283237, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.001149425287356322, "num_lines": 59 }
from functools import wraps from flask import Blueprint, request, abort, jsonify from flask import make_response, json, current_app from flask.views import MethodView from flask.ext.restful import marshal from bson.objectid import ObjectId from datetime import datetime import pyotp from ..common import ApiException from ..extensions import bcrypt, provider, totp from ..database import ResourceOwner as User, Client, Device from ..database import get_user_or_abort, get_client_or_abort, get_device_or_abort from .utils import parser, user_fields, device_fields api = Blueprint("api", __name__) @api.errorhandler(ApiException) def handle_api_exception(error): data = { "flag": "fail", "msg": error.msg, } resp = make_response(json.dumps(data), error.code) resp.headers["Content-Type"] = "application/json" return resp def require_oauth(f): @wraps(f) def deco(*args, **kwargs): if "TESTING_WITHOUT_OAUTH" in current_app.config: return f(*args, **kwargs) else: decorator = provider.require_oauth(realm="users") meth = decorator(f) return meth(*args, **kwargs) return deco class Seed(MethodView): def post(self): """Register a new user account.""" args = parser.parse_args() if not totp.verify(args["otp"]): raise ApiException( code=400, msg="OTP incorrect, expect {}, got {}".format(totp.now(), args["otp"]), ) # gather user, client and device client = Client.find_one({"client_key": args["consumer_key"]}) if not client: raise ApiException( code=400, msg="Client key not found: {}".format(args["consumer_key"]), ) user = User() user.client_ids.append(client["_id"]) User.save(user) return jsonify({ "flag": "success", "user_id": str(user["_id"]), }) class Myself(MethodView): decorators = [require_oauth] def put(self): user = get_user_or_abort() args = parser.parse_args() if args["name"]: user["name"] = args["name"] if args["email"]: user["email"] = args["email"] if args["password"]: user["pw_hash"] = bcrypt.generate_password_hash(args["password"]) user["updated_since"] = datetime.utcnow() User.save(user) return jsonify({ "flag": "success", "res": marshal(user, user_fields), }) def get(self): user = get_user_or_abort() return jsonify({ "flag": "success", "res": marshal(user, user_fields), }) class DeviceList(MethodView): decorators = [require_oauth] def put(self, device_id): if device_id is None: raise ApiException( code=400, msg="Does not support updating multiple devices", ) elif device_id == "from_access_token": device = get_device_or_abort() else: device = Device.find_one({'_id': ObjectId(device_id)}) if not device: raise ApiException( code=404, msg="Device {} doesn't exist".format(device_id), ) args = parser.parse_args() if args["name"]: device["name"] = args["name"] if args["description"]: device["description"] = args["description"] if args["vendor"]: device["vendor"] = args["vendor"] if args["model"]: device["model"] = args["model"] device["updated_since"] = datetime.utcnow() Device.save(device) return jsonify({ "flag": "success", "res": marshal(device, device_fields), }) def get(self, device_id): if device_id is None: user = get_user_or_abort() devices = Device \ .find({'_id': {'$in': [oid for oid in user.device_ids]}}) \ .sort('updated_since', -1) devices_marshaled = [] for device in devices: devices_marshaled.append(marshal(device, device_fields)) return jsonify({ "flag": "success", "res": devices_marshaled, }) elif device_id == "from_access_token": device = get_device_or_abort() return jsonify({ "flag": "success", "res": marshal(device, device_fields), }) else: device = Device.find_one({'_id': ObjectId(device_id)}) if not device: raise ApiException( code=404, msg="Device {} doesn't exist".format(device_id), ) return jsonify({ "flag": "success", "res": marshal(device, device_fields), }) api.add_url_rule("/v1/seeds", view_func=Seed.as_view("seeds")) device_list_view = DeviceList.as_view("devices") api.add_url_rule("/v1/devices", defaults={"device_id": None}, view_func=device_list_view, methods=["GET",]) api.add_url_rule("/v1/devices/<string:device_id>", view_func=device_list_view, methods=["GET", "PUT"]) api.add_url_rule("/v1/device", defaults={"device_id": "from_access_token"}, view_func=device_list_view, methods=["GET", "PUT"]) api.add_url_rule("/v1/me", view_func=Myself.as_view("myself"), methods=["GET", "PUT"])
{ "repo_name": "Avamagic/mgserver-web-api", "path": "mgserver/api/views.py", "copies": "1", "size": "5902", "license": "bsd-3-clause", "hash": 8143441738089623000, "line_mean": 30.0631578947, "line_max": 87, "alpha_frac": 0.5116909522, "autogenerated": false, "ratio": 4.18581560283688, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5197506555036879, "avg_score": null, "num_lines": null }
from functools import wraps from flask import current_app, flash, request, abort from flask.ext.login import current_user def send_email(to, subject, text_body, html_body): if current_app.config['EMAIL_METHOD'].lower() == "smtp": send_email_smtp(to, subject, text_body, html_body) elif current_app.config['EMAIL_METHOD'].lower() == "mailgun": send_email_mailgun(to, subject, text_body, html_body) def send_email_smtp(to, subject, text_body, html_body): from flask.ext.mail import Message from auth import mail msg = Message(subject, recipients=to) msg.body = text_body msg.html = html_body mail.send(msg) def send_email_mailgun(to, subject, text_body, html_body): import requests data = { "from": current_app.config['MG_FROM'], "to": to, "subject": subject, "text": text_body, "html": html_body } requests.post( current_app.config['MG_ENDPOINT'], auth=("api", current_app.config['MG_API']), data=data ) def flash_errors(form): for field, errors in form.errors.items(): for error in errors: flash(u"Error in the %s field - %s" % ( getattr(form, field).label.text, error )) def superuser_required(f): @wraps(f) def decorated_function(*args, **kwargs): if current_user is None: return redirect(url_for('login', next=request.url)) elif not current_user.superuser: abort(403) else: return f(*args, **kwargs) return decorated_function
{ "repo_name": "hreeder/WHAuth", "path": "auth/utils.py", "copies": "1", "size": "1610", "license": "mit", "hash": 2880242994520722400, "line_mean": 27.7678571429, "line_max": 65, "alpha_frac": 0.6031055901, "autogenerated": false, "ratio": 3.6507936507936507, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47538992408936503, "avg_score": null, "num_lines": null }
from functools import wraps from flask import current_app, g, request, redirect, url_for, session, _app_ctx_stack, _request_ctx_stack from werkzeug.local import LocalProxy from models import User, Project, Experiment from urlparse import urlparse current_project = LocalProxy(lambda: _get_project()) current_experiment = LocalProxy(lambda: _get_experiment()) next_backend_global_host = LocalProxy(lambda: urlparse(request.url).hostname) class Current(object): ''' Manages the current project and experiment that a user is navigating. Requires a project_loader: ::\n @current.project_loader def load_project(project_id): return Project.objects(name = project_id)[0] ''' def __init__(self, app=None, add_context_processor=True): self.project_callback = None self.experiment_callback = None if app is not None: self.init_app(app, add_context_processor) def init_app(self, app, add_context_processor=True): app.current = self if add_context_processor: app.context_processor(_project_context_processor) app.context_processor(_experiment_context_processor) def project_loader(self, loader): self.project_callback = loader def experiment_loader(self, loader): self.experiment_callback = loader def set_project(project = None, project_id = None): ''' Set's the project as the current project. Either the project object or the project_id can be passed to this. ''' # Now add this project to the app context stack if not project == None: session['project_id'] = project.id elif not project_id == None: if current_app.current.project_callback == None: raise Exception("Please register a project loader method using the Current.project_loader decorator") session['project_id'] = project_id else: del session['project_id'] # raise Exception(" Either project_id or project object must be provided") def set_experiment(experiment = None, experiment_id = None): ''' Set's the experiment as the current experiment. Either the experiment object or the exp_uid can be passed to this. ''' # Now add this project to the app context stack if not experiment == None: session['experiment_id'] = experiment.id elif not experiment_id == None: if current_app.current.experiment_callback == None: raise Exception("Please register an experiment loader method using the Current.experiment_loader decorator") session["experiment_id"] = experiment_id else: del session["experiment_id"] # raise Exception(" Either experiment_id or experiment object must be provided") def project_required(func): ''' Decorator for a view to ensure that a project is active. If a project is not available, will kick the user to their dashboard. ''' @wraps(func) def decorated_view(*args, **kwargs): if current_project == None: # Eventually generalize this!! return redirect(url_for('dashboard._dashboard')) return func(*args, **kwargs) return decorated_view def experiment_required(func): ''' Decorator for a view to ensure that a project is active. If a project is not available, will kick the user to their dashboard. ''' @wraps(func) def decorated_view(*args, **kwargs): if current_experiment == None: # Eventually generalize this!! return redirect(url_for('dashboard._dashboard')) return func(*args, **kwargs) return decorated_view def _project_context_processor(): return dict(current_project=_get_project()) def _experiment_context_processor(): return dict(current_experiment=_get_experiment()) def _get_project(): if 'project_id' in session.keys(): return current_app.current.project_callback(session['project_id']) else: return None def _get_experiment(): if 'experiment_id' in session.keys(): return current_app.current.experiment_callback(session['experiment_id']) else: return None
{ "repo_name": "kgjamieson/NEXT-psych", "path": "gui/base/current.py", "copies": "1", "size": "4193", "license": "apache-2.0", "hash": -4006489114642162700, "line_mean": 35.1465517241, "line_max": 130, "alpha_frac": 0.6670641545, "autogenerated": false, "ratio": 4.27420998980632, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5441274144306321, "avg_score": null, "num_lines": null }
from functools import wraps from flask import flash, redirect, jsonify, \ session, url_for, Blueprint, make_response from project import db from project.models import Task api_blueprint = Blueprint('api', __name__) def login_required(test): @wraps(test) def wrap(*args, **kwargs): if 'logged_in' in session: return test(*args, **kwargs) else: flash('You need to login first.') return redirect(url_for('users.login')) return wrap def open_tasks(): return db.session.query(Task).filter_by( status='1').order_by(Task.due_date.asc()) def closed_tasks(): return db.session.query(Task).filter_by( status='0').order_by(Task.due_date.asc()) @api_blueprint.route('/api/v1/tasks/') def api_tasks(): results = db.session.query(Task).limit(10).offset(0).all() json_results = [] for result in results: data = { 'task_id': result.task_id, 'task name': result.name, 'due date': str(result.due_date), 'priority': result.priority, 'posted date': str(result.posted_date), 'status': result.status, 'user id': result.user_id } json_results.append(data) return jsonify(items=json_results) @api_blueprint.route('/api/v1/tasks/<int:task_id>') def task(task_id): result = db.session.query(Task).filter_by(task_id=task_id).first() if result: result = { 'task_id': result.task_id, 'task name': result.name, 'due date': str(result.due_date), 'priority': result.priority, 'posted date': str(result.posted_date), 'status': result.status, 'user id': result.user_id } code = 200 else: result = {"error": "Element does not exist"} code = 404 return make_response(jsonify(result), code)
{ "repo_name": "azaleas/Flasktaskr", "path": "project/api/views.py", "copies": "1", "size": "1925", "license": "mit", "hash": -6769992104787919000, "line_mean": 28.1666666667, "line_max": 70, "alpha_frac": 0.5797402597, "autogenerated": false, "ratio": 3.6389413988657844, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4718681658565784, "avg_score": null, "num_lines": null }
from functools import wraps from flask import flash, redirect, url_for, render_template from flask_login import current_user def root_required(func): @wraps(func) def wrapper(*args, **kwargs): if current_user.power == 3: return func(*args, **kwargs) else: flash("您请求的页面与您当前用户身份不符") return redirect(url_for('main.index')) return wrapper def manager_required(func): @wraps(func) def wrapper(*args, **kwargs): if current_user.power == 3: return func(*args, **kwargs) else: flash("您请求的页面与您当前用户身份不符") return redirect(url_for('main.index')) return wrapper def user_required(func): @wraps(func) def wrapper(*args, **kwargs): if current_user.power == 1: return func(*args, **kwargs) else: flash("您请求的页面与您当前用户身份不符") return redirect(url_for('main.index')) return wrapper
{ "repo_name": "lvhuiyang/cxcy-ims", "path": "app/decorators.py", "copies": "1", "size": "1058", "license": "apache-2.0", "hash": -3546080307848899000, "line_mean": 23.6666666667, "line_max": 59, "alpha_frac": 0.5904365904, "autogenerated": false, "ratio": 3.1540983606557376, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42445349510557373, "avg_score": null, "num_lines": null }
from functools import wraps from flask import Flask, g, request, session, redirect, url_for from samil import app from samil.db import * app.secret_key = b'\xf4\x96n\x8d7\xbcp\x8a\xca\x84\x17U\x98\x17\x06\x98\xf2\xc6\fc\xda\x9a\xfcm' def getfootermsg(): if 'sessionkey' in session: sessionkey = session["sessionkey"] if checksessionkey(sessionkey): footermsg = "| <a href=\"/logout\">로그아웃</a>" else: session.pop('sessionkey', None) footermsg = "| <a href=\"/login\">로그인</a>" else: footermsg = "| <a href=\"/login\">로그인</a>" return footermsg def isvalidsession(): if 'sessionkey' in session: sessionkey = session["sessionkey"] if checksessionkey(sessionkey): return True return False def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): isvs = isvalidsession() if not isvs: return redirect(url_for('login', next=request.url)) return f(*args, **kwargs) return decorated_function def put_accesslog(f): @wraps(f) def decorated_function(*args, **kwargs): print("request.headers.get('User-agent'): " + str(request.headers.get('User-agent'))) print("request.user_agent: " + str(request.user_agent)) return f(*args, **kwargs) return decorated_function
{ "repo_name": "ffee21/samil", "path": "samil/security.py", "copies": "1", "size": "1399", "license": "mit", "hash": 6202181147535991000, "line_mean": 30.3636363636, "line_max": 96, "alpha_frac": 0.6171138506, "autogenerated": false, "ratio": 3.2370892018779345, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9286437208642409, "avg_score": 0.013553168767105373, "num_lines": 44 }
from functools import wraps from flask import Flask, jsonify, request, abort from flask_api import FlaskAPI app = FlaskAPI(__name__) ctx = None def error(e): return {"error": e} def marketstr(market): return "%s_%s" % (market["base"], market["quote"]) @app.route("/public") def public(): command = request.args.get("command") if command == "returnTicker": r = {} for pair in ctx.pairs: market = Market(pair, bitshares_instance=ctx.bitshares) mstr = marketstr(market) ticker = market.ticker() r[mstr] = { "last": ticker["last"], "lowestAsk": ticker["lowestAsk"], "highestBid": ticker["highestBid"], "percentChange": ticker["percentChange"], "baseVolume": ticker["baseVolume"], "quoteVolume": ticker["quoteVolume"], } return r elif command == "return24Volume": r = {} total = {} for pair in ctx.pairs: market = Market(pair, bitshares_instance=ctx.bitshares) mstr = marketstr(market) ticker = market.ticker() base = market["base"]["symbol"] quote = market["quote"]["symbol"] total["base"] = total.get("base", 0) + ticker["baseVolume"] total["quote"] = total.get("quote", 0) + ticker["quoteVolume"] r[mstr] = {base: ticker["baseVolume"], quote: ticker["quoteVolume"]} for symbol, value in total.items(): r["total%s" % symbol] = value return r elif command == "returnOrderBook": """ https://poloniex.com/public?command=returnOrderBook&currencyPair=BTC_NXT&depth=10 """ """ {"asks":[[0.00007600,1164],[0.00007620,1300], ... ], "bids":[[0.00006901,200],[0.00006900,408], ... ], "isFrozen": 0, "seq": 18849} {"BTC_NXT":{"asks":[[0.00007600,1164],[0.00007620,1300], ... ], "bids":[[0.00006901,200],[0.00006900,408], ... ], "isFrozen": 0, "seq": 149},"BTC_XMR":...} """ pass elif command == "returnTradeHistory": """ Call: https://poloniex.com/public?command=returnTradeHistory&currencyPair=BTC_NXT&start=1410158341&end=1410499372 """ """ [{"date":"2014-02-10 04:23:23","type":"buy","rate":"0.00007600","amount":"140","total":"0.01064"},{"date":"2014-02-10 01:19:37","type":"buy","rate":"0.00007600","amount":"655","total":"0.04978"}, ... ] """ pass elif command == "returnChartData": """ Call: https://poloniex.com/public?command=returnChartData&currencyPair=BTC_XMR&start=1405699200&end=9999999999&period=14400 """ """ [{"date":1405699200,"high":0.0045388,"low":0.00403001,"open":0.00404545,"close":0.00427592,"volume":44.11655644, "quoteVolume":10259.29079097,"weightedAverage":0.00430015}, ...] """ pass elif command == "returnCurrencies": r = {} for pair in ctx.pairs: market = Market(pair, bitshares_instance=ctx.bitshares) for symbol in [market["base"], market["quote"]]: r[symbol] = { "maxDailyWithdrawal": None, "txFee": "standard transfer fee", "minConf": None, "disabled": False, } for symbol, value in total.items(): r["total%s" % symbol] = value return r """ {"1CR":{"maxDailyWithdrawal":10000,"txFee":0.01,"minConf":3,"disabled":0},"ABY":{"maxDailyWithdrawal":10000000,"txFee":0.01,"minConf":8,"disabled":0}, ... } """ pass elif command == "returnLoanOrders": return error("Not available.") else: return error("Invalid command.") def run(context, port): """ Run the Webserver/SocketIO and app """ global ctx ctx = context app.run(port=port)
{ "repo_name": "xeroc/uptick", "path": "uptick/apis/poloniex.py", "copies": "1", "size": "3967", "license": "mit", "hash": 3832887973342155000, "line_mean": 33.798245614, "line_max": 209, "alpha_frac": 0.5414671036, "autogenerated": false, "ratio": 3.5867992766726946, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.962597773611302, "avg_score": 0.00045772883193470517, "num_lines": 114 }
from functools import wraps from flask import Flask from flask import request from container import Container class Request(object): def __init__(self, request): self.request = request def param(self, name): return self.request.form[name] def attach_request(self, handler): @wraps(handler) def f(*args, **kwargs): self.request = Request(request) return handler(*args, **kwargs) return f class FlaskContainer(Container): def __init__(self): Container.__init__(self) self.app = Flask(__name__) self.init_controllers() def init_controllers(self): for controller in self.controllers: request_mapping = controller.__class__._request_mapping for name, value in controller.__class__.__dict__.iteritems(): if hasattr(value, '_request_mapping'): handler = getattr(controller, name) url = request_mapping['url'] + handler._request_mapping['url'] self.app.route(url, methods=[handler._request_mapping['method']])(attach_request(controller, handler))
{ "repo_name": "macbinn/summer", "path": "summer/web/container/flaskimpl.py", "copies": "1", "size": "1140", "license": "mit", "hash": 7837956942371352000, "line_mean": 29.8108108108, "line_max": 122, "alpha_frac": 0.6175438596, "autogenerated": false, "ratio": 4.488188976377953, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005453587586999282, "num_lines": 37 }
from functools import wraps from flask import Flask, render_template, redirect, url_for, request, abort from flask_login import LoginManager, login_user, UserMixin, current_user from flask_ldap3_login import LDAP3LoginManager from flask_ldap3_login.forms import LDAPLoginForm from user import User from reverseproxy import ReverseProxy app = Flask(__name__) app.wsgi_app = ReverseProxy(app.wsgi_app) app.config.from_object("config") login_manager = LoginManager(app) ldap_manager = LDAP3LoginManager(app) users = {} @login_manager.user_loader def load_user(id): if id in users: return users[id] return None @ldap_manager.save_user def save_user(dn, username, data, memberships): user = User(dn, username, data) users[dn] = user return user def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user or current_user.is_anonymous: return redirect(url_for("login", next=request.url, _external=True)) return f(*args, **kwargs) return decorated_function @app.route("/") @login_required def index(): return render_template("index.html", user=current_user) @app.route("/init") def init(): if not current_user or current_user.is_anonymous: return redirect(url_for("login", next=request.args.get("next", ""), _external=True)) else: return redirect(url_for("index", _external=True)) @app.route("/check") def check(): if not current_user or current_user.is_anonymous: return abort(401) else: return "ok" @app.route("/login", methods=["GET", "POST"]) def login(): form = LDAPLoginForm() if form.validate_on_submit(): login_user(form.user) return redirect(request.args.get("next", url_for("index", _external=True))) return render_template("login.html", form=form) if __name__ == "__main__": app.run( debug=app.config["DEBUG"], host=app.config["HOST"], port=app.config["PORT"], )
{ "repo_name": "skyblue3350/cypress", "path": "app.py", "copies": "1", "size": "1993", "license": "mit", "hash": 3789930304772103700, "line_mean": 26.301369863, "line_max": 92, "alpha_frac": 0.6703462117, "autogenerated": false, "ratio": 3.4721254355400695, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46424716472400696, "avg_score": null, "num_lines": null }
from functools import wraps from flask import Flask, render_template, request, jsonify, Response from app import app, host, port, user, passwd, db from app.helpers.database import con_db import pymysql as MySQLdb import pickle import numpy as np import dateutil.parser import csv import math import random # Define helper functions from app.helpers.database import con_db, query_db from app.helpers.filters import format_currency import jinja2 def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ return username == 'guest' and password == 'insight123' def authenticate(): """Sends a 401 response that enables basic auth""" return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return authenticate() return f(*args, **kwargs) return decorated #Change sql to 0.0.0.0 def sqlExec(query): con = MySQLdb.connect(user=user, host=host, port=port, passwd=passwd, db=db) with con: cur = con.cursor(MySQLdb.cursors.DictCursor) cur.execute(query) tables = cur.fetchall() return tables def remove_uni(s): """remove the leading unicode designator from a string""" if isinstance(s, unicode): s = s.encode("ascii", "ignore") return s @app.route("/") @requires_auth def hello(): return render_template('index.html') #ifexists = 0 #while ifexists ==0: # rand_loanid = random.randint(0, 5000) # cnt=sqlExec("SELECT COUNT(1) AS total FROM loanapplic WHERE loanid = %d;" % rand_loanid) # ifexists = int(cnt[0]['total']) @app.route('/index.html') def index(): return render_template('index.html') @app.route("/about.html") def aboutfn(): return render_template('about.html') @app.route("/search.html") @requires_auth def search(): user = app.config["DATABASE_USER"] host = app.config["DATABASE_HOST"] port = app.config["DATABASE_PORT"] passwd = app.config["DATABASE_PASSWORD"] db = app.config["DATABASE_DB"] # Need to change this on AWS: con = MySQLdb.connect(user=user, host=host, port=port, passwd = passwd, db=db) cursor = con.cursor() # Loan ID loan_id = int(request.args.get("loan_id", None)) pickle.dump( loan_id, open( "passloan.pkl", "wb")) # Load loan info loan_info = sqlExec("SELECT borrowerid, sift_score, interest, period, length(family_member1_mobile_phone) as family1, applydate-borrowers.Created as time_to_complete, length(frontNationalId) as fnid,firstname as first, reffered_by as referred_by, Country as country, City as city, Amount as amount, loanuse from loanapplic join borrowers on loanapplic.borrowerid = borrowers.userid join borrowers_extn on borrowers_extn.userid = borrowers.userid where loanid = %d;" % loan_id) print loan_info[0]['loanuse'] loan_info[0]['loanuse'] = loan_info[0]['loanuse'].decode("ascii", "ignore") # Sift score sift_score = loan_info[0]['sift_score'] interest = loan_info[0]['interest'] period = loan_info[0]['period'] family1 = loan_info[0]['family1'] fnid = loan_info[0]['fnid'] time_to_complete = loan_info[0]['time_to_complete'] interest = loan_info[0]['interest'] # Check for null values if family1 is None: family1 = 0 if fnid is None: fnid = 0 # Features xin = np.array([sift_score, time_to_complete, interest, period, family1, fnid]) # Load model - Lin regression clf = pickle.load(open('app/helpers/model.pkl', "rb")) y = clf.predict(xin)[0] prob_default = 100.0*clf.predict_proba(xin)[0][1] # Make prediction if y == 0: ypred = 'Will pay back loan in full' elif y ==1: ypred = 'Will default' # Set image id file image_id_str = "static/images/loan_images/" + str(loan_id) + ".jpg" return render_template('search.html', loan_id=loan_id, loan_info=loan_info, y=y, ypred=ypred, prob_default=prob_default, image_id_str =image_id_str) @app.route("/blocker") def block(): return "Blocked!" @app.route('/<pagename>') def regularpage(pagename = None): """ Route not found by the other routes above. """ return "You've arrived at : " + pagename
{ "repo_name": "vVvVvVvVvVv/lenderstanding", "path": "app/views.py", "copies": "1", "size": "4606", "license": "mit", "hash": 346466829984539140, "line_mean": 32.6204379562, "line_max": 480, "alpha_frac": 0.6532783326, "autogenerated": false, "ratio": 3.344952795933188, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44982311285331883, "avg_score": null, "num_lines": null }
from functools import wraps from flask import Flask, render_template, request, redirect, url_for, session import os tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') # ... app = Flask('__name__', template_folder=tmpl_dir) #webapp = Flask('__name__') @webapp.route('/') def indexpage(): """ The home page for this webapp. Displays what the site is about/for. """ return render_template("index.html", title = "Portfolio of James Cantwell") @webapp.route('/games') def goToGames(): """ Sends the user to the Games Programming page. """ return render_template("gamesProgramming.html", title="Games Programming") '''@webapp.route('/3dsculptures') def goToSculpting(): """ Sends the user to the Games Programming page. """ return render_template(".../html/sculptures.html", title="3D Sculptures") @webapp.route('/contact') def goToContact(): """ Sends the user to the Games Programming page. """ return render_template(".../html/contact.html", title="Contact James") @webapp.route('/about') def goToAbout(): """ Sends the user to the Games Programming page. """ return render_template(".../html/about.html", title="About James")''' if __name__ == '__main__': webapp.secret_key = b'..-.keysecretaisthis0101..-' if 'liveconsole' not in gethostname(): webapp.run(debug=True, host='0.0.0.0')
{ "repo_name": "Jamesmgc/portfolio", "path": "webpage.py", "copies": "1", "size": "1634", "license": "apache-2.0", "hash": 1192501631074207500, "line_mean": 28.7272727273, "line_max": 80, "alpha_frac": 0.5654834761, "autogenerated": false, "ratio": 3.8812351543942993, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4946718630494299, "avg_score": null, "num_lines": null }
from functools import wraps from flask import Flask, session, redirect, url_for, escape, request, Response #dev from response_controller import * from user import * from switchs import * app = Flask(__name__) app.config['MYSQL_DATABASE_USER'] = 'domuspi' app.config['MYSQL_DATABASE_PASSWORD'] = 'domuspi' app.config['MYSQL_DATABASE_DB'] = 'domuspi' app.config['MYSQL_DATABASE_HOST'] = 'localhost' # db = Db(app) def islogged(): return session['login'] == True def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): if not islogged(): return Response('Access Denied', 401) return f(*args, **kwargs) return decorated @app.route("/") def home(): return "Follow <a href='https://github.com/hastrolaptecos/homeautomation'>https://github.com/hastrolaptecos/homeautomation</a>" @app.route("/switch/update/") @requires_auth def switch(): _id = request.args.get('id') state = request.args.get('state') if(int(_id) <= 10): switch = SwitchController(_id) if(state == "1"): switch.on() return "on" else: switch.off() return "off" else: return 'ERROR' @app.route("/switch") @requires_auth def switchs(): switchs = Switchs() return ResponseController.json_response(switchs.get_all()); ############# @app.route("/auth/login") def login(): login = request.args.get('login') password = request.args.get('password') data = User().find_by_login(login) if data is None: return "Username is wrong." else: print data if data['password'] == password: session['login'] = True session['_id'] = data['id'] return "Logged in successfully." else: return "Password is wrong." @app.route("/auth/logout") def logout(): session['login'] = False session['_id'] = None return 'see ya' ResetSwitchs.resetAll() app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' if __name__ == "__main__": app.run(host='0.0.0.0',debug=True)
{ "repo_name": "hastrolaptecos/domuspi_servidor", "path": "server.py", "copies": "1", "size": "1956", "license": "mit", "hash": 1248322867042409700, "line_mean": 20.7333333333, "line_max": 129, "alpha_frac": 0.6416155419, "autogenerated": false, "ratio": 3.1650485436893203, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43066640855893207, "avg_score": null, "num_lines": null }
from functools import wraps from flask import g, flash, redirect, url_for, request, session from models import DB # Used to divert users from account-only STACK pages # Admins are able to access protected pages def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if g.project is None: if g.admin is None: flash(u'You need to login to view this page!') return redirect(url_for('index', next=request.path)) return f(*args, **kwargs) return decorated_function def admin_required(f): @wraps(f) def decorated_function(*args, **kwargs): if g.admin is None: flash(u'You need to be an admin to view this page!') return redirect(url_for('index', next=request.path)) return f(*args, **kwargs) return decorated_function # Used to load project info into the session if not there def load_project(f): @wraps(f) def decorated_function(*args, **kwargs): g.project = None if 'project_id' in session: db = DB() resp = db.get_project_detail(session['project_id']) if resp['status']: g.project = resp return f(*args, **kwargs) return decorated_function # Used to load admin info into the session def load_admin(f): @wraps(f) def decorated_function(*args, **kwargs): g.admin = None if 'admin_project_id' in session: db = DB() resp = db.get_project_detail(session['admin_project_id']) if resp['status']: g.admin = resp return f(*args, **kwargs) return decorated_function
{ "repo_name": "bitslabsyr/stack", "path": "app/decorators.py", "copies": "1", "size": "1685", "license": "mit", "hash": -8434157952782797000, "line_mean": 27.5593220339, "line_max": 69, "alpha_frac": 0.5994065282, "autogenerated": false, "ratio": 3.974056603773585, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.998871736926172, "avg_score": 0.01694915254237288, "num_lines": 59 }
from functools import wraps from flask import g, flash, url_for from openedoo.core.libs import session, redirect from modules.module_employee.models import Employee, Setting def setup_required(f): @wraps(f) def wrap(*args, **kwargs): """Checks if there is any employee or not""" employee = Employee.check_records() if not employee: flash("You don't have administrator. Register one now.") return redirect(url_for('module_employee.setup')) return f(*args, **kwargs) return wrap def login_required(f): @wraps(f) def wrap(*args, **kwargs): """Checks user is logged in or not in the session""" session.permanent = True try: if session['username'] is False: flash('You must login first!') return redirect(url_for('module_employee.login')) return f(*args, **kwargs) except KeyError: flash('Your session is timeout!') return redirect(url_for('module_employee.login')) return wrap def site_setting(f): @wraps(f) def wrap(*args, **kwargs): if not hasattr(g, 'school') or g.school is None: g.school = {'name': ''} setting = Setting() schoolData = setting.get_existing_name() if schoolData: g.school = schoolData return f(*args, **kwargs) return wrap
{ "repo_name": "openedoo/module_employee", "path": "views/decorators.py", "copies": "1", "size": "1430", "license": "mit", "hash": 2886717655764378600, "line_mean": 30.7777777778, "line_max": 68, "alpha_frac": 0.5874125874, "autogenerated": false, "ratio": 4.230769230769231, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5318181818169231, "avg_score": null, "num_lines": null }
from functools import wraps from flask import g from flask import request from werkzeug.exceptions import BadRequest from webargs import fields as webargs_fields from webargs.flaskparser import parser as webargs_parser from dataactcore.interfaces.db import GlobalDB from dataactcore.models.domainModels import SubTierAgency from dataactcore.models.jobModels import Submission from dataactcore.models.lookups import (ALL_PERMISSION_TYPES_DICT, PERMISSION_SHORT_DICT, DABS_PERMISSION_ID_LIST, FABS_PERMISSION_ID_LIST) from dataactcore.utils.jsonResponse import JsonResponse from dataactcore.utils.responseException import ResponseException from dataactcore.utils.statusCode import StatusCode from dataactcore.utils.requestDictionary import RequestDictionary NOT_AUTHORIZED_MSG = "You are not authorized to perform the requested task. Please contact your administrator." DABS_PERMS = [PERMISSION_SHORT_DICT['w'], PERMISSION_SHORT_DICT['s']] FABS_PERM = PERMISSION_SHORT_DICT['f'] def requires_login(func): """ Decorator requiring that a user be logged in (i.e. that we're not using an anonymous session) Args: func: the function that this wrapper is wrapped around Returns: LOGIN_REQUIRED JSONResponse object if the user doesn't exist, otherwise it runs the wrapped function """ @wraps(func) def inner(*args, **kwargs): if g.user is None: return JsonResponse.create(StatusCode.LOGIN_REQUIRED, {'message': "Login Required"}) return func(*args, **kwargs) return inner def requires_admin(func): """ Decorator requiring the requesting user be a website admin Args: func: the function that this wrapper is wrapped around Returns: LOGIN_REQUIRED JSONResponse object if the user doesn't exist or is not an admin user, otherwise it runs the wrapped function """ @wraps(func) def inner(*args, **kwargs): if g.user is None: return JsonResponse.create(StatusCode.LOGIN_REQUIRED, {'message': "Login Required"}) if not g.user.website_admin: return JsonResponse.create(StatusCode.LOGIN_REQUIRED, {'message': NOT_AUTHORIZED_MSG}) return func(*args, **kwargs) return inner def current_user_can(permission, cgac_code=None, frec_code=None): """ Validate whether the current user can perform the act (described by the permission level) for the given cgac_code or frec_code Args: permission: single-letter string representing an application permission_type cgac_code: 3-digit numerical string identifying a CGAC agency frec_code: 4-digit numerical string identifying a FREC agency Returns: Boolean result on whether the user has permissions greater than or equal to permission """ # If the user is not logged in, or the user is a website admin, there is no reason to check their permissions if not hasattr(g, 'user'): return False if g.user.website_admin: return True # Ensure the permission exists and retrieve its ID and type try: permission_id = ALL_PERMISSION_TYPES_DICT[permission] except KeyError: return False permission_list = FABS_PERMISSION_ID_LIST if permission_id in FABS_PERMISSION_ID_LIST else DABS_PERMISSION_ID_LIST # Loop through user's affiliations and return True if any match the permission for aff in g.user.affiliations: # Check if affiliation agency matches agency args if (aff.cgac and aff.cgac.cgac_code == cgac_code) or (aff.frec and aff.frec.frec_code == frec_code): # Check if affiliation has higher permissions than permission args aff_perm_id = aff.permission_type_id # We can check for reader overall regardless of FABS or DABS or permission level because DABS permissions # give read access to FABS submissions so it should pass as long as there are any permissions for the agency if (permission == 'reader') or (aff_perm_id in permission_list and aff_perm_id >= permission_id): return True return False def current_user_can_on_submission(perm, submission, check_owner=True): """ Submissions add another permission possibility: if a user created a submission, they can do anything to it, regardless of submission agency Args: perm: string PermissionType value submission: Submission object check_owner: allows the functionality if the user is the owner of the Submission; default True Returns: Boolean result on whether the user has permissions greater than or equal to perm """ is_owner = hasattr(g, 'user') and submission.user_id == g.user.user_id user_can = current_user_can(perm, cgac_code=submission.cgac_code, frec_code=submission.frec_code) return (is_owner and check_owner) or user_can def requires_submission_perms(perm, check_owner=True, check_fabs=None): """ Decorator that checks the current user's permissions and validates that the submission exists. It expects a submission_id parameter on top of the function arguments. Args: perm: the type of permission we are checking for check_owner: a boolean indicating if we should check whether the user is the owner of the submission check_fabs: FABS permission to check if the Submission is FABS; default None Returns: A submission object obtained using the submission_id provided (along with the other args/kwargs that were initially provided) Raises: ResponseException: If the user doesn't have permission to access the submission at the level requested or the submission doesn't exist. """ def inner(fn): @requires_login @wraps(fn) def wrapped(submission_id, *args, **kwargs): sess = GlobalDB.db().session submission = sess.query(Submission).filter_by(submission_id=submission_id).one_or_none() if submission is None: # @todo - why don't we use 404s? raise ResponseException('No such submission', StatusCode.CLIENT_ERROR) permission = check_fabs if check_fabs and submission.d2_submission else perm if not current_user_can_on_submission(permission, submission, check_owner): raise ResponseException("User does not have permission to access that submission", StatusCode.PERMISSION_DENIED) return fn(submission, *args, **kwargs) return wrapped return inner def requires_agency_perms(perm): """ Decorator that checks the current user's permissions and validates them against the agency code. It expects an existing_submission_id, cgac_code, or frec_code parameter on top of the function arguments. Args: perm: the type of permission we are checking for Returns: The args/kwargs that were initially provided Raises: ResponseException: If the user doesn't have permission to access the submission at the level requested or no valid agency code was provided. """ def inner(fn): @requires_login @wraps(fn) def wrapped(*args, **kwargs): req_args = webargs_parser.parse({ 'existing_submission_id': webargs_fields.Int(missing=None), 'cgac_code': webargs_fields.String(missing=None), 'frec_code': webargs_fields.String(missing=None) }) # Ensure there is either an existing_submission_id, a cgac_code, or a frec_code if req_args['existing_submission_id'] is None and req_args['cgac_code'] is None and \ req_args['frec_code'] is None: raise ResponseException('Missing required parameter: cgac_code, frec_code, or existing_submission_id', StatusCode.CLIENT_ERROR) # Use codes based on existing Submission if existing_submission_id is provided, otherwise use CGAC or FREC if req_args['existing_submission_id'] is not None: check_existing_submission_perms(perm, req_args['existing_submission_id']) else: # Check permissions for the agency if not current_user_can(perm, cgac_code=req_args['cgac_code'], frec_code=req_args['frec_code']): raise ResponseException("User does not have permissions to write to that agency", StatusCode.PERMISSION_DENIED) return fn(*args, **kwargs) return wrapped return inner def requires_agency_code_perms(perm): """ Decorator that checks the current user's permissions and validates them against the agency code. It expects an agency_code parameter on top of the function arguments. Args: perm: the type of permission we are checking for Returns: The args/kwargs that were initially provided Raises: ResponseException: If the user doesn't have permission to access the submission at the level requested or no valid agency code was provided. """ def inner(fn): @requires_login @wraps(fn) def wrapped(*args, **kwargs): req_args = webargs_parser.parse({ 'agency_code': webargs_fields.String(missing=None) }) # Ensure there is an agency_code if req_args['agency_code'] is None: raise ResponseException('Missing required parameter: agency_code', StatusCode.CLIENT_ERROR) # Check permissions for the agency if not current_user_can(perm, cgac_code=req_args['agency_code'], frec_code=req_args['agency_code']): raise ResponseException("User does not have permissions for that agency", StatusCode.PERMISSION_DENIED) return fn(*args, **kwargs) return wrapped return inner def requires_sub_agency_perms(perm): """ Decorator that checks the current user's permissions and validates them against the agency code. It expects an agency_code parameter on top of the function arguments. Args: perm: the type of permission we are checking for Returns: The args/kwargs that were initially provided Raises: ResponseException: If the user doesn't have permission to access the submission at the level requested or no valid agency code was provided. """ def inner(fn): @requires_login @wraps(fn) def wrapped(*args, **kwargs): sess = GlobalDB.db().session try: req_args = { 'agency_code': RequestDictionary.derive(request).get('agency_code', None), 'existing_submission_id': RequestDictionary.derive(request).get('existing_submission_id', None) } except (ValueError, TypeError) as e: raise ResponseException(e, StatusCode.CLIENT_ERROR) except BadRequest: raise ResponseException('Bad request: agency_code or existing_submission_id not included properly', StatusCode.CLIENT_ERROR) if req_args['agency_code'] is None and req_args['existing_submission_id'] is None: raise ResponseException('Missing required parameter: agency_code or existing_submission_id', StatusCode.CLIENT_ERROR) if not isinstance(req_args['agency_code'], str) and not isinstance(req_args['existing_submission_id'], str): raise ResponseException('Bad request: agency_code or existing_submission_id' + 'required and must be strings', StatusCode.CLIENT_ERROR) if req_args['existing_submission_id'] is not None: check_existing_submission_perms(perm, req_args['existing_submission_id']) else: sub_tier_agency = sess.query(SubTierAgency).\ filter(SubTierAgency.sub_tier_agency_code == req_args['agency_code']).one_or_none() if sub_tier_agency is None: raise ResponseException('sub_tier_agency must be a valid sub_tier_agency_code', StatusCode.CLIENT_ERROR) cgac_code = sub_tier_agency.cgac.cgac_code if sub_tier_agency.cgac_id else None frec_code = sub_tier_agency.frec.frec_code if sub_tier_agency.frec_id else None if not current_user_can(perm, cgac_code=cgac_code, frec_code=frec_code): raise ResponseException("User does not have permissions to write to that subtier agency", StatusCode.PERMISSION_DENIED) return fn(*args, **kwargs) return wrapped return inner def separate_affiliations(affiliations, app_type): """ Separates CGAC and FREC UserAffiliations and removes affiliations with permissions outside of the specified application (FABS or DABS) Args: affiliations: list of UserAffiliations app_type: string deciding which application to use (FABS or DABS) Returns: A list of UserAffiliations with CGAC agencies within the app_type application A list of UserAffiliations with FREC agencies within the app_type application """ cgac_ids, frec_ids = [], [] app_permissions = FABS_PERMISSION_ID_LIST if app_type.lower() == 'fabs' else DABS_PERMISSION_ID_LIST for affiliation in affiliations: if affiliation.permission_type_id in app_permissions: if affiliation.frec: frec_ids.append(affiliation.frec.frec_id) else: cgac_ids.append(affiliation.cgac.cgac_id) return cgac_ids, frec_ids def check_existing_submission_perms(perm, submission_id): """ Checks the current user's permissions against the submission with the ID of submission_id Args: perm: the type of permission we are checking for submission_id: the ID of the Submission that the user input Raises: ResponseException: If the user doesn't have permission to access the submission at the level requested or no valid agency code was provided. """ sess = GlobalDB.db().session submission = sess.query(Submission).filter(Submission.submission_id == submission_id).one_or_none() # Ensure submission exists if submission is None: raise ResponseException("existing_submission_id must be a valid submission_id", StatusCode.CLIENT_ERROR) # Check permissions for the submission if not current_user_can_on_submission(perm, submission): raise ResponseException("User does not have permissions to write to that submission", StatusCode.PERMISSION_DENIED)
{ "repo_name": "fedspendingtransparency/data-act-broker-backend", "path": "dataactbroker/permissions.py", "copies": "1", "size": "15311", "license": "cc0-1.0", "hash": 1630953763610491100, "line_mean": 44.4332344214, "line_max": 120, "alpha_frac": 0.6473123898, "autogenerated": false, "ratio": 4.439257755871267, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5586570145671268, "avg_score": null, "num_lines": null }
from functools import wraps from flask import g, request, jsonify from jose import jwt oauth2_server_pub_key = """""" token_prefix = "Bearer " def get_jwt_scopes(token, audience): if token.startswith(token_prefix): token = token[len(token_prefix):] return jwt.decode(token, oauth2_server_pub_key, audience=audience)["scope"] else: raise Exception('invalid token') class oauth2_Dropbox: def __init__(self, scopes=None, audience= None): self.described_by = "headers" self.field = "Authorization" self.allowed_scopes = scopes if audience is None: self.audience = '' else: self.audience = ",".join(audience) def __call__(self, f): @wraps(f) def decorated_function(*args, **kwargs): token = "" if self.described_by == "headers": token = request.headers.get(self.field, "") elif self.described_by == "queryParameters": token = request.args.get("access_token", "") if token == "": return jsonify(), 401 g.access_token = token if len(oauth2_server_pub_key) > 0: scopes = get_jwt_scopes(token, self.audience) if self.check_scopes(scopes) == False: return jsonify(), 403 return f(*args, **kwargs) return decorated_function def check_scopes(self, scopes): if self.allowed_scopes is None or len(self.allowed_scopes) == 0: return True for allowed in self.allowed_scopes: for s in scopes: if s == allowed: return True return False
{ "repo_name": "Jumpscale/go-raml", "path": "codegen/python/fixtures/libraries/python_server/libraries/security/oauth2_Dropbox.py", "copies": "1", "size": "1746", "license": "bsd-2-clause", "hash": -2071805503560956200, "line_mean": 28.6101694915, "line_max": 83, "alpha_frac": 0.5486827033, "autogenerated": false, "ratio": 4.0889929742388755, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5137675677538875, "avg_score": null, "num_lines": null }
from functools import wraps from flask import g, request, jsonify class oauth2_oauth_2_0: def __init__(self, scopes=None): self.described_by = "headers" self.field = "Authorization" self.allowed_scopes = scopes def __call__(self, f): @wraps(f) def decorated_function(*args, **kwargs): token = "" if self.described_by == "headers": token = request.headers.get(self.field, "") elif self.described_by == "queryParameters": token = request.args.get("access_token", "") if token == "": return jsonify(), 401 g.access_token = token # provide code to check scopes of the access_token scopes = [] if self.check_scopes(scopes) == False: return jsonify(), 403 return f(*args, **kwargs) return decorated_function def check_scopes(self, scopes): if self.allowed_scopes is None or len(self.allowed_scopes) == 0: return True for allowed in self.allowed_scopes: for s in scopes: if s == allowed: return True return False
{ "repo_name": "Jumpscale/jscockpit", "path": "ays_api/oauth2_oauth_2_0.py", "copies": "1", "size": "1235", "license": "apache-2.0", "hash": -3355321116659260000, "line_mean": 26.4444444444, "line_max": 72, "alpha_frac": 0.5311740891, "autogenerated": false, "ratio": 4.490909090909091, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00043572984749455336, "num_lines": 45 }
from functools import wraps from flask import g, request, redirect, url_for, abort from .models import Guild def login_required(f): """Decorator that makes the view require logging in. If the user is not logged in, it redirects them to the index page. """ @wraps(f) def decorator(*args, **kwargs): if g.user is None: return redirect(url_for('main.index')) return f(*args, **kwargs) return decorator def guild_admin_required(f): """Decorator that makes the view require guild admin privileges. A guild admin is someone that can edit the guild, e.g. MANAGE_GUILD or higher. This requires that the view defines a ``guild_id`` argument. After this decorator is used, ``g.managed_guild`` is set to the current managed guild. """ @wraps(f) def decorator(*args, **kwargs): guild_id = request.view_args.get('guild_id') g.managed_guild = next(filter(lambda n: n.id == guild_id, g.guilds), None) if g.managed_guild is None: abort(404) return f(*args, **kwargs) return decorator def get_guild_or_404(guild_id): # search our own guild list ret = next(filter(lambda s: s.id == guild_id, g.guilds), None) if ret is None: # fallback to the database ret = Guild.query.get_or_404(guild_id) return ret def public_guild_required(f): """Decorator that makes the view require a public guild. If the guild is not found or is not public then the view aborts with 404. The resulting guild is stored under ``g.guild``. Follows similar rules to :func:`guild_admin_required`. """ @wraps(f) def decorator(*args, **kwargs): guild_id = request.view_args.get('guild_id') # get the guild with the guild_id from our own guild list guild = get_guild_or_404(guild_id) if guild.public is not True: abort(404) g.guild = guild return f(*args, **kwargs) return decorator
{ "repo_name": "DiscordEmotes/website", "path": "website/utils.py", "copies": "2", "size": "2002", "license": "mit", "hash": -4501917727844604000, "line_mean": 29.8, "line_max": 82, "alpha_frac": 0.6368631369, "autogenerated": false, "ratio": 3.6268115942028984, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5263674731102899, "avg_score": null, "num_lines": null }
from functools import wraps from flask import g, request, redirect, url_for from peewee import ForeignKeyField def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if g.user is None: return redirect(url_for('login')) return f(*args, **kwargs) return decorated_function def get_dictionary_from_model(model, fields=None, exclude=None): if model is None: return {} model_class = type(model) data = {} fields = fields or {} exclude = exclude or {} curr_exclude = exclude.get(model_class, []) curr_fields = fields.get(model_class, model._meta.get_field_names()) for field_name in curr_fields: if field_name in curr_exclude: continue field_obj = model_class._meta.fields[field_name] field_data = model._data.get(field_name) if isinstance(field_obj, ForeignKeyField) and field_data and field_obj.rel_model in fields: rel_obj = getattr(model, field_name) data[field_name] = get_dictionary_from_model(rel_obj, fields, exclude) else: data[field_name] = field_data return data
{ "repo_name": "glenbot/dibbs", "path": "utils.py", "copies": "1", "size": "1166", "license": "mit", "hash": 4251421693165640700, "line_mean": 30.5135135135, "line_max": 99, "alpha_frac": 0.6363636364, "autogenerated": false, "ratio": 3.761290322580645, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4897653958980645, "avg_score": null, "num_lines": null }
from functools import wraps from flask import g, session, flash, redirect, request, url_for from flask.ext.login import login_user from werkzeug.routing import RequestRedirect def getCurrentUserRole(): return g.user.user_class def privilegeError(): """Actions to perform when user has wrong role.""" flash("The user has insufficient privileges to access this resource.") raise RequestRedirect(url_for('index')) def requires_roles(*roles): """ Require that the user have the specified roles to access the view. http://flask.pocoo.org/snippets/98/ """ def wrapper(f): @wraps(f) def wrapped(*args, **kwargs): if getCurrentUserRole() not in roles: return privilegeError() return f(*args, **kwargs) return wrapped return wrapper def mustMatchOrPrivilegeError(first, second): """Utility function to require two things to match unless user is an admin.""" if g.user.user_class is not 'a' and str(first) != str(second): return privilegeError() def tryLogin(user, password): """ Tries to log the user in with given password. Handles remember me. If successful, redirects to the requested page. Else, redirects to index. """ if user and user.password == password: remember_me = False if 'remember_me' in session: remember_me = session['remember_me'] session.pop('remember_me', None) login_user(user, remember=remember_me) return redirect(request.args.get('next') or url_for('index')) else: flash("Invalid login. Please try again.") return redirect(url_for('index'))
{ "repo_name": "MarkGalloway/RIS", "path": "app/views/util/login.py", "copies": "1", "size": "1690", "license": "apache-2.0", "hash": -8677312264378690000, "line_mean": 30.2962962963, "line_max": 82, "alpha_frac": 0.6544378698, "autogenerated": false, "ratio": 4.1320293398533, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00022311468094600627, "num_lines": 54 }
from functools import wraps from flask import g, url_for, redirect, abort, request def login_required(f): # requires users to be logged in to view @wraps(f) def decorated_function(*args, **kwargs): if g.user is None: dest = f.__name__ if '/mod/' in request.path: dest = "mod." + dest elif '/api/' in request.path: dest = "api." + dest return redirect(url_for('auth', next=dest)) return f(*args, **kwargs) return decorated_function def mod_required(f): # requires user to be a moderator to view @wraps(f) def decorated_function(*args, **kwargs): if g.user is None: dest = f.__name__ if '/mod/' in request.path: dest = "mod." + dest elif '/api/' in request.path: dest = "api." + dest return redirect(url_for('auth', next=dest)) if not g.user.form_mod: return abort(403) return f(*args, **kwargs) return decorated_function def api_disallowed(f): # requires that logins be browser-based to access @wraps(f) def decorated_function(*args, **kwargs): if g.api_login: return abort(403) return f(*args, **kwargs) return decorated_function
{ "repo_name": "Jakeable/rforms", "path": "decorators.py", "copies": "1", "size": "1324", "license": "unlicense", "hash": 4776994320743725000, "line_mean": 29.0909090909, "line_max": 55, "alpha_frac": 0.5513595166, "autogenerated": false, "ratio": 3.952238805970149, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5003598322570149, "avg_score": null, "num_lines": null }
from functools import wraps from flask import jsonify from flask import request, Response import settings def check_auth(username, password): import settings return username == settings.BASIC_USERNAME and password == settings.BASIC_PASSWORD def authenticate(): message = {'message': "Authenticate."} resp = jsonify(message) resp.status_code = 401 resp.headers['WWW-Authenticate'] = 'Basic realm="Secure"' return resp def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth: return authenticate() elif not check_auth(auth.username, auth.password): return authenticate() return f(*args, **kwargs) return decorated def requires_apitoken(f): @wraps(f) def decorated(*args, **kwargs): try: request.headers.get('apitoken') if request.headers.get('apitoken') == "1234": return f(*args, **kwargs) else: message = {'message': "Authenticate."} resp = jsonify(message) resp.status_code = 401 return resp except Exception, e: indigo.server.log(str(e)) return decorated
{ "repo_name": "mikewesner-wf/glasshouse", "path": "glasshouse.indigoPlugin/Contents/Server Plugin/decorators.py", "copies": "1", "size": "1270", "license": "apache-2.0", "hash": 6219505549701513000, "line_mean": 23.9215686275, "line_max": 86, "alpha_frac": 0.5992125984, "autogenerated": false, "ratio": 4.440559440559441, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5539772038959441, "avg_score": null, "num_lines": null }
from functools import wraps from flask import make_response, request from userver.user.admin import Admin import time """ support basic auth 1、email and password 2、auth token(username=auth token, password='') """ class HTTPAuth: def __init__(self): # def default_get_password(username): # return None def default_auth_error(): return "Unauthorized Access" self.realm = "Authentication Required" # self.get_password(default_get_password) self.error_handler(default_auth_error) def error_handler(self, f): @wraps(f) def decorated(*args, **kwargs): res = f(*args, **kwargs) if type(res) == str: res = make_response(res) res.status_code = 401 if 'WWW-Authenticate' not in res.headers.keys(): res.headers['WWW-Authenticate'] = 'Basic realm="' + self.realm + '"' return res self.auth_error_callback = decorated return decorated @staticmethod def verify_password(username, password): # first try to authenticate by token # user = Admin.verify_password(email_or_token, password) # if not user: # # try to authenticate with username/password # user = Admin.query.filter_by(email=email_or_token).first() # if not user or not user.verify_password(password): # return False admin = Admin.query.filter_by(username=username).first() if not admin: return False elif not admin.verify_password(password): return False return admin def auth_required(self, f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth: return self.auth_error_callback() admin = self.verify_password(auth.username, auth.password) if not admin: return self.auth_error_callback() return f(*args, **kwargs) return decorated auth = HTTPAuth()
{ "repo_name": "soybean217/lora-python", "path": "UServer/admin_server/admin_http_api/http_auth.py", "copies": "1", "size": "2101", "license": "mit", "hash": 1728716954708485400, "line_mean": 30.3134328358, "line_max": 84, "alpha_frac": 0.5846447306, "autogenerated": false, "ratio": 4.332644628099174, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5417289358699173, "avg_score": null, "num_lines": null }
from functools import wraps from flask import make_response, request from userver.user.models import User import time """ support basic auth 1、email and password 2、auth token(username=auth token, password='') """ class HTTPAuth: def __init__(self): # def default_get_password(username): # return None def default_auth_error(): return "Unauthorized Access" self.realm = "Authentication Required" # self.get_password(default_get_password) self.error_handler(default_auth_error) def error_handler(self, f): @wraps(f) def decorated(*args, **kwargs): res = f(*args, **kwargs) if type(res) == str: res = make_response(res) res.status_code = 401 if 'WWW-Authenticate' not in res.headers.keys(): res.headers['WWW-Authenticate'] = 'Basic realm="' + self.realm + '"' return res self.auth_error_callback = decorated return decorated @staticmethod def verify_password(email_or_token, password): # first try to authenticate by token first = time.time() user = User.verify_auth_token(email_or_token) second = time.time() if not user: # try to authenticate with username/password third = time.time() user = User.query.filter_by(email=email_or_token).first() fourth = time.time() if not user or not user.verify_password(password): return False fifth = time.time() print('verify', second-first, third-second, fourth-third, fifth-fourth) return user def auth_required(self, f): @wraps(f) def decorated(*args, **kwargs): start = time.time() auth = request.authorization if not auth: return self.auth_error_callback() user = self.verify_password(auth.username, auth.password) mid = time.time() # if not password: # return self.auth_error_callback() if not user: return self.auth_error_callback() # user = User.query.get(1) end= time.time() print('auth', mid-start, end-mid) return f(user, *args, **kwargs) return decorated auth = HTTPAuth()
{ "repo_name": "soybean217/lora-python", "path": "UServer/http_api/http_auth.py", "copies": "1", "size": "2393", "license": "mit", "hash": 4141298778779865600, "line_mean": 30.8666666667, "line_max": 84, "alpha_frac": 0.5646714106, "autogenerated": false, "ratio": 4.213403880070547, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.001400946585530764, "num_lines": 75 }
from functools import wraps from flask import make_response, request from userver.user.models import User """ support basic auth 1、email and password 2、auth token(username=auth token, password='') """ class HTTPAuth: def __init__(self): # def default_get_password(username): # return None def default_auth_error(): return "Unauthorized Access" self.realm = "Authentication Required" # self.get_password(default_get_password) self.error_handler(default_auth_error) def error_handler(self, f): @wraps(f) def decorated(*args, **kwargs): res = f(*args, **kwargs) if type(res) == str: res = make_response(res) res.status_code = 401 if 'WWW-Authenticate' not in res.headers.keys(): res.headers['WWW-Authenticate'] = 'Basic realm="' + self.realm + '"' return res self.auth_error_callback = decorated return decorated @staticmethod def verify_password(email_or_token, password): # first try to authenticate by token user = User.verify_auth_token(email_or_token) if not user: # try to authenticate with username/password user = User.query.filter_by(email=email_or_token).first() if not user or not user.verify_password(password): return False return user def auth_required(self, f): @wraps(f) def decorated(*args, **kwargs): user = User.query.get(1) return f(user, *args, **kwargs) return decorated auth = HTTPAuth()
{ "repo_name": "soybean217/lora-python", "path": "UServer/http_api_no_auth/http_auth.py", "copies": "1", "size": "1665", "license": "mit", "hash": 5594138137907067000, "line_mean": 28.6785714286, "line_max": 84, "alpha_frac": 0.5881998796, "autogenerated": false, "ratio": 4.183879093198993, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0012605042016806723, "num_lines": 56 }
from functools import wraps from flask import make_response, request, render_template from flask_login import current_user from .utils import patch_http_cache_headers def templated(template=None): """ Taken from http://flask.pocoo.org/docs/0.10/patterns/viewdecorators/ """ def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): template_name = template if template_name is None: template_name = request.endpoint.replace(".", "/") + ".html" ctx = f(*args, **kwargs) if ctx is None: ctx = {} elif not isinstance(ctx, dict): return ctx return render_template(template_name, **ctx) return decorated_function return decorator def http_cache(timeout=None): """ Add Flask cache response headers based on timeout in seconds. If timeout is None, caching will be disabled. Otherwise, caching headers are set to expire in now + timeout seconds Example usage: @app.route('/map') @http_cache(timeout=60) def index(): return render_template('index.html') Originally from https://gist.github.com/glenrobertson/954da3acec84606885f5 """ def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): response = make_response(f(*args, **kwargs)) if current_user.is_authenticated: return response else: return patch_http_cache_headers(response, timeout) return decorated_function return decorator
{ "repo_name": "jazzband/site", "path": "jazzband/decorators.py", "copies": "1", "size": "1624", "license": "mit", "hash": 7683388486216787000, "line_mean": 26.5254237288, "line_max": 78, "alpha_frac": 0.6120689655, "autogenerated": false, "ratio": 4.319148936170213, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 59 }