sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def to_jwt(self, key=None, algorithm="", lev=0, lifetime=0): """ Create a signed JWT representation of the class instance :param key: The signing key :param algorithm: The signature algorithm to use :param lev: :param lifetime: The lifetime of the JWS :return: A signed JWT """ _jws = JWS(self.to_json(lev), alg=algorithm) return _jws.sign_compact(key)
Create a signed JWT representation of the class instance :param key: The signing key :param algorithm: The signature algorithm to use :param lev: :param lifetime: The lifetime of the JWS :return: A signed JWT
entailment
def from_jwt(self, txt, keyjar, verify=True, **kwargs): """ Given a signed and/or encrypted JWT, verify its correctness and then create a class instance from the content. :param txt: The JWT :param key: keys that might be used to decrypt and/or verify the signature of the JWT :param verify: Whether the signature should be verified or not :param keyjar: A KeyJar that might contain the necessary key. :param kwargs: Extra key word arguments :return: A class instance """ algarg = {} if 'encalg' in kwargs: algarg['alg'] = kwargs['encalg'] if 'encenc' in kwargs: algarg['enc'] = kwargs['encenc'] _decryptor = jwe_factory(txt, **algarg) if _decryptor: logger.debug("JWE headers: {}".format(_decryptor.jwt.headers)) dkeys = keyjar.get_decrypt_key(owner="") logger.debug('Decrypt class: {}'.format(_decryptor.__class__)) _res = _decryptor.decrypt(txt, dkeys) logger.debug('decrypted message:{}'.format(_res)) if isinstance(_res, tuple): txt = as_unicode(_res[0]) elif isinstance(_res, list) and len(_res) == 2: txt = as_unicode(_res[0]) else: txt = as_unicode(_res) self.jwe_header = _decryptor.jwt.headers try: _verifier = jws_factory(txt, alg=kwargs['sigalg']) except: _verifier = jws_factory(txt) if _verifier: try: _jwt = _verifier.jwt jso = _jwt.payload() _header = _jwt.headers key = [] # if "sender" in kwargs: # key.extend(keyjar.get_verify_key(owner=kwargs["sender"])) logger.debug("Raw JSON: {}".format(jso)) logger.debug("JWS header: {}".format(_header)) if _header["alg"] == "none": pass elif verify: if keyjar: key.extend(keyjar.get_jwt_verify_keys(_jwt, **kwargs)) if "alg" in _header and _header["alg"] != "none": if not key: raise MissingSigningKey( "alg=%s" % _header["alg"]) logger.debug("Found signing key.") try: _verifier.verify_compact(txt, key) except NoSuitableSigningKeys: if keyjar: update_keyjar(keyjar) key = keyjar.get_jwt_verify_keys(_jwt, **kwargs) _verifier.verify_compact(txt, key) except Exception: raise else: self.jws_header = _jwt.headers else: jso = json.loads(txt) self.jwt = txt return self.from_dict(jso)
Given a signed and/or encrypted JWT, verify its correctness and then create a class instance from the content. :param txt: The JWT :param key: keys that might be used to decrypt and/or verify the signature of the JWT :param verify: Whether the signature should be verified or not :param keyjar: A KeyJar that might contain the necessary key. :param kwargs: Extra key word arguments :return: A class instance
entailment
def verify(self, **kwargs): """ Make sure all the required values are there and that the values are of the correct type """ _spec = self.c_param try: _allowed = self.c_allowed_values except KeyError: _allowed = {} for (attribute, (typ, required, _, _, na)) in _spec.items(): if attribute == "*": continue try: val = self._dict[attribute] except KeyError: if required: raise MissingRequiredAttribute("%s" % attribute) continue else: if typ == bool: pass elif not val: if required: raise MissingRequiredAttribute("%s" % attribute) continue try: _allowed_val = _allowed[attribute] except KeyError: pass else: if not self._type_check(typ, _allowed_val, val, na): raise NotAllowedValue(val) return True
Make sure all the required values are there and that the values are of the correct type
entailment
def request(self, location, fragment_enc=False): """ Given a URL this method will add a fragment, a query part or extend a query part if it already exists with the information in this instance. :param location: A URL :param fragment_enc: Whether the information should be placed in a fragment (True) or in a query part (False) :return: The extended URL """ _l = as_unicode(location) _qp = as_unicode(self.to_urlencoded()) if fragment_enc: return "%s#%s" % (_l, _qp) else: if "?" in location: return "%s&%s" % (_l, _qp) else: return "%s?%s" % (_l, _qp)
Given a URL this method will add a fragment, a query part or extend a query part if it already exists with the information in this instance. :param location: A URL :param fragment_enc: Whether the information should be placed in a fragment (True) or in a query part (False) :return: The extended URL
entailment
def extra(self): """ Return the extra parameters that this instance. Extra meaning those that are not listed in the c_params specification. :return: The key,value pairs for keys that are not in the c_params specification, """ return dict([(key, val) for key, val in self._dict.items() if key not in self.c_param])
Return the extra parameters that this instance. Extra meaning those that are not listed in the c_params specification. :return: The key,value pairs for keys that are not in the c_params specification,
entailment
def only_extras(self): """ Return True if this instance only has key,value pairs for keys that are not defined in c_params. :return: True/False """ known = [key for key in self._dict.keys() if key in self.c_param] if not known: return True else: return False
Return True if this instance only has key,value pairs for keys that are not defined in c_params. :return: True/False
entailment
def update(self, item, **kwargs): """ Update the information in this instance. :param item: a dictionary or a Message instance """ if isinstance(item, dict): self._dict.update(item) elif isinstance(item, Message): for key, val in item.items(): self._dict[key] = val else: raise ValueError("Can't update message using: '%s'" % (item,))
Update the information in this instance. :param item: a dictionary or a Message instance
entailment
def to_jwe(self, keys, enc, alg, lev=0): """ Place the information in this instance in a JSON object. Make that JSON object the body of a JWT. Then encrypt that JWT using the specified algorithms and the given keys. Return the encrypted JWT. :param keys: list or KeyJar instance :param enc: Content Encryption Algorithm :param alg: Key Management Algorithm :param lev: Used for JSON construction :return: An encrypted JWT. If encryption failed an exception will be raised. """ _jwe = JWE(self.to_json(lev), alg=alg, enc=enc) return _jwe.encrypt(keys)
Place the information in this instance in a JSON object. Make that JSON object the body of a JWT. Then encrypt that JWT using the specified algorithms and the given keys. Return the encrypted JWT. :param keys: list or KeyJar instance :param enc: Content Encryption Algorithm :param alg: Key Management Algorithm :param lev: Used for JSON construction :return: An encrypted JWT. If encryption failed an exception will be raised.
entailment
def from_jwe(self, msg, keys): """ Decrypt an encrypted JWT and load the JSON object that was the body of the JWT into this object. :param msg: An encrypted JWT :param keys: Possibly usable keys. :type keys: list or KeyJar instance :return: The decrypted message. If decryption failed an exception will be raised. """ jwe = JWE() _res = jwe.decrypt(msg, keys) return self.from_json(_res.decode())
Decrypt an encrypted JWT and load the JSON object that was the body of the JWT into this object. :param msg: An encrypted JWT :param keys: Possibly usable keys. :type keys: list or KeyJar instance :return: The decrypted message. If decryption failed an exception will be raised.
entailment
def weed(self): """ Get rid of key value pairs that are not standard """ _ext = [k for k in self._dict.keys() if k not in self.c_param] for k in _ext: del self._dict[k]
Get rid of key value pairs that are not standard
entailment
def rm_blanks(self): """ Get rid of parameters that has no value. """ _blanks = [k for k in self._dict.keys() if not self._dict[k]] for key in _blanks: del self._dict[key]
Get rid of parameters that has no value.
entailment
def proper_path(path): """ Clean up the path specification so it looks like something I could use. "./" <path> "/" """ if path.startswith("./"): pass elif path.startswith("/"): path = ".%s" % path elif path.startswith("."): while path.startswith("."): path = path[1:] if path.startswith("/"): path = ".%s" % path else: path = "./%s" % path if not path.endswith("/"): path += "/" return path
Clean up the path specification so it looks like something I could use. "./" <path> "/"
entailment
def ansi(color, text): """Wrap text in an ansi escape sequence""" code = COLOR_CODES[color] return '\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)
Wrap text in an ansi escape sequence
entailment
def require_flush(fun): """Decorator for methods that need to query security. It ensures all security related operations are flushed to DB, but avoids unneeded flushes. """ @wraps(fun) def ensure_flushed(service, *args, **kwargs): if service.app_state.needs_db_flush: session = db.session() if not session._flushing and any( isinstance(m, (RoleAssignment, SecurityAudit)) for models in (session.new, session.dirty, session.deleted) for m in models ): session.flush() service.app_state.needs_db_flush = False return fun(service, *args, **kwargs) return ensure_flushed
Decorator for methods that need to query security. It ensures all security related operations are flushed to DB, but avoids unneeded flushes.
entailment
def query_pa_no_flush(session, permission, role, obj): """Query for a :class:`PermissionAssignment` using `session` without any `flush()`. It works by looking in session `new`, `dirty` and `deleted`, and issuing a query with no autoflush. .. note:: This function is used by `add_permission` and `delete_permission` to allow to add/remove the same assignment twice without issuing any flush. Since :class:`Entity` creates its initial permissions in during :sqlalchemy:`sqlalchemy.orm.events.SessionEvents.after_attach`, it might be problematic to issue a flush when entity is not yet ready to be flushed (missing required attributes for example). """ to_visit = [session.deleted, session.dirty, session.new] with session.no_autoflush: # no_autoflush is required to visit PERMISSIONS_ATTR without emitting a # flush() if obj: to_visit.append(getattr(obj, PERMISSIONS_ATTR)) permissions = ( p for p in chain(*to_visit) if isinstance(p, PermissionAssignment) ) for instance in permissions: if ( instance.permission == permission and instance.role == role and instance.object == obj ): return instance # Last chance: perform a filtered query. If obj is not None, sometimes # getattr(obj, PERMISSIONS_ATTR) has objects not present in session # not in this query (maybe in a parent session transaction `new`?). if obj is not None and obj.id is None: obj = None return ( session.query(PermissionAssignment) .filter( PermissionAssignment.permission == permission, PermissionAssignment.role == role, PermissionAssignment.object == obj, ) .first() )
Query for a :class:`PermissionAssignment` using `session` without any `flush()`. It works by looking in session `new`, `dirty` and `deleted`, and issuing a query with no autoflush. .. note:: This function is used by `add_permission` and `delete_permission` to allow to add/remove the same assignment twice without issuing any flush. Since :class:`Entity` creates its initial permissions in during :sqlalchemy:`sqlalchemy.orm.events.SessionEvents.after_attach`, it might be problematic to issue a flush when entity is not yet ready to be flushed (missing required attributes for example).
entailment
def _current_user_manager(self, session=None): """Return the current user, or SYSTEM user.""" if session is None: session = db.session() try: user = g.user except Exception: return session.query(User).get(0) if sa.orm.object_session(user) is not session: # this can happen when called from a celery task during development # (with CELERY_ALWAYS_EAGER=True): the task SA session is not # app.db.session, and we should not attach this object to # the other session, because it can make weird, hard-to-debug # errors related to session.identity_map. return session.query(User).get(user.id) else: return user
Return the current user, or SYSTEM user.
entailment
def get_roles(self, principal, object=None, no_group_roles=False): """Get all the roles attached to given `principal`, on a given `object`. :param principal: a :class:`User` or :class:`Group` :param object: an :class:`Entity` :param no_group_roles: If `True`, return only direct roles, not roles acquired through group membership. """ assert principal if hasattr(principal, "is_anonymous") and principal.is_anonymous: return [AnonymousRole] query = db.session.query(RoleAssignment.role) if isinstance(principal, Group): filter_principal = RoleAssignment.group == principal else: filter_principal = RoleAssignment.user == principal if not no_group_roles: groups = [g.id for g in principal.groups] if groups: filter_principal |= RoleAssignment.group_id.in_(groups) query = query.filter(filter_principal) if object is not None: assert isinstance(object, Entity) query = query.filter(RoleAssignment.object == object) roles = {i[0] for i in query.all()} if object is not None: for attr, role in (("creator", Creator), ("owner", Owner)): if getattr(object, attr) == principal: roles.add(role) return list(roles)
Get all the roles attached to given `principal`, on a given `object`. :param principal: a :class:`User` or :class:`Group` :param object: an :class:`Entity` :param no_group_roles: If `True`, return only direct roles, not roles acquired through group membership.
entailment
def get_principals( self, role, anonymous=True, users=True, groups=True, object=None, as_list=True ): """Return all users which are assigned given role.""" if not isinstance(role, Role): role = Role(role) assert role assert users or groups query = RoleAssignment.query.filter_by(role=role) if not anonymous: query = query.filter(RoleAssignment.anonymous == False) if not users: query = query.filter(RoleAssignment.user == None) elif not groups: query = query.filter(RoleAssignment.group == None) query = query.filter(RoleAssignment.object == object) principals = {(ra.user or ra.group) for ra in query.all()} if object is not None and role in (Creator, Owner): p = object.creator if role == Creator else object.owner if p: principals.add(p) if not as_list: return principals return list(principals)
Return all users which are assigned given role.
entailment
def _fill_role_cache(self, principal, overwrite=False): """Fill role cache for `principal` (User or Group), in order to avoid too many queries when checking role access with 'has_role'. Return role_cache of `principal` """ if not self.app_state.use_cache: return None if not self._has_role_cache(principal) or overwrite: self._set_role_cache(principal, self._all_roles(principal)) return self._role_cache(principal)
Fill role cache for `principal` (User or Group), in order to avoid too many queries when checking role access with 'has_role'. Return role_cache of `principal`
entailment
def _fill_role_cache_batch(self, principals, overwrite=False): """Fill role cache for `principals` (Users and/or Groups), in order to avoid too many queries when checking role access with 'has_role'.""" if not self.app_state.use_cache: return query = db.session.query(RoleAssignment) users = {u for u in principals if isinstance(u, User)} groups = {g for g in principals if isinstance(g, Group)} groups |= {g for u in users for g in u.groups} if not overwrite: users = {u for u in users if not self._has_role_cache(u)} groups = {g for g in groups if not self._has_role_cache(g)} if not (users or groups): return # ensure principals processed here will have role cache. Thus users or # groups without any role will have an empty role cache, to avoid # unneeded individual DB query when calling self._fill_role_cache(p). for p in chain(users, groups): self._set_role_cache(p, {}) filter_cond = [] if users: filter_cond.append(RoleAssignment.user_id.in_(u.id for u in users)) if groups: filter_cond.append(RoleAssignment.group_id.in_(g.id for g in groups)) query = query.filter(sql.or_(*filter_cond)) ra_users = {} ra_groups = {} for ra in query.all(): if ra.user: all_roles = ra_users.setdefault(ra.user, {}) else: all_roles = ra_groups.setdefault(ra.group, {}) object_key = ( f"{ra.object.entity_type}:{ra.object_id:d}" if ra.object is not None else None ) all_roles.setdefault(object_key, set()).add(ra.role) for group, all_roles in ra_groups.items(): self._set_role_cache(group, all_roles) for user, all_roles in ra_users.items(): for gr in user.groups: group_roles = self._fill_role_cache(gr) for object_key, roles in group_roles.items(): obj_roles = all_roles.setdefault(object_key, set()) obj_roles |= roles self._set_role_cache(user, all_roles)
Fill role cache for `principals` (Users and/or Groups), in order to avoid too many queries when checking role access with 'has_role'.
entailment
def has_role(self, principal, role, object=None): """True if `principal` has `role` (either globally, if `object` is None, or on the specific `object`). :param:role: can be a list or tuple of strings or a :class:`Role` instance `object` can be an :class:`Entity`, a string, or `None`. Note: we're using a cache for efficiency here. TODO: check that we're not over-caching. Note2: caching could also be moved upfront to when the user is loaded. """ if not principal: return False principal = unwrap(principal) if not self.running: return True if isinstance(role, (Role, (str,))): role = (role,) # admin & manager always have role valid_roles = frozenset((Admin, Manager) + tuple(role)) if AnonymousRole in valid_roles: # everybody has the role 'Anonymous' return True if ( Authenticated in valid_roles and isinstance(principal, User) and not principal.is_anonymous ): return True if principal is AnonymousRole or ( hasattr(principal, "is_anonymous") and principal.is_anonymous ): # anonymous user, and anonymous role isn't in valid_roles return False # root always have any role if isinstance(principal, User) and principal.id == 0: return True if object: assert isinstance(object, Entity) object_key = "{}:{}".format(object.object_type, str(object.id)) if Creator in role: if object.creator == principal: return True if Owner in role: if object.owner == principal: return True else: object_key = None all_roles = ( self._fill_role_cache(principal) if self.app_state.use_cache else self._all_roles(principal) ) roles = set() roles |= all_roles.get(None, set()) roles |= all_roles.get(object_key, set()) return len(valid_roles & roles) > 0
True if `principal` has `role` (either globally, if `object` is None, or on the specific `object`). :param:role: can be a list or tuple of strings or a :class:`Role` instance `object` can be an :class:`Entity`, a string, or `None`. Note: we're using a cache for efficiency here. TODO: check that we're not over-caching. Note2: caching could also be moved upfront to when the user is loaded.
entailment
def grant_role(self, principal, role, obj=None): """Grant `role` to `user` (either globally, if `obj` is None, or on the specific `obj`).""" assert principal principal = unwrap(principal) session = object_session(obj) if obj is not None else db.session manager = self._current_user_manager(session=session) args = { "role": role, "object": obj, "anonymous": False, "user": None, "group": None, } if principal is AnonymousRole or ( hasattr(principal, "is_anonymous") and principal.is_anonymous ): args["anonymous"] = True elif isinstance(principal, User): args["user"] = principal else: args["group"] = principal query = session.query(RoleAssignment) if query.filter_by(**args).limit(1).count(): # role already granted, nothing to do return # same as above but in current, not yet flushed objects in session. We # cannot call flush() in grant_role() since this method may be called a # great number of times in the same transaction, and sqlalchemy limits # to 100 flushes before triggering a warning for ra in ( o for models in (session.new, session.dirty) for o in models if isinstance(o, RoleAssignment) ): if all(getattr(ra, attr) == val for attr, val in args.items()): return ra = RoleAssignment(**args) session.add(ra) audit = SecurityAudit(manager=manager, op=SecurityAudit.GRANT, **args) if obj is not None: audit.object_id = obj.id audit.object_type = obj.entity_type object_name = "" for attr_name in ("name", "path", "__path_before_delete"): if hasattr(obj, attr_name): object_name = getattr(obj, attr_name) audit.object_name = object_name session.add(audit) self._needs_flush() if hasattr(principal, "__roles_cache__"): del principal.__roles_cache__
Grant `role` to `user` (either globally, if `obj` is None, or on the specific `obj`).
entailment
def ungrant_role(self, principal, role, object=None): """Ungrant `role` to `user` (either globally, if `object` is None, or on the specific `object`).""" assert principal principal = unwrap(principal) session = object_session(object) if object is not None else db.session manager = self._current_user_manager(session=session) args = { "role": role, "object": object, "anonymous": False, "user": None, "group": None, } query = session.query(RoleAssignment) query = query.filter( RoleAssignment.role == role, RoleAssignment.object == object ) if principal is AnonymousRole or ( hasattr(principal, "is_anonymous") and principal.is_anonymous ): args["anonymous"] = True query.filter( RoleAssignment.anonymous == False, RoleAssignment.user == None, RoleAssignment.group == None, ) elif isinstance(principal, User): args["user"] = principal query = query.filter(RoleAssignment.user == principal) else: args["group"] = principal query = query.filter(RoleAssignment.group == principal) ra = query.one() session.delete(ra) audit = SecurityAudit(manager=manager, op=SecurityAudit.REVOKE, **args) session.add(audit) self._needs_flush() self._clear_role_cache(principal)
Ungrant `role` to `user` (either globally, if `object` is None, or on the specific `object`).
entailment
def has_permission(self, user, permission, obj=None, inherit=False, roles=None): """ :param obj: target object to check permissions. :param inherit: check with permission inheritance. By default, check only local roles. :param roles: additional valid role or iterable of roles having `permission`. """ if not isinstance(permission, Permission): assert permission in PERMISSIONS permission = Permission(permission) user = unwrap(user) if not self.running: return True session = None if obj is not None: session = object_session(obj) if session is None: session = db.session() # root always have any permission if isinstance(user, User) and user.id == 0: return True # valid roles # 1: from database pa_filter = PermissionAssignment.object == None if obj is not None and obj.id is not None: pa_filter |= PermissionAssignment.object == obj pa_filter &= PermissionAssignment.permission == permission valid_roles = session.query(PermissionAssignment.role).filter(pa_filter) valid_roles = {res[0] for res in valid_roles.yield_per(1000)} # complete with defaults valid_roles |= {Admin} # always have all permissions valid_roles |= DEFAULT_PERMISSION_ROLE.get(permission, set()) # FIXME: obj.__class__ could define default permisssion matrix too if roles is not None: if isinstance(roles, (Role,) + (str,)): roles = (roles,) for r in roles: valid_roles.add(Role(r)) # FIXME: query permission_role: global and on object if AnonymousRole in valid_roles: return True if Authenticated in valid_roles and not user.is_anonymous: return True # first test global roles, then object local roles checked_objs = [None, obj] if inherit and obj is not None: while obj.inherit_security and obj.parent is not None: obj = obj.parent checked_objs.append(obj) principals = [user] + list(user.groups) self._fill_role_cache_batch(principals) return any( self.has_role(principal, valid_roles, item) for principal in principals for item in checked_objs )
:param obj: target object to check permissions. :param inherit: check with permission inheritance. By default, check only local roles. :param roles: additional valid role or iterable of roles having `permission`.
entailment
def query_entity_with_permission(self, permission, user=None, Model=Entity): """Filter a query on an :class:`Entity` or on of its subclasses. Usage:: read_q = security.query_entity_with_permission(READ, Model=MyModel) MyModel.query.filter(read_q) It should always be placed before any `.join()` happens in the query; else sqlalchemy might join to the "wrong" entity table when joining to other :class:`Entity`. :param user: user to filter for. Default: `current_user`. :param permission: required :class:`Permission` :param Model: An :class:`Entity` based class. Useful when there is more than one Entity based object in query, or if an alias should be used. :returns: a `sqlalchemy.sql.exists()` expression. """ assert isinstance(permission, Permission) assert issubclass(Model, Entity) RA = sa.orm.aliased(RoleAssignment) PA = sa.orm.aliased(PermissionAssignment) # id column from entity table. Model.id would refer to 'model' table. # this allows the DB to use indexes / foreign key constraints. id_column = sa.inspect(Model).primary_key[0] creator = Model.creator owner = Model.owner if not self.running: return sa.sql.exists([1]) if user is None: user = unwrap(current_user) # build role CTE principal_filter = RA.anonymous == True if not user.is_anonymous: principal_filter |= RA.user == user if user.groups: principal_filter |= RA.group_id.in_([g.id for g in user.groups]) RA = sa.sql.select([RA], principal_filter).cte() permission_exists = sa.sql.exists([1]).where( sa.sql.and_( PA.permission == permission, PA.object_id == id_column, (RA.c.role == PA.role) | (PA.role == AnonymousRole), (RA.c.object_id == PA.object_id) | (RA.c.object_id == None), ) ) # is_admin: self-explanatory. It search for local or global admin # role, but PermissionAssignment is not involved, thus it can match on # entities that don't have *any permission assignment*, whereas previous # expressions cannot. is_admin = sa.sql.exists([1]).where( sa.sql.and_( RA.c.role == Admin, (RA.c.object_id == id_column) | (RA.c.object_id == None), principal_filter, ) ) filter_expr = permission_exists | is_admin if user and not user.is_anonymous: is_owner_or_creator = sa.sql.exists([1]).where( sa.sql.and_( PA.permission == permission, PA.object_id == id_column, sa.sql.or_( (PA.role == Owner) & (owner == user), (PA.role == Creator) & (creator == user), ), ) ) filter_expr |= is_owner_or_creator return filter_expr
Filter a query on an :class:`Entity` or on of its subclasses. Usage:: read_q = security.query_entity_with_permission(READ, Model=MyModel) MyModel.query.filter(read_q) It should always be placed before any `.join()` happens in the query; else sqlalchemy might join to the "wrong" entity table when joining to other :class:`Entity`. :param user: user to filter for. Default: `current_user`. :param permission: required :class:`Permission` :param Model: An :class:`Entity` based class. Useful when there is more than one Entity based object in query, or if an alias should be used. :returns: a `sqlalchemy.sql.exists()` expression.
entailment
def get_permissions_assignments(self, obj=None, permission=None): """ :param permission: return only roles having this permission :returns: an dict where keys are `permissions` and values `roles` iterable. """ session = None if obj is not None: assert isinstance(obj, Entity) session = object_session(obj) if obj.id is None: obj = None if session is None: session = db.session() pa = session.query( PermissionAssignment.permission, PermissionAssignment.role ).filter(PermissionAssignment.object == obj) if permission: pa = pa.filter(PermissionAssignment.permission == permission) results = {} for permission, role in pa.yield_per(1000): results.setdefault(permission, set()).add(role) return results
:param permission: return only roles having this permission :returns: an dict where keys are `permissions` and values `roles` iterable.
entailment
def register_asset(self, type_, *assets): """Register webassets bundle to be served on all pages. :param type_: `"css"`, `"js-top"` or `"js""`. :param assets: a path to file, a :ref:`webassets.Bundle <webassets:bundles>` instance or a callable that returns a :ref:`webassets.Bundle <webassets:bundles>` instance. :raises KeyError: if `type_` is not supported. """ supported = list(self._assets_bundles.keys()) if type_ not in supported: msg = "Invalid type: {}. Valid types: {}".format( repr(type_), ", ".join(sorted(supported)) ) raise KeyError(msg) for asset in assets: if not isinstance(asset, Bundle) and callable(asset): asset = asset() self._assets_bundles[type_].setdefault("bundles", []).append(asset)
Register webassets bundle to be served on all pages. :param type_: `"css"`, `"js-top"` or `"js""`. :param assets: a path to file, a :ref:`webassets.Bundle <webassets:bundles>` instance or a callable that returns a :ref:`webassets.Bundle <webassets:bundles>` instance. :raises KeyError: if `type_` is not supported.
entailment
def register_i18n_js(self, *paths): """Register templates path translations files, like `select2/select2_locale_{lang}.js`. Only existing files are registered. """ languages = self.config["BABEL_ACCEPT_LANGUAGES"] assets = self.extensions["webassets"] for path in paths: for lang in languages: filename = path.format(lang=lang) try: assets.resolver.search_for_source(assets, filename) except IOError: pass # logger.debug('i18n JS not found, skipped: "%s"', filename) else: self.register_asset("js-i18n-" + lang, filename)
Register templates path translations files, like `select2/select2_locale_{lang}.js`. Only existing files are registered.
entailment
def register_base_assets(self): """Register assets needed by Abilian. This is done in a separate method in order to allow applications to redefine it at will. """ from abilian.web import assets as bundles self.register_asset("css", bundles.LESS) self.register_asset("js-top", bundles.TOP_JS) self.register_asset("js", bundles.JS) self.register_i18n_js(*bundles.JS_I18N)
Register assets needed by Abilian. This is done in a separate method in order to allow applications to redefine it at will.
entailment
def user_photo_url(user, size): """Return url to use for this user.""" endpoint, kwargs = user_url_args(user, size) return url_for(endpoint, **kwargs)
Return url to use for this user.
entailment
def make_response(self, image, size, mode, filename=None, *args, **kwargs): """ :param image: image as bytes :param size: requested maximum width/height size :param mode: one of 'scale', 'fit' or 'crop' :param filename: filename """ try: fmt = get_format(image) except IOError: # not a known image file raise NotFound() self.content_type = "image/png" if fmt == "PNG" else "image/jpeg" ext = "." + str(fmt.lower()) if not filename: filename = "image" if not filename.lower().endswith(ext): filename += ext self.filename = filename if size: image = resize(image, size, size, mode=mode) if mode == CROP: assert get_size(image) == (size, size) else: image = image.read() return make_response(image)
:param image: image as bytes :param size: requested maximum width/height size :param mode: one of 'scale', 'fit' or 'crop' :param filename: filename
entailment
def newlogins(sessions): """Brand new logins each day, and total of users each day. :return: data, total 2 lists of dictionaries of the following format [{'x':epoch, 'y': value},] """ if not sessions: return [], [] users = {} dates = {} for session in sessions: user = session.user # time value is discarded to aggregate on days only date = session.started_at.strftime("%Y/%m/%d") # keep the info only it's the first time we encounter a user if user not in users: users[user] = date # build the list of users on a given day if date not in dates: dates[date] = [user] else: dates[date].append(user) data = [] total = [] previous = 0 for date in sorted(dates.keys()): # print u"{} : {}".format(date, len(dates[date])) date_epoch = unix_time_millis(datetime.strptime(date, "%Y/%m/%d")) data.append({"x": date_epoch, "y": len(dates[date])}) previous += len(dates[date]) total.append({"x": date_epoch, "y": previous}) return data, total
Brand new logins each day, and total of users each day. :return: data, total 2 lists of dictionaries of the following format [{'x':epoch, 'y': value},]
entailment
def uniquelogins(sessions): """Unique logins per days/weeks/months. :return: daily, weekly, monthly 3 lists of dictionaries of the following format [{'x':epoch, 'y': value},] """ # sessions = LoginSession.query.order_by(LoginSession.started_at.asc()).all() if not sessions: return [], [], [] dates = {} for session in sessions: user = session.user # time value is discarded to aggregate on days only date = session.started_at.strftime("%Y/%m/%d") if date not in dates: dates[date] = set() # we want unique users on a given day dates[date].add(user) else: dates[date].add(user) daily = [] weekly = [] monthly = [] for date in sorted(dates.keys()): # print u"{} : {}".format(date, len(dates[date])) date_epoch = unix_time_millis(datetime.strptime(date, "%Y/%m/%d")) daily.append({"x": date_epoch, "y": len(dates[date])}) # first_day = data[0]['x'] # last_day = data[-1]['x'] daily_serie = pd.Series(dates) # convert the index to Datetime type daily_serie.index = pd.DatetimeIndex(daily_serie.index) # calculate the values instead of users lists daily_serie = daily_serie.apply(lambda x: len(x)) # GroupBy Week/month, Thanks Panda weekly_serie = daily_serie.groupby(pd.Grouper(freq="W")).aggregate(numpysum) monthly_serie = daily_serie.groupby(pd.Grouper(freq="M")).aggregate(numpysum) for date, value in weekly_serie.items(): try: value = int(value) except ValueError: continue date_epoch = unix_time_millis(date) weekly.append({"x": date_epoch, "y": value}) for date, value in monthly_serie.items(): try: value = int(value) except ValueError: continue date_epoch = unix_time_millis(date) monthly.append({"x": date_epoch, "y": value}) return daily, weekly, monthly
Unique logins per days/weeks/months. :return: daily, weekly, monthly 3 lists of dictionaries of the following format [{'x':epoch, 'y': value},]
entailment
def allow_access_for_roles(roles): """Access control helper to check user's roles against a list of valid roles.""" if isinstance(roles, Role): roles = (roles,) valid_roles = frozenset(roles) if Anonymous in valid_roles: return allow_anonymous def check_role(user, roles, **kwargs): from abilian.services import get_service security = get_service("security") return security.has_role(user, valid_roles) return check_role
Access control helper to check user's roles against a list of valid roles.
entailment
def populate_obj(self, obj, name): """Store file.""" from abilian.core.models.blob import Blob delete_value = self.allow_delete and self.delete_files_index if not self.has_file() and not delete_value: # nothing uploaded, and nothing to delete return state = sa.inspect(obj) mapper = state.mapper if name not in mapper.relationships: # directly store in database return super().populate_obj(obj, name) rel = getattr(mapper.relationships, name) if rel.uselist: raise ValueError("Only single target supported; else use ModelFieldList") if delete_value: setattr(obj, name, None) return # FIXME: propose option to always create a new blob cls = rel.mapper.class_ val = getattr(obj, name) if val is None: val = cls() setattr(obj, name, val) data = "" if self.has_file(): data = self.data if not issubclass(cls, Blob): data = data.read() setattr(val, self.blob_attr, data)
Store file.
entailment
def _get_pk_from_identity(obj): """Copied / pasted, and fixed, from WTForms_sqlalchemy due to issue w/ SQLAlchemy >= 1.2.""" from sqlalchemy.orm.util import identity_key cls, key = identity_key(instance=obj)[0:2] return ":".join(text_type(x) for x in key)
Copied / pasted, and fixed, from WTForms_sqlalchemy due to issue w/ SQLAlchemy >= 1.2.
entailment
def keys(self, prefix=None): """List all keys, with optional prefix filtering.""" query = Setting.query if prefix: query = query.filter(Setting.key.startswith(prefix)) # don't use iteritems: 'value' require little processing whereas we only # want 'key' return [i[0] for i in query.yield_per(1000).values(Setting.key)]
List all keys, with optional prefix filtering.
entailment
def iteritems(self, prefix=None): """Like dict.iteritems.""" query = Setting.query if prefix: query = query.filter(Setting.key.startswith(prefix)) for s in query.yield_per(1000): yield (s.key, s.value)
Like dict.iteritems.
entailment
def register(cls): """Register an :class:`Entity` as a commentable class. Can be used as a class decorator: .. code-block:: python @comment.register class MyContent(Entity): ... """ if not issubclass(cls, Entity): raise ValueError("Class must be a subclass of abilian.core.entities.Entity") Commentable.register(cls) return cls
Register an :class:`Entity` as a commentable class. Can be used as a class decorator: .. code-block:: python @comment.register class MyContent(Entity): ...
entailment
def is_commentable(obj_or_class): """ :param obj_or_class: a class or instance """ if isinstance(obj_or_class, type): return issubclass(obj_or_class, Commentable) if not isinstance(obj_or_class, Commentable): return False if obj_or_class.id is None: return False return True
:param obj_or_class: a class or instance
entailment
def for_entity(obj, check_commentable=False): """Return comments on an entity.""" if check_commentable and not is_commentable(obj): return [] return getattr(obj, ATTRIBUTE)
Return comments on an entity.
entailment
def available(self, context): """Determine if this actions is available in this `context`. :param context: a dict whose content is left to application needs; if :attr:`.condition` is a callable it receives `context` in parameter. """ if not self._enabled: return False try: return self.pre_condition(context) and self._check_condition(context) except Exception: return False
Determine if this actions is available in this `context`. :param context: a dict whose content is left to application needs; if :attr:`.condition` is a callable it receives `context` in parameter.
entailment
def installed(self, app=None): """Return `True` if the registry has been installed in current applications.""" if app is None: app = current_app return self.__EXTENSION_NAME in app.extensions
Return `True` if the registry has been installed in current applications.
entailment
def register(self, *actions): """Register `actions` in the current application. All `actions` must be an instance of :class:`.Action` or one of its subclasses. If `overwrite` is `True`, then it is allowed to overwrite an existing action with same name and category; else `ValueError` is raised. """ assert self.installed(), "Actions not enabled on this application" assert all(isinstance(a, Action) for a in actions) for action in actions: cat = action.category reg = self._state["categories"].setdefault(cat, []) reg.append(action)
Register `actions` in the current application. All `actions` must be an instance of :class:`.Action` or one of its subclasses. If `overwrite` is `True`, then it is allowed to overwrite an existing action with same name and category; else `ValueError` is raised.
entailment
def actions(self, context=None): """Return a mapping of category => actions list. Actions are filtered according to :meth:`.Action.available`. if `context` is None, then current action context is used (:attr:`context`). """ assert self.installed(), "Actions not enabled on this application" result = {} if context is None: context = self.context for cat, actions in self._state["categories"].items(): result[cat] = [a for a in actions if a.available(context)] return result
Return a mapping of category => actions list. Actions are filtered according to :meth:`.Action.available`. if `context` is None, then current action context is used (:attr:`context`).
entailment
def for_category(self, category, context=None): """Returns actions list for this category in current application. Actions are filtered according to :meth:`.Action.available`. if `context` is None, then current action context is used (:attr:`context`) """ assert self.installed(), "Actions not enabled on this application" actions = self._state["categories"].get(category, []) if context is None: context = self.context return [a for a in actions if a.available(context)]
Returns actions list for this category in current application. Actions are filtered according to :meth:`.Action.available`. if `context` is None, then current action context is used (:attr:`context`)
entailment
def babel2datetime(pattern): """Convert date format from babel (http://babel.pocoo.org/docs/dates/#date- fields)) to a format understood by datetime.strptime.""" if not isinstance(pattern, DateTimePattern): pattern = parse_pattern(pattern) map_fmt = { # days "d": "%d", "dd": "%d", "EEE": "%a", "EEEE": "%A", "EEEEE": "%a", # narrow name => short name # months "M": "%m", "MM": "%m", "MMM": "%b", "MMMM": "%B", # years "y": "%Y", "yy": "%Y", "yyyy": "%Y", # hours "h": "%I", "hh": "%I", "H": "%H", "HH": "%H", # minutes, "m": "%M", "mm": "%M", # seconds "s": "%S", "ss": "%S", # am/pm "a": "%p", } return pattern.format % map_fmt
Convert date format from babel (http://babel.pocoo.org/docs/dates/#date- fields)) to a format understood by datetime.strptime.
entailment
def get_active_for(self, user, user_agent=_MARK, ip_address=_MARK): """Return last known session for given user. :param user: user session :type user: `abilian.core.models.subjects.User` :param user_agent: *exact* user agent string to lookup, or `None` to have user_agent extracted from request object. If not provided at all, no filtering on user_agent. :type user_agent: string or None, or absent :param ip_address: client IP, or `None` to have ip_address extracted from request object (requires header 'X-Forwarded-For'). If not provided at all, no filtering on ip_address. :type ip_address: string or None, or absent :rtype: `LoginSession` or `None` if no session is found. """ conditions = [LoginSession.user == user] if user_agent is not _MARK: if user_agent is None: user_agent = request.environ.get("HTTP_USER_AGENT", "") conditions.append(LoginSession.user_agent == user_agent) if ip_address is not _MARK: if ip_address is None: ip_addresses = request.headers.getlist("X-Forwarded-For") ip_address = ip_addresses[0] if ip_addresses else request.remote_addr conditions.append(LoginSession.ip_address == ip_address) session = ( LoginSession.query.filter(*conditions) .order_by(LoginSession.id.desc()) .first() ) return session
Return last known session for given user. :param user: user session :type user: `abilian.core.models.subjects.User` :param user_agent: *exact* user agent string to lookup, or `None` to have user_agent extracted from request object. If not provided at all, no filtering on user_agent. :type user_agent: string or None, or absent :param ip_address: client IP, or `None` to have ip_address extracted from request object (requires header 'X-Forwarded-For'). If not provided at all, no filtering on ip_address. :type ip_address: string or None, or absent :rtype: `LoginSession` or `None` if no session is found.
entailment
def show(only_path=False): """Show the current config.""" logger.setLevel(logging.INFO) infos = ["\n", f'Instance path: "{current_app.instance_path}"'] logger.info("\n ".join(infos)) if not only_path: log_config(current_app.config)
Show the current config.
entailment
def should_handle(self, event_type, filename): """Check if an event should be handled. An event should be handled if a file in the searchpath was modified. :param event_type: a string, representing the type of event :param filename: the path to the file that triggered the event. """ return (event_type in ("modified", "created") and filename.startswith(self.searchpath) and os.path.isfile(filename))
Check if an event should be handled. An event should be handled if a file in the searchpath was modified. :param event_type: a string, representing the type of event :param filename: the path to the file that triggered the event.
entailment
def event_handler(self, event_type, src_path): """Re-render templates if they are modified. :param event_type: a string, representing the type of event :param src_path: the path to the file that triggered the event. """ filename = os.path.relpath(src_path, self.searchpath) if self.should_handle(event_type, src_path): print("%s %s" % (event_type, filename)) if self.site.is_static(filename): files = self.site.get_dependencies(filename) self.site.copy_static(files) else: templates = self.site.get_dependencies(filename) self.site.render_templates(templates)
Re-render templates if they are modified. :param event_type: a string, representing the type of event :param src_path: the path to the file that triggered the event.
entailment
def protect(view): """Protects a view agains CSRF attacks by checking `csrf_token` value in submitted values. Do nothing if `config.WTF_CSRF_ENABLED` is not set. Raises `werkzeug.exceptions.Forbidden` if validation fails. """ @wraps(view) def csrf_check(*args, **kwargs): # an empty form is used to validate current csrf token and only that! if not FlaskForm().validate(): raise Forbidden("CSRF validation failed.") return view(*args, **kwargs) return csrf_check
Protects a view agains CSRF attacks by checking `csrf_token` value in submitted values. Do nothing if `config.WTF_CSRF_ENABLED` is not set. Raises `werkzeug.exceptions.Forbidden` if validation fails.
entailment
def createuser(email, password, role=None, name=None, first_name=None): """Create new user.""" if User.query.filter(User.email == email).count() > 0: print(f"A user with email '{email}' already exists, aborting.") return # if password is None: # password = prompt_pass("Password") user = User( email=email, password=password, last_name=name, first_name=first_name, can_login=True, ) db.session.add(user) if role in ("admin",): # FIXME: add other valid roles security = get_service("security") security.grant_role(user, role) db.session.commit() print(f"User {email} added")
Create new user.
entailment
def auto_slug_on_insert(mapper, connection, target): """Generate a slug from :prop:`Entity.auto_slug` for new entities, unless slug is already set.""" if target.slug is None and target.name: target.slug = target.auto_slug
Generate a slug from :prop:`Entity.auto_slug` for new entities, unless slug is already set.
entailment
def auto_slug_after_insert(mapper, connection, target): """Generate a slug from entity_type and id, unless slug is already set.""" if target.slug is None: target.slug = "{name}{sep}{id}".format( name=target.entity_class.lower(), sep=target.SLUG_SEPARATOR, id=target.id )
Generate a slug from entity_type and id, unless slug is already set.
entailment
def setup_default_permissions(session, instance): """Setup default permissions on newly created entities according to. :attr:`Entity.__default_permissions__`. """ if instance not in session.new or not isinstance(instance, Entity): return if not current_app: # working outside app_context. Raw object manipulation return _setup_default_permissions(instance)
Setup default permissions on newly created entities according to. :attr:`Entity.__default_permissions__`.
entailment
def _setup_default_permissions(instance): """Separate method to conveniently call it from scripts for example.""" from abilian.services import get_service security = get_service("security") for permission, roles in instance.__default_permissions__: if permission == "create": # use str for comparison instead of `abilian.services.security.CREATE` # symbol to avoid imports that quickly become circular. # # FIXME: put roles and permissions in a separate, isolated module. continue for role in roles: security.add_permission(permission, role, obj=instance)
Separate method to conveniently call it from scripts for example.
entailment
def polymorphic_update_timestamp(session, flush_context, instances): """This listener ensures an update statement is emited for "entity" table to update 'updated_at'. With joined-table inheritance if the only modified attributes are subclass's ones, then no update statement will be emitted. """ for obj in session.dirty: if not isinstance(obj, Entity): continue state = sa.inspect(obj) history = state.attrs["updated_at"].history if not any((history.added, history.deleted)): obj.updated_at = datetime.utcnow()
This listener ensures an update statement is emited for "entity" table to update 'updated_at'. With joined-table inheritance if the only modified attributes are subclass's ones, then no update statement will be emitted.
entailment
def all_entity_classes(): """Return the list of all concrete persistent classes that are subclasses of Entity.""" persistent_classes = Entity._decl_class_registry.values() # with sqlalchemy 0.8 _decl_class_registry holds object that are not # classes return [ cls for cls in persistent_classes if isclass(cls) and issubclass(cls, Entity) ]
Return the list of all concrete persistent classes that are subclasses of Entity.
entailment
def auto_slug(self): """This property is used to auto-generate a slug from the name attribute. It can be customized by subclasses. """ slug = self.name if slug is not None: slug = slugify(slug, separator=self.SLUG_SEPARATOR) session = sa.orm.object_session(self) if not session: return None query = session.query(Entity.slug).filter( Entity._entity_type == self.object_type ) if self.id is not None: query = query.filter(Entity.id != self.id) slug_re = re.compile(re.escape(slug) + r"-?(-\d+)?") results = [ int(m.group(1) or 0) # 0: for the unnumbered slug for m in (slug_re.match(s.slug) for s in query.all() if s.slug) if m ] max_id = max(-1, -1, *results) + 1 if max_id: slug = f"{slug}-{max_id}" return slug
This property is used to auto-generate a slug from the name attribute. It can be customized by subclasses.
entailment
def _indexable_roles_and_users(self): """Return a string made for indexing roles having :any:`READ` permission on this object.""" from abilian.services.indexing import indexable_role from abilian.services.security import READ, Admin, Anonymous, Creator, Owner from abilian.services import get_service result = [] security = get_service("security") # roles - required to match when user has a global role assignments = security.get_permissions_assignments(permission=READ, obj=self) allowed_roles = assignments.get(READ, set()) allowed_roles.add(Admin) for r in allowed_roles: result.append(indexable_role(r)) for role, attr in ((Creator, "creator"), (Owner, "owner")): if role in allowed_roles: user = getattr(self, attr) if user: result.append(indexable_role(user)) # users and groups principals = set() for user, role in security.get_role_assignements(self): if role in allowed_roles: principals.add(user) if Anonymous in principals: # it's a role listed in role assignments - legacy when there wasn't # permission-role assignments principals.remove(Anonymous) for p in principals: result.append(indexable_role(p)) return " ".join(result)
Return a string made for indexing roles having :any:`READ` permission on this object.
entailment
def _indexable_tags(self): """Index tag ids for tags defined in this Entity's default tags namespace.""" tags = current_app.extensions.get("tags") if not tags or not tags.supports_taggings(self): return "" default_ns = tags.entity_default_ns(self) return [t for t in tags.entity_tags(self) if t.ns == default_ns]
Index tag ids for tags defined in this Entity's default tags namespace.
entailment
def country_choices(first=None, default_country_first=True): """Return a list of (code, countries), alphabetically sorted on localized country name. :param first: Country code to be placed at the top :param default_country_first: :type default_country_first: bool """ locale = _get_locale() territories = [ (code, name) for code, name in locale.territories.items() if len(code) == 2 ] # skip 3-digit regions if first is None and default_country_first: first = default_country() def sortkey(item): if first is not None and item[0] == first: return "0" return to_lower_ascii(item[1]) territories.sort(key=sortkey) return territories
Return a list of (code, countries), alphabetically sorted on localized country name. :param first: Country code to be placed at the top :param default_country_first: :type default_country_first: bool
entailment
def supported_app_locales(): """Language codes and labels supported by current application. :return: an iterable of `(:class:`babel.Locale`, label)`, label being the locale language human name in current locale. """ locale = _get_locale() codes = current_app.config["BABEL_ACCEPT_LANGUAGES"] return ((Locale.parse(code), locale.languages.get(code, code)) for code in codes)
Language codes and labels supported by current application. :return: an iterable of `(:class:`babel.Locale`, label)`, label being the locale language human name in current locale.
entailment
def timezones_choices(): """Timezones values and their labels for current locale. :return: an iterable of `(code, label)`, code being a timezone code and label the timezone name in current locale. """ utcnow = pytz.utc.localize(datetime.utcnow()) locale = _get_locale() for tz in sorted(pytz.common_timezones): tz = get_timezone(tz) now = tz.normalize(utcnow.astimezone(tz)) label = "({}) {}".format(get_timezone_gmt(now, locale=locale), tz.zone) yield (tz, label)
Timezones values and their labels for current locale. :return: an iterable of `(code, label)`, code being a timezone code and label the timezone name in current locale.
entailment
def _get_translations_multi_paths(): """Return the correct gettext translations that should be used for this request. This will never fail and return a dummy translation object if used outside of the request or if a translation cannot be found. """ ctx = _request_ctx_stack.top if ctx is None: return None translations = getattr(ctx, "babel_translations", None) if translations is None: babel_ext = ctx.app.extensions["babel"] translations = None trs = None # reverse order: thus the application catalog is loaded last, so that # translations from libraries can be overriden for (dirname, domain) in reversed(babel_ext._translations_paths): trs = Translations.load( dirname, locales=[flask_babel.get_locale()], domain=domain ) # babel.support.Translations is a subclass of # babel.support.NullTranslations, so we test if object has a 'merge' # method if not trs or not hasattr(trs, "merge"): # got None or NullTranslations instance continue elif translations is not None and hasattr(translations, "merge"): translations.merge(trs) else: translations = trs # ensure translations is at least a NullTranslations object if translations is None: translations = trs ctx.babel_translations = translations return translations
Return the correct gettext translations that should be used for this request. This will never fail and return a dummy translation object if used outside of the request or if a translation cannot be found.
entailment
def localeselector(): """Default locale selector used in abilian applications.""" # if a user is logged in, use the locale from the user settings user = getattr(g, "user", None) if user is not None: locale = getattr(user, "locale", None) if locale: return locale # Otherwise, try to guess the language from the user accept header the browser # transmits. By default we support en/fr. The best match wins. return request.accept_languages.best_match( current_app.config["BABEL_ACCEPT_LANGUAGES"] )
Default locale selector used in abilian applications.
entailment
def get_template_i18n(template_name, locale): """Build template list with preceding locale if found.""" if locale is None: return [template_name] template_list = [] parts = template_name.rsplit(".", 1) root = parts[0] suffix = parts[1] if locale.territory is not None: locale_string = "_".join([locale.language, locale.territory]) localized_template_path = ".".join([root, locale_string, suffix]) template_list.append(localized_template_path) localized_template_path = ".".join([root, locale.language, suffix]) template_list.append(localized_template_path) # append the default template_list.append(template_name) return template_list
Build template list with preceding locale if found.
entailment
def render_template_i18n(template_name_or_list, **context): """Try to build an ordered list of template to satisfy the current locale.""" template_list = [] # Use locale if present in **context if "locale" in context: locale = Locale.parse(context["locale"]) else: # Use get_locale() or default_locale locale = flask_babel.get_locale() if isinstance(template_name_or_list, str): template_list = get_template_i18n(template_name_or_list, locale) else: # Search for locale for each member of the list, do not bypass for template in template_name_or_list: template_list.extend(get_template_i18n(template, locale)) with ensure_request_context(), force_locale(locale): return render_template(template_list, **context)
Try to build an ordered list of template to satisfy the current locale.
entailment
def add_translations( self, module_name, translations_dir="translations", domain="messages" ): """Add translations from external module. For example:: babel.add_translations('abilian.core') Will add translations files from `abilian.core` module. """ module = importlib.import_module(module_name) for path in (Path(p, translations_dir) for p in module.__path__): if not (path.exists() and path.is_dir()): continue if not os.access(str(path), os.R_OK): self.app.logger.warning( "Babel translations: read access not allowed {}, skipping." "".format(repr(str(path).encode("utf-8"))) ) continue self._translations_paths.append((str(path), domain))
Add translations from external module. For example:: babel.add_translations('abilian.core') Will add translations files from `abilian.core` module.
entailment
def get(self, attach, *args, **kwargs): """ :param attach: if True, return file as an attachment. """ response = self.make_response(*args, **kwargs) # type: Response response.content_type = self.get_content_type(*args, **kwargs) if attach: filename = self.get_filename(*args, **kwargs) if not filename: filename = "file.bin" headers = response.headers headers.add("Content-Disposition", "attachment", filename=filename) self.set_cache_headers(response) return response
:param attach: if True, return file as an attachment.
entailment
def ping_connection(dbapi_connection, connection_record, connection_proxy): """Ensure connections are valid. From: `http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html` In case db has been restarted pool may return invalid connections. """ cursor = dbapi_connection.cursor() try: cursor.execute("SELECT 1") except Exception: # optional - dispose the whole pool # instead of invalidating one at a time # connection_proxy._pool.dispose() # raise DisconnectionError - pool will try # connecting again up to three times before raising. raise sa.exc.DisconnectionError() cursor.close()
Ensure connections are valid. From: `http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html` In case db has been restarted pool may return invalid connections.
entailment
def filter_cols(model, *filtered_columns): """Return columnsnames for a model except named ones. Useful for defer() for example to retain only columns of interest """ m = sa.orm.class_mapper(model) return list( {p.key for p in m.iterate_properties if hasattr(p, "columns")}.difference( filtered_columns ) )
Return columnsnames for a model except named ones. Useful for defer() for example to retain only columns of interest
entailment
def JSONList(*args, **kwargs): """Stores a list as JSON on database, with mutability support. If kwargs has a param `unique_sorted` (which evaluated to True), list values are made unique and sorted. """ type_ = JSON try: if kwargs.pop("unique_sorted"): type_ = JSONUniqueListType except KeyError: pass return MutationList.as_mutable(type_(*args, **kwargs))
Stores a list as JSON on database, with mutability support. If kwargs has a param `unique_sorted` (which evaluated to True), list values are made unique and sorted.
entailment
def coerce(cls, key, value): """Convert plain dictionaries to MutationDict.""" if not isinstance(value, MutationDict): if isinstance(value, dict): return MutationDict(value) # this call will raise ValueError return Mutable.coerce(key, value) else: return value
Convert plain dictionaries to MutationDict.
entailment
def coerce(cls, key, value): """Convert list to MutationList.""" if not isinstance(value, MutationList): if isinstance(value, list): return MutationList(value) # this call will raise ValueError return Mutable.coerce(key, value) else: return value
Convert list to MutationList.
entailment
def add_file(self, user, file_obj, **metadata): """Add a new file. :returns: file handle """ user_dir = self.user_dir(user) if not user_dir.exists(): user_dir.mkdir(mode=0o775) handle = str(uuid1()) file_path = user_dir / handle with file_path.open("wb") as out: for chunk in iter(lambda: file_obj.read(CHUNK_SIZE), b""): out.write(chunk) if metadata: meta_file = user_dir / f"{handle}.metadata" with meta_file.open("wb") as out: metadata_json = json.dumps(metadata, skipkeys=True).encode("ascii") out.write(metadata_json) return handle
Add a new file. :returns: file handle
entailment
def get_file(self, user, handle): """Retrieve a file for a user. :returns: a :class:`pathlib.Path` instance to this file, or None if no file can be found for this handle. """ user_dir = self.user_dir(user) if not user_dir.exists(): return None if not is_valid_handle(handle): return None file_path = user_dir / handle if not file_path.exists() and not file_path.is_file(): return None return file_path
Retrieve a file for a user. :returns: a :class:`pathlib.Path` instance to this file, or None if no file can be found for this handle.
entailment
def clear_stalled_files(self): """Scan upload directory and delete stalled files. Stalled files are files uploaded more than `DELETE_STALLED_AFTER` seconds ago. """ # FIXME: put lock in directory? CLEAR_AFTER = self.config["DELETE_STALLED_AFTER"] minimum_age = time.time() - CLEAR_AFTER for user_dir in self.UPLOAD_DIR.iterdir(): if not user_dir.is_dir(): logger.error("Found non-directory in upload dir: %r", bytes(user_dir)) continue for content in user_dir.iterdir(): if not content.is_file(): logger.error( "Found non-file in user upload dir: %r", bytes(content) ) continue if content.stat().st_ctime < minimum_age: content.unlink()
Scan upload directory and delete stalled files. Stalled files are files uploaded more than `DELETE_STALLED_AFTER` seconds ago.
entailment
def friendly_fqcn(cls_name): """Friendly name of fully qualified class name. :param cls_name: a string or a class """ if isinstance(cls_name, type): cls_name = fqcn(cls_name) return cls_name.rsplit(".", 1)[-1]
Friendly name of fully qualified class name. :param cls_name: a string or a class
entailment
def local_dt(dt): """Return an aware datetime in system timezone, from a naive or aware datetime. Naive datetime are assumed to be in UTC TZ. """ if not dt.tzinfo: dt = pytz.utc.localize(dt) return LOCALTZ.normalize(dt.astimezone(LOCALTZ))
Return an aware datetime in system timezone, from a naive or aware datetime. Naive datetime are assumed to be in UTC TZ.
entailment
def utc_dt(dt): """Set UTC timezone on a datetime object. A naive datetime is assumed to be in UTC TZ. """ if not dt.tzinfo: return pytz.utc.localize(dt) return dt.astimezone(pytz.utc)
Set UTC timezone on a datetime object. A naive datetime is assumed to be in UTC TZ.
entailment
def get_params(names): """Return a dictionary with params from request. TODO: I think we don't use it anymore and it should be removed before someone gets hurt. """ params = {} for name in names: value = request.form.get(name) or request.files.get(name) if value is not None: params[name] = value return params
Return a dictionary with params from request. TODO: I think we don't use it anymore and it should be removed before someone gets hurt.
entailment
def slugify(value, separator="-"): """Slugify an Unicode string, to make it URL friendly.""" if not isinstance(value, str): raise ValueError("value must be a Unicode string") value = _NOT_WORD_RE.sub(" ", value) value = unicodedata.normalize("NFKD", value) value = value.encode("ascii", "ignore") value = value.decode("ascii") value = value.strip().lower() value = re.sub(fr"[{separator}_\s]+", separator, value) return value
Slugify an Unicode string, to make it URL friendly.
entailment
def luhn(n): """Validate that a string made of numeric characters verify Luhn test. Used by siret validator. from http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python https://en.wikipedia.org/wiki/Luhn_algorithm """ r = [int(ch) for ch in str(n)][::-1] return (sum(r[0::2]) + sum(sum(divmod(d * 2, 10)) for d in r[1::2])) % 10 == 0
Validate that a string made of numeric characters verify Luhn test. Used by siret validator. from http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python https://en.wikipedia.org/wiki/Luhn_algorithm
entailment
def siret_validator(): """Validate a SIRET: check its length (14), its final code, and pass it through the Luhn algorithm.""" def _validate_siret(form, field, siret=""): """SIRET validator. A WTForm validator wants a form and a field as parameters. We also want to give directly a siret, for a scripting use. """ if field is not None: siret = (field.data or "").strip() if len(siret) != 14: msg = _("SIRET must have exactly 14 characters ({count})").format( count=len(siret) ) raise validators.ValidationError(msg) if not all(("0" <= c <= "9") for c in siret): if not siret[-3:] in SIRET_CODES: msg = _( "SIRET looks like special SIRET but geographical " "code seems invalid (%(code)s)", code=siret[-3:], ) raise validators.ValidationError(msg) elif not luhn(siret): msg = _("SIRET number is invalid (length is ok: verify numbers)") raise validators.ValidationError(msg) return _validate_siret
Validate a SIRET: check its length (14), its final code, and pass it through the Luhn algorithm.
entailment
def get_rel_attr(self, attr_name, model): """For a related attribute specification, returns (related model, attribute). Returns (None, None) if model is not found, or (model, None) if attribute is not found. """ rel_attr_name, attr_name = attr_name.split(".", 1) rel_attr = getattr(self.model, rel_attr_name, None) rel_model = None attr = None if rel_attr is not None: rel_model = rel_attr.property.mapper.class_ attr = getattr(rel_model, attr_name, None) return rel_model, attr
For a related attribute specification, returns (related model, attribute). Returns (None, None) if model is not found, or (model, None) if attribute is not found.
entailment
def rel_path(self, uuid): # type: (UUID) -> Path """Contruct relative path from repository top directory to the file named after this uuid. :param:uuid: :class:`UUID` instance """ _assert_uuid(uuid) filename = str(uuid) return Path(filename[0:2], filename[2:4], filename)
Contruct relative path from repository top directory to the file named after this uuid. :param:uuid: :class:`UUID` instance
entailment
def abs_path(self, uuid): # type: (UUID) -> Path """Return absolute :class:`Path` object for given uuid. :param:uuid: :class:`UUID` instance """ top = self.app_state.path rel_path = self.rel_path(uuid) dest = top / rel_path assert top in dest.parents return dest
Return absolute :class:`Path` object for given uuid. :param:uuid: :class:`UUID` instance
entailment
def get(self, uuid, default=None): # type: (UUID, Optional[Path]) -> Optional[Path] """Return absolute :class:`Path` object for given uuid, if this uuid exists in repository, or `default` if it doesn't. :param:uuid: :class:`UUID` instance """ path = self.abs_path(uuid) if not path.exists(): return default return path
Return absolute :class:`Path` object for given uuid, if this uuid exists in repository, or `default` if it doesn't. :param:uuid: :class:`UUID` instance
entailment
def set(self, uuid, content, encoding="utf-8"): # type: (UUID, Any, Optional[Text]) -> None """Store binary content with uuid as key. :param:uuid: :class:`UUID` instance :param:content: string, bytes, or any object with a `read()` method :param:encoding: encoding to use when content is Unicode """ dest = self.abs_path(uuid) if not dest.parent.exists(): dest.parent.mkdir(0o775, parents=True) if hasattr(content, "read"): content = content.read() mode = "tw" if not isinstance(content, str): mode = "bw" encoding = None with dest.open(mode, encoding=encoding) as f: f.write(content)
Store binary content with uuid as key. :param:uuid: :class:`UUID` instance :param:content: string, bytes, or any object with a `read()` method :param:encoding: encoding to use when content is Unicode
entailment
def delete(self, uuid): # type: (UUID) -> None """Delete file with given uuid. :param:uuid: :class:`UUID` instance :raises:KeyError if file does not exists """ dest = self.abs_path(uuid) if not dest.exists(): raise KeyError("No file can be found for this uuid", uuid) dest.unlink()
Delete file with given uuid. :param:uuid: :class:`UUID` instance :raises:KeyError if file does not exists
entailment
def set_transaction(self, session, transaction): # type: (Session, RepositoryTransaction) -> None """ :param:session: :class:`sqlalchemy.orm.session.Session` instance :param:transaction: :class:`RepositoryTransaction` instance """ if isinstance(session, sa.orm.scoped_session): session = session() s_id = id(session) self.transactions[s_id] = (weakref.ref(session), transaction)
:param:session: :class:`sqlalchemy.orm.session.Session` instance :param:transaction: :class:`RepositoryTransaction` instance
entailment
def _session_for(self, model_or_session): """Return session instance for object parameter. If parameter is a session instance, it is return as is. If parameter is a registered model instance, its session will be used. If parameter is a detached model instance, or None, application scoped session will be used (db.session()) If parameter is a scoped_session instance, a new session will be instanciated. """ session = model_or_session if not isinstance(session, (Session, sa.orm.scoped_session)): if session is not None: session = sa.orm.object_session(model_or_session) if session is None: session = db.session if isinstance(session, sa.orm.scoped_session): session = session() return session
Return session instance for object parameter. If parameter is a session instance, it is return as is. If parameter is a registered model instance, its session will be used. If parameter is a detached model instance, or None, application scoped session will be used (db.session()) If parameter is a scoped_session instance, a new session will be instanciated.
entailment
def commit(self, session=None): """Merge modified objects into parent transaction. Once commited a transaction object is not usable anymore :param:session: current sqlalchemy Session """ if self.__cleared: return if self._parent: # nested transaction self._commit_parent() else: self._commit_repository() self._clear()
Merge modified objects into parent transaction. Once commited a transaction object is not usable anymore :param:session: current sqlalchemy Session
entailment
def _add_to(self, uuid, dest, other): """Add `item` to `dest` set, ensuring `item` is not present in `other` set.""" _assert_uuid(uuid) try: other.remove(uuid) except KeyError: pass dest.add(uuid)
Add `item` to `dest` set, ensuring `item` is not present in `other` set.
entailment
def ns(ns): """Class decorator that sets default tags namespace to use with its instances.""" def setup_ns(cls): setattr(cls, ENTITY_DEFAULT_NS_ATTR, ns) return cls return setup_ns
Class decorator that sets default tags namespace to use with its instances.
entailment
def tags_from_hit(self, tag_ids): """ :param tag_ids: indexed ids of tags in hit result. Do not pass hit instances. :returns: an iterable of :class:`Tag` instances. """ ids = [] for t in tag_ids.split(): t = t.strip() try: t = int(t) except ValueError: pass else: ids.append(t) if not ids: return [] return Tag.query.filter(Tag.id.in_(ids)).all()
:param tag_ids: indexed ids of tags in hit result. Do not pass hit instances. :returns: an iterable of :class:`Tag` instances.
entailment
def entity_tags_form(self, entity, ns=None): """Construct a form class with a field for tags in namespace `ns`.""" if ns is None: ns = self.entity_default_ns(entity) field = TagsField(label=_l("Tags"), ns=ns) cls = type("EntityNSTagsForm", (_TagsForm,), {"tags": field}) return cls
Construct a form class with a field for tags in namespace `ns`.
entailment
def get(self, ns, label=None): """Return :class:`tags instances<~Tag>` for the namespace `ns`, ordered by label. If `label` is not None the only one instance may be returned, or `None` if no tags exists for this label. """ query = Tag.query.filter(Tag.ns == ns) if label is not None: return query.filter(Tag.label == label).first() return query.all()
Return :class:`tags instances<~Tag>` for the namespace `ns`, ordered by label. If `label` is not None the only one instance may be returned, or `None` if no tags exists for this label.
entailment