code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if html: text = _tag_re.sub(' ', text) text = _strip_re.sub('', text) text = _punctuation_re.sub(' ', text) return len(text.split())
def word_count(text, html=True)
Return the count of words in the given text. If the text is HTML (default True), tags are stripped before counting. Handles punctuation and bad formatting like.this when counting words, but assumes conventions for Latin script languages. May not be reliable for other languages.
2.773529
2.792231
0.993302
text = unescape(text) # Find the "dot" text = _deobfuscate_dot1_re.sub('.', text) text = _deobfuscate_dot2_re.sub(r'\1.\2', text) text = _deobfuscate_dot3_re.sub(r'\1.\2', text) # Find the "at" text = _deobfuscate_at1_re.sub('@', text) text = _deobfuscate_at2_re.sub(r'\1@\2', text) text = _deobfuscate_at3_re.sub(r'\1@\2', text) return text
def deobfuscate_email(text)
Deobfuscate email addresses in provided text
1.973893
2.014992
0.979603
if isinstance(text, six.text_type): if six.PY3: # pragma: no cover text = text.translate(text.maketrans("", "", string.punctuation)).lower() else: # pragma: no cover text = six.text_type(text.encode('utf-8').translate(string.maketrans("", ""), string.punctuation).lower(), 'utf-8') else: text = text.translate(string.maketrans("", ""), string.punctuation).lower() return " ".join(text.split())
def simplify_text(text)
Simplify text to allow comparison. >>> simplify_text("Awesome Coder wanted at Awesome Company") 'awesome coder wanted at awesome company' >>> simplify_text("Awesome Coder, wanted at Awesome Company! ") 'awesome coder wanted at awesome company' >>> simplify_text(u"Awesome Coder, wanted at Awesome Company! ") == 'awesome coder wanted at awesome company' True
2.385149
2.495042
0.955956
sentences = [] for text in text_blocks: sentences.extend(nltk.sent_tokenize(text)) tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences] tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences] chunked_sentences = nltk.ne_chunk_sents(tagged_sentences, binary=True) def extract_entity_names(t): entity_names = [] if hasattr(t, 'label'): if t.label() == 'NE': entity_names.append(' '.join([child[0] for child in t])) else: for child in t: entity_names.extend(extract_entity_names(child)) return entity_names entity_names = [] for tree in chunked_sentences: entity_names.extend(extract_entity_names(tree)) return set(entity_names)
def extract_named_entities(text_blocks)
Return a list of named entities extracted from provided text blocks (list of text strings).
1.617779
1.612203
1.003459
config = Config() try: config.set_main_option("script_location", path or "migrations") script = ScriptDirectory.from_config(config) head = script.get_current_head() # create alembic table metadata, alembic_version = alembic_table_metadata() metadata.create_all() item = manager.db.session.query(alembic_version).first() if item and item.version_num != head: item.version_num = head else: item = alembic_version.insert().values(version_num=head) item.compile() conn = manager.db.engine.connect() conn.execute(item) manager.db.session.commit() stdout.write("alembic head is set to %s \n" % head) except CommandError as e: stdout.write(e.message)
def set_alembic_revision(path=None)
Create/Update alembic table to latest revision number
2.849393
2.801376
1.01714
manager.db.engine.echo = True if prompt_bool("Are you sure you want to lose all your data"): manager.db.drop_all() metadata, alembic_version = alembic_table_metadata() alembic_version.drop() manager.db.session.commit()
def dropdb()
Drop database tables
5.545073
5.710923
0.970959
manager.db.engine.echo = True manager.db.create_all() set_alembic_revision()
def createdb()
Create database tables from sqlalchemy models
7.480009
7.322297
1.021539
print("Syncing resources with Lastuser...") resources = manager.app.lastuser.sync_resources()['results'] for rname, resource in six.iteritems(resources): if resource['status'] == 'error': print("Error for %s: %s" % (rname, resource['error'])) else: print("Resource %s %s..." % (rname, resource['status'])) for aname, action in six.iteritems(resource['actions']): if action['status'] == 'error': print("\tError for %s/%s: %s" % (rname, aname, action['error'])) else: print("\tAction %s/%s %s..." % (rname, aname, resource['status'])) print("Resources synced...")
def sync_resources()
Sync the client's resources with the Lastuser server
2.883702
2.620923
1.100262
manager.app = app manager.db = db manager.context = kwargs manager.add_command('db', MigrateCommand) manager.add_command('clean', Clean()) manager.add_command('showurls', ShowUrls()) manager.add_command('shell', Shell(make_context=shell_context)) manager.add_command('plainshell', Shell(make_context=shell_context, use_ipython=False, use_bpython=False)) return manager
def init_manager(app, db, **kwargs)
Initialise Manager :param app: Flask app object :parm db: db instance :param kwargs: Additional keyword arguments to be made available as shell context
2.951478
3.483786
0.847204
# Make current_auth available to app templates app.jinja_env.globals['current_auth'] = current_auth # Make the current view available to app templates app.jinja_env.globals['current_view'] = current_view # Disable Flask-SQLAlchemy events. # Apps that want it can turn it back on in their config app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', False) # Load config from the app's settings.py load_config_from_file(app, 'settings.py') # Load additional settings from the app's environment-specific config file if not env: env = environ.get('FLASK_ENV', 'DEVELOPMENT') # Uppercase for compatibility with Flask-Environments additional = _additional_config.get(env.lower()) # Lowercase because that's how we define it if additional: load_config_from_file(app, additional) logger.init_app(app)
def init_app(app, env=None)
Configure an app depending on the environment. Loads settings from a file named ``settings.py`` in the instance folder, followed by additional settings from one of ``development.py``, ``production.py`` or ``testing.py``. Typical usage:: from flask import Flask import coaster.app app = Flask(__name__, instance_relative_config=True) coaster.app.init_app(app) # Guess environment automatically :func:`init_app` also configures logging by calling :func:`coaster.logger.init_app`. :param app: App to be configured :param env: Environment to configure for (``'development'``, ``'production'`` or ``'testing'``). If not specified, the ``FLASK_ENV`` environment variable is consulted. Defaults to ``'development'``.
4.446163
4.316846
1.029956
try: app.config.from_pyfile(filepath) return True except IOError: # TODO: Can we print to sys.stderr in production? Should this go to # logs instead? print("Did not find settings file %s for additional settings, skipping it" % filepath, file=sys.stderr) return False
def load_config_from_file(app, filepath)
Helper function to load config from a specified file
6.769448
6.982987
0.96942
options = dict(self.jinja_options) if 'autoescape' not in options: options['autoescape'] = self.select_jinja_autoescape rv = SandboxedEnvironment(self, **options) rv.globals.update( url_for=url_for, get_flashed_messages=get_flashed_messages, config=self.config, # FIXME: Sandboxed templates shouldn't access full config # request, session and g are normally added with the # context processor for efficiency reasons but for imported # templates we also want the proxies in there. request=request, session=session, g=g # FIXME: Similarly with g: no access for sandboxed templates ) rv.filters['tojson'] = _tojson_filter return rv
def create_jinja_environment(self)
Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`select_jinja_autoescape`. Since 0.7 this also adds the Jinja2 globals and filters after initialization. Override this function to customize the behavior.
7.131316
6.117064
1.165807
if cls.__uuid_primary_key__: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, primary_key=True, nullable=False)) else: return immutable(Column(Integer, primary_key=True, nullable=False))
def id(cls)
Database identity for this model, used for foreign key references from other models
4.869601
4.07018
1.196409
if cls.__uuid_primary_key__: def url_id_func(self): return self.id.hex def url_id_is(cls): return SqlHexUuidComparator(cls.id) url_id_func.__name__ = 'url_id' url_id_property = hybrid_property(url_id_func) url_id_property = url_id_property.comparator(url_id_is) return url_id_property else: def url_id_func(self): return six.text_type(self.id) def url_id_expression(cls): return cls.id url_id_func.__name__ = 'url_id' url_id_property = hybrid_property(url_id_func) url_id_property = url_id_property.expression(url_id_expression) return url_id_property
def url_id(cls)
The URL id
2.655386
2.690797
0.98684
if hasattr(cls, '__uuid_primary_key__') and cls.__uuid_primary_key__: return synonym('id') else: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, unique=True, nullable=False))
def uuid(cls)
UUID column, or synonym to existing :attr:`id` column if that is a UUID
5.488538
4.365532
1.257244
app = current_app._get_current_object() if current_app else None if app is not None and action in self.url_for_endpoints.get(app, {}): endpoint, paramattrs, _external = self.url_for_endpoints[app][action] else: try: endpoint, paramattrs, _external = self.url_for_endpoints[None][action] except KeyError: raise BuildError(action, kwargs, 'GET') params = {} for param, attr in list(paramattrs.items()): if isinstance(attr, tuple): # attr is a tuple containing: # 1. ('parent', 'name') --> self.parent.name # 2. ('**entity', 'name') --> kwargs['entity'].name if attr[0].startswith('**'): item = kwargs.pop(attr[0][2:]) attr = attr[1:] else: item = self for subattr in attr: item = getattr(item, subattr) params[param] = item elif callable(attr): params[param] = attr(self) else: params[param] = getattr(self, attr) if _external is not None: params['_external'] = _external params.update(kwargs) # Let kwargs override params # url_for from flask return url_for(endpoint, **params)
def url_for(self, action='view', **kwargs)
Return public URL to this instance for a given action (default 'view')
3.108453
3.08979
1.00604
def decorator(f): if 'url_for_endpoints' not in cls.__dict__: cls.url_for_endpoints = {None: {}} # Stick it into the class with the first endpoint cls.url_for_endpoints.setdefault(_app, {}) for keyword in paramattrs: if isinstance(paramattrs[keyword], six.string_types) and '.' in paramattrs[keyword]: paramattrs[keyword] = tuple(paramattrs[keyword].split('.')) cls.url_for_endpoints[_app][_action] = _endpoint or f.__name__, paramattrs, _external return f return decorator
def is_url_for(cls, _action, _endpoint=None, _app=None, _external=None, **paramattrs)
View decorator that registers the view as a :meth:`url_for` target.
3.201713
3.132145
1.022211
if 'view_for_endpoints' not in cls.__dict__: cls.view_for_endpoints = {} cls.view_for_endpoints.setdefault(app, {})[action] = (classview, attr)
def register_view_for(cls, app, action, classview, attr)
Register a classview and viewhandler for a given app and action
2.563018
2.608813
0.982446
app = current_app._get_current_object() view, attr = self.view_for_endpoints[app][action] return getattr(view(self), attr)
def view_for(self, action='view')
Return the classview viewhandler that handles the specified action
6.676606
6.248316
1.068545
app = current_app._get_current_object() return self.view_for_endpoints[app][action][0](self)
def classview_for(self, action='view')
Return the classview that contains the viewhandler for the specified action
9.392295
8.327181
1.127908
for f in fields: if hasattr(self, f): setattr(self, f, fields[f]) else: raise TypeError("'{arg}' is an invalid argument for {instance_type}".format(arg=f, instance_type=self.__class__.__name__))
def _set_fields(self, fields)
Helper method for :meth:`upsert` in the various subclasses
3.184088
3.000539
1.061172
if cls.__name_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__name_length__) if cls.__name_blank_allowed__: return Column(column_type, nullable=False, unique=True) else: return Column(column_type, CheckConstraint("name <> ''"), nullable=False, unique=True)
def name(cls)
The URL name of this object, unique across all instances of this model
3.706893
3.480841
1.064942
if cls.__title_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__title_length__) return Column(column_type, nullable=False)
def title(cls)
The title of this object
4.853666
5.12363
0.94731
instance = cls.get(name) if instance: instance._set_fields(fields) else: instance = cls(name=name, **fields) instance = failsafe_add(cls.query.session, instance, name=name) return instance
def upsert(cls, name, **fields)
Insert or update an instance
4.433874
4.282513
1.035344
if self.title: if inspect(self).has_identity: def checkused(c): return bool(c in reserved or c in self.reserved_names or self.__class__.query.filter(self.__class__.id != self.id).filter_by(name=c).notempty()) else: def checkused(c): return bool(c in reserved or c in self.reserved_names or self.__class__.query.filter_by(name=c).notempty()) with self.__class__.query.session.no_autoflush: self.name = six.text_type(make_name(self.title_for_name, maxlength=self.__name_length__, checkused=checkused))
def make_name(self, reserved=[])
Autogenerates a :attr:`name` from the :attr:`title`. If the auto-generated name is already in use in this model, :meth:`make_name` tries again by suffixing numbers starting with 2 until an available name is found. :param reserved: List or set of reserved names unavailable for use
4.113009
4.1867
0.982399
return cls.query.filter_by(parent=parent, name=name).one_or_none()
def get(cls, parent, name)
Get an instance matching the parent and name
2.865816
2.70541
1.059291
if self.title and self.parent is not None and hasattr(self.parent, 'title') and self.parent.title: if self.title.startswith(self.parent.title): short = self.title[len(self.parent.title):].strip() match = _punctuation_re.match(short) if match: short = short[match.end():].strip() if short: return short return self.title
def short_title(self)
Generates an abbreviated title by subtracting the parent's title from this instance's title.
2.638506
2.359515
1.118241
if inherited is not None: return inherited | super(BaseScopedNameMixin, self).permissions(actor) elif self.parent is not None and isinstance(self.parent, PermissionMixin): return self.parent.permissions(actor) | super(BaseScopedNameMixin, self).permissions(actor) else: return super(BaseScopedNameMixin, self).permissions(actor)
def permissions(self, actor, inherited=None)
Permissions for this model, plus permissions inherited from the parent.
2.686325
2.393143
1.122509
if self.title: self.name = six.text_type(make_name(self.title_for_name, maxlength=self.__name_length__))
def make_name(self)
Autogenerates a :attr:`name` from :attr:`title_for_name`
11.419167
5.828464
1.959207
return cls.query.filter_by(parent=parent, url_id=url_id).one_or_none()
def get(cls, parent, url_id)
Get an instance matching the parent and url_id
2.346487
2.076021
1.130281
if self.url_id is None: # Set id only if empty self.url_id = select([func.coalesce(func.max(self.__class__.url_id + 1), 1)], self.__class__.parent == self.parent)
def make_id(self)
Create a new URL id that is unique to the parent container
7.639987
5.549291
1.37675
return ( Column('created_at', DateTime, default=func.utcnow(), nullable=False), Column('updated_at', DateTime, default=func.utcnow(), onupdate=func.utcnow(), nullable=False), )
def make_timestamp_columns()
Return two columns, created_at and updated_at, with appropriate defaults
2.201124
1.729359
1.272798
if _instance in _session: # This instance is already in the session, most likely due to a # save-update cascade. SQLAlchemy will flush before beginning a # nested transaction, which defeats the purpose of nesting, so # remove it for now and add it back inside the SAVEPOINT. _session.expunge(_instance) _session.begin_nested() try: _session.add(_instance) _session.commit() if filters: return _instance except IntegrityError as e: _session.rollback() if filters: try: return _session.query(_instance.__class__).filter_by(**filters).one() except NoResultFound: # Do not trap the other exception, MultipleResultsFound raise e
def failsafe_add(_session, _instance, **filters)
Add and commit a new instance in a nested transaction (using SQL SAVEPOINT), gracefully handling failure in case a conflicting entry is already in the database (which may occur due to parallel requests causing race conditions in a production environment with multiple workers). Returns the instance saved to database if no error occurred, or loaded from database using the provided filters if an error occurred. If the filters fail to load from the database, the original IntegrityError is re-raised, as it is assumed to imply that the commit failed because of missing or invalid data, not because of a duplicate entry. However, when no filters are provided, nothing is returned and IntegrityError is also suppressed as there is no way to distinguish between data validation failure and an existing conflicting record in the database. Use this option when failures are acceptable but the cost of verification is not. Usage: ``failsafe_add(db.session, instance, **filters)`` where filters are the parameters passed to ``Model.query.filter_by(**filters).one()`` to load the instance. You must commit the transaction as usual after calling ``failsafe_add``. :param _session: Database session :param _instance: Instance to commit :param filters: Filters required to load existing instance from the database in case the commit fails (required) :return: Instance that is in the database
5.223291
5.182709
1.00783
if isinstance(column, ColumnProperty): default = column.columns[0].default else: default = column.default @event.listens_for(column, 'init_scalar', retval=True, propagate=True) def init_scalar(target, value, dict_): # A subclass may override the column and not provide a default. Watch out for that. if default: if default.is_callable: value = default.arg(None) elif default.is_scalar: value = default.arg else: raise NotImplementedError("Can't invoke pre-default for a SQL-level column default") dict_[column.key] = value return value
def auto_init_default(column)
Set the default value for a column when it's first accessed rather than first committed to the database.
5.314609
5.197159
1.022599
if config and list(config.keys()) != ['source']: raise TypeError("Unrecognised parameters: %s" % repr(config.keys())) def inner(f): namefilt = [(name[:-2], filt, True) if name.endswith('[]') else (name, filt, False) for name, filt in [(v[0], v[1]) if isinstance(v, (list, tuple)) else (v, None) for v in vars]] if config and config.get('source') == 'form': def datasource(): return request.form if request else {} elif config and config.get('source') == 'query': def datasource(): return request.args if request else {} else: def datasource(): return request.values if request else {} @wraps(f) def decorated_function(*args, **kw): values = datasource() for name, filt, is_list in namefilt: # Process name if # (a) it's not in the function's parameters, and # (b) is in the form/query if name not in kw and name in values: try: if is_list: kw[name] = values.getlist(name, type=filt) else: kw[name] = values.get(name, type=filt) except ValueError as e: raise RequestValueError(e) try: return f(*args, **kw) except TypeError as e: raise RequestTypeError(e) return decorated_function return inner
def requestargs(*vars, **config)
Decorator that loads parameters from request.values if not specified in the function's keyword arguments. Usage:: @requestargs('param1', ('param2', int), 'param3[]', ...) def function(param1, param2=0, param3=None): ... requestargs takes a list of parameters to pass to the wrapped function, with an optional filter (useful to convert incoming string request data into integers and other common types). If a required parameter is missing and your function does not specify a default value, Python will raise TypeError. requestargs recasts this as :exc:`RequestTypeError`, which returns HTTP 400 Bad Request. If the parameter name ends in ``[]``, requestargs will attempt to read a list from the incoming data. Filters are applied to each member of the list, not to the whole list. If the filter raises a ValueError, this is recast as a :exc:`RequestValueError`, which also returns HTTP 400 Bad Request. Tests:: >>> from flask import Flask >>> app = Flask(__name__) >>> >>> @requestargs('p1', ('p2', int), ('p3[]', int)) ... def f(p1, p2=None, p3=None): ... return p1, p2, p3 ... >>> f(p1=1) (1, None, None) >>> f(p1=1, p2=2) (1, 2, None) >>> f(p1='a', p2='b') ('a', 'b', None) >>> with app.test_request_context('/?p2=2'): ... f(p1='1') ... ('1', 2, None) >>> with app.test_request_context('/?p3=1&p3=2'): ... f(p1='1', p2='2') ... ('1', '2', [1, 2]) >>> with app.test_request_context('/?p2=100&p3=1&p3=2'): ... f(p1='1', p2=200) ... ('1', 200, [1, 2])
2.88035
2.978963
0.966897
return load_models((model, attributes, parameter), kwargs=kwargs, permission=permission, addlperms=addlperms, urlcheck=urlcheck)
def load_model(model, attributes=None, parameter=None, kwargs=False, permission=None, addlperms=None, urlcheck=[])
Decorator to load a model given a query parameter. Typical usage:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profileob') def profile_view(profileob): # 'profileob' is now a Profile model instance. The load_model decorator replaced this: # profileob = Profile.query.filter_by(name=profile).first_or_404() return "Hello, %s" % profileob.name Using the same name for request and parameter makes code easier to understand:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profile') def profile_view(profile): return "Hello, %s" % profile.name ``load_model`` aborts with a 404 if no instance is found. :param model: The SQLAlchemy model to query. Must contain a ``query`` object (which is the default with Flask-SQLAlchemy) :param attributes: A dict of attributes (from the URL request) that will be used to query for the object. For each key:value pair, the key is the name of the column on the model and the value is the name of the request parameter that contains the data :param parameter: The name of the parameter to the decorated function via which the result is passed. Usually the same as the attribute. If the parameter name is prefixed with 'g.', the parameter is also made available as g.<parameter> :param kwargs: If True, the original request parameters are passed to the decorated function as a ``kwargs`` parameter :param permission: If present, ``load_model`` calls the :meth:`~coaster.sqlalchemy.PermissionMixin.permissions` method of the retrieved object with ``current_auth.actor`` as a parameter. If ``permission`` is not present in the result, ``load_model`` aborts with a 403. The permission may be a string or a list of strings, in which case access is allowed if any of the listed permissions are available :param addlperms: Iterable or callable that returns an iterable containing additional permissions available to the user, apart from those granted by the models. In an app that uses Lastuser for authentication, passing ``lastuser.permissions`` will pass through permissions granted via Lastuser :param list urlcheck: If an attribute in this list has been used to load an object, but the value of the attribute in the loaded object does not match the request argument, issue a redirect to the corrected URL. This is useful for attributes like ``url_id_name`` and ``url_name_suuid`` where the ``name`` component may change
2.962371
5.869337
0.50472
if not isinstance(param, dict): param = dict(param) return jsonify(param)
def dict_jsonify(param)
Convert the parameter into a dictionary before calling jsonify, if it's not already one
3.672094
2.288848
1.604341
if not isinstance(param, dict): param = dict(param) return jsonp(param)
def dict_jsonp(param)
Convert the parameter into a dictionary before calling jsonp, if it's not already one
3.614106
2.752073
1.31323
def inner(f): @wraps(f) def wrapper(*args, **kwargs): origin = request.headers.get('Origin') if request.method not in methods: abort(405) if origins == '*': pass elif is_collection(origins) and origin in origins: pass elif callable(origins) and origins(origin): pass else: abort(403) if request.method == 'OPTIONS': # pre-flight request resp = Response() else: result = f(*args, **kwargs) resp = make_response(result) if not isinstance(result, (Response, WerkzeugResponse, current_app.response_class)) else result resp.headers['Access-Control-Allow-Origin'] = origin if origin else '' resp.headers['Access-Control-Allow-Methods'] = ', '.join(methods) resp.headers['Access-Control-Allow-Headers'] = ', '.join(headers) if max_age: resp.headers['Access-Control-Max-Age'] = str(max_age) # Add 'Origin' to the Vary header since response will vary by origin if 'Vary' in resp.headers: vary_values = [item.strip() for item in resp.headers['Vary'].split(',')] if 'Origin' not in vary_values: vary_values.append('Origin') resp.headers['Vary'] = ', '.join(vary_values) else: resp.headers['Vary'] = 'Origin' return resp return wrapper return inner
def cors(origins, methods=['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'], headers=['Accept', 'Accept-Language', 'Content-Language', 'Content-Type', 'X-Requested-With'], max_age=None)
Adds CORS headers to the decorated view function. :param origins: Allowed origins (see below) :param methods: A list of allowed HTTP methods :param headers: A list of allowed HTTP headers :param max_age: Duration in seconds for which the CORS response may be cached The :obj:`origins` parameter may be one of: 1. A callable that receives the origin as a parameter. 2. A list of origins. 3. ``*``, indicating that this resource is accessible by any origin. Example use:: from flask import Flask, Response from coaster.views import cors app = Flask(__name__) @app.route('/any') @cors('*') def any_origin(): return Response() @app.route('/static', methods=['GET', 'POST']) @cors(['https://hasgeek.com'], methods=['GET'], headers=['Content-Type', 'X-Requested-With'], max_age=3600) def static_list(): return Response() def check_origin(origin): # check if origin should be allowed return True @app.route('/callable') @cors(check_origin) def callable_function(): return Response()
2.03099
2.046797
0.992277
def inner(f): def is_available_here(): if not hasattr(current_auth, 'permissions'): return False elif is_collection(permission): return bool(current_auth.permissions.intersection(permission)) else: return permission in current_auth.permissions def is_available(context=None): result = is_available_here() if result and hasattr(f, 'is_available'): # We passed, but we're wrapping another test, so ask there as well return f.is_available(context) return result @wraps(f) def wrapper(*args, **kwargs): add_auth_attribute('login_required', True) if not is_available_here(): abort(403) return f(*args, **kwargs) wrapper.requires_permission = permission wrapper.is_available = is_available return wrapper return inner
def requires_permission(permission)
View decorator that requires a certain permission to be present in ``current_auth.permissions`` before the view is allowed to proceed. Aborts with ``403 Forbidden`` if the permission is not present. The decorated view will have an ``is_available`` method that can be called to perform the same test. :param permission: Permission that is required. If a collection type is provided, any one permission must be available
3.499117
3.359447
1.041575
return not isinstance(item, six.string_types) and isinstance(item, (collections.Set, collections.Sequence))
def is_collection(item)
Returns True if the item is a collection class: list, tuple, set, frozenset or any other class that resembles one of these (using abstract base classes). >>> is_collection(0) False >>> is_collection(0.1) False >>> is_collection('') False >>> is_collection({}) False >>> is_collection({}.keys()) True >>> is_collection([]) True >>> is_collection(()) True >>> is_collection(set()) True >>> is_collection(frozenset()) True >>> from coaster.utils import InspectableSet >>> is_collection(InspectableSet({1, 2})) True
4.486109
7.141439
0.62818
if six.PY3: # pragma: no cover return urlsafe_b64encode(uuid.uuid4().bytes).decode('utf-8').rstrip('=') else: # pragma: no cover return six.text_type(urlsafe_b64encode(uuid.uuid4().bytes).rstrip('='))
def buid()
Return a new random id that is exactly 22 characters long, by encoding a UUID4 in URL-safe Base64. See http://en.wikipedia.org/wiki/Base64#Variants_summary_table >>> len(buid()) 22 >>> buid() == buid() False >>> isinstance(buid(), six.text_type) True
2.398249
2.263492
1.059535
fields = list(uuid1mc().fields) if isinstance(dt, datetime): timeval = time.mktime(dt.timetuple()) + dt.microsecond / 1e6 else: # Assume we got an actual timestamp timeval = dt # The following code is borrowed from the UUID module source: nanoseconds = int(timeval * 1e9) # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. timestamp = int(nanoseconds // 100) + 0x01b21dd213814000 time_low = timestamp & 0xffffffff time_mid = (timestamp >> 32) & 0xffff time_hi_version = (timestamp >> 48) & 0x0fff fields[0] = time_low fields[1] = time_mid fields[2] = time_hi_version return uuid.UUID(fields=tuple(fields))
def uuid1mc_from_datetime(dt)
Return a UUID1 with a random multicast MAC id and with a timestamp matching the given datetime object or timestamp value. .. warning:: This function does not consider the timezone, and is not guaranteed to return a unique UUID. Use under controlled conditions only. >>> dt = datetime.now() >>> u1 = uuid1mc() >>> u2 = uuid1mc_from_datetime(dt) >>> # Both timestamps should be very close to each other but not an exact match >>> u1.time > u2.time True >>> u1.time - u2.time < 5000 True >>> d2 = datetime.fromtimestamp((u2.time - 0x01b21dd213814000) * 100 / 1e9) >>> d2 == dt True
2.117967
2.291817
0.924143
if six.PY3: # pragma: no cover return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=') else: return six.text_type(urlsafe_b64encode(value.bytes).rstrip('='))
def uuid2buid(value)
Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ'
2.639111
3.202799
0.824001
randnum = randint(0, 10 ** digits) while len(str(randnum)) > digits: randnum = randint(0, 10 ** digits) return (u'%%0%dd' % digits) % randnum
def newpin(digits=4)
Return a random numeric string with the specified number of digits, default 4. >>> len(newpin()) 4 >>> len(newpin(5)) 5 >>> newpin().isdigit() True
2.952576
3.655383
0.807734
if encoding not in ['PLAIN', 'SSHA', 'BCRYPT']: raise ValueError("Unknown encoding %s" % encoding) if encoding == 'PLAIN': if isinstance(password, str) and six.PY2: password = six.text_type(password, 'utf-8') return '{PLAIN}%s' % password elif encoding == 'SSHA': # SSHA is a modification of the SHA digest scheme with a salt # starting at byte 20 of the base64-encoded string. # Source: http://developer.netscape.com/docs/technote/ldap/pass_sha.html # This implementation is from Zope2's AccessControl.AuthEncoding. salt = '' for n in range(7): salt += chr(randrange(256)) # b64encode accepts only bytes in Python 3, so salt also has to be encoded salt = salt.encode('utf-8') if six.PY3 else salt if isinstance(password, six.text_type): password = password.encode('utf-8') else: password = str(password) b64_encoded = b64encode(hashlib.sha1(password + salt).digest() + salt) b64_encoded = b64_encoded.decode('utf-8') if six.PY3 else b64_encoded return '{SSHA}%s' % b64_encoded elif encoding == 'BCRYPT': # BCRYPT is the recommended hash for secure passwords password_hashed = bcrypt.hashpw( password.encode('utf-8') if isinstance(password, six.text_type) else password, bcrypt.gensalt()) if six.PY3: # pragma: no cover password_hashed = password_hashed.decode('utf-8') return '{BCRYPT}%s' % password_hashed
def make_password(password, encoding='BCRYPT')
Make a password with PLAIN, SSHA or BCRYPT (default) encoding. >>> make_password('foo', encoding='PLAIN') '{PLAIN}foo' >>> make_password(u're-foo', encoding='SSHA')[:6] '{SSHA}' >>> make_password(u're-foo')[:8] '{BCRYPT}' >>> make_password('foo') == make_password('foo') False
3.002518
2.891279
1.038474
if reference.startswith(u'{PLAIN}'): if reference[7:] == attempt: return True elif reference.startswith(u'{SSHA}'): # In python3 b64decode takes inputtype as bytes as opposed to str in python 2, and returns # binascii.Error as opposed to TypeError if six.PY3: # pragma: no cover try: if isinstance(reference, six.text_type): ref = b64decode(reference[6:].encode('utf-8')) else: ref = b64decode(reference[6:]) except binascii.Error: return False # Not Base64 else: # pragma: no cover try: ref = b64decode(reference[6:]) except TypeError: return False # Not Base64 if isinstance(attempt, six.text_type): attempt = attempt.encode('utf-8') salt = ref[20:] b64_encoded = b64encode(hashlib.sha1(attempt + salt).digest() + salt) if six.PY3: # pragma: no cover # type(b64_encoded) is bytes and can't be compared with type(reference) which is str compare = six.text_type('{SSHA}%s' % b64_encoded.decode('utf-8') if type(b64_encoded) is bytes else b64_encoded) else: # pragma: no cover compare = six.text_type('{SSHA}%s' % b64_encoded) return compare == reference elif reference.startswith(u'{BCRYPT}'): # bcrypt.hashpw() accepts either a unicode encoded string or the basic string (python 2) if isinstance(attempt, six.text_type) or isinstance(reference, six.text_type): attempt = attempt.encode('utf-8') reference = reference.encode('utf-8') if six.PY3: # pragma: no cover return bcrypt.hashpw(attempt, reference[8:]) == reference[8:] else: # pragma: no cover return bcrypt.hashpw( attempt.encode('utf-8') if isinstance(attempt, six.text_type) else attempt, str(reference[8:])) == reference[8:] return False
def check_password(reference, attempt)
Compare a reference password with the user attempt. >>> check_password('{PLAIN}foo', 'foo') True >>> check_password(u'{PLAIN}bar', 'bar') True >>> check_password(u'{UNKNOWN}baz', 'baz') False >>> check_password(u'no-encoding', u'no-encoding') False >>> check_password(u'{SSHA}q/uVU8r15k/9QhRi92CWUwMJu2DM6TUSpp25', u're-foo') True >>> check_password(u'{BCRYPT}$2b$12$NfKivgz7njR3/rWZ56EsDe7..PPum.fcmFLbdkbP.chtMTcS1s01C', 'foo') True
2.550243
2.477404
1.029401
number, decimal = ((u'%%.%df' % decimals) % value).split(u'.') parts = [] while len(number) > 3: part, number = number[-3:], number[:-3] parts.append(part) parts.append(number) parts.reverse() if int(decimal) == 0: return u','.join(parts) else: return u','.join(parts) + u'.' + decimal
def format_currency(value, decimals=2)
Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points. >>> format_currency(1000) '1,000' >>> format_currency(100) '100' >>> format_currency(999.95) '999.95' >>> format_currency(99.95) '99.95' >>> format_currency(100000) '100,000' >>> format_currency(1000.00) '1,000' >>> format_currency(1000.41) '1,000.41' >>> format_currency(23.21, decimals=3) '23.210' >>> format_currency(1000, decimals=3) '1,000' >>> format_currency(123456789.123456789) '123,456,789.12'
2.428779
2.819771
0.861339
if six.PY3: # pragma: no cover return hashlib.md5(data.encode('utf-8')).hexdigest() else: # pragma: no cover return hashlib.md5(data).hexdigest()
def md5sum(data)
Return md5sum of data as a 32-character string. >>> md5sum('random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> md5sum(u'random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> len(md5sum('random text')) 32
1.926434
2.54655
0.756488
naivedt = datetime.combine(isoweek.Week(year, week).day(0), datetime.min.time()) if isinstance(timezone, six.string_types): tz = pytz.timezone(timezone) else: tz = timezone dt = tz.localize(naivedt).astimezone(pytz.UTC) if naive: return dt.replace(tzinfo=None) else: return dt
def isoweek_datetime(year, week, timezone='UTC', naive=False)
Returns a datetime matching the starting point of a specified ISO week in the specified timezone (default UTC). Returns a naive datetime in UTC if requested (default False). >>> isoweek_datetime(2017, 1) datetime.datetime(2017, 1, 2, 0, 0, tzinfo=<UTC>) >>> isoweek_datetime(2017, 1, 'Asia/Kolkata') datetime.datetime(2017, 1, 1, 18, 30, tzinfo=<UTC>) >>> isoweek_datetime(2017, 1, 'Asia/Kolkata', naive=True) datetime.datetime(2017, 1, 1, 18, 30) >>> isoweek_datetime(2008, 1, 'Asia/Kolkata') datetime.datetime(2007, 12, 30, 18, 30, tzinfo=<UTC>)
2.334225
3.416525
0.683216
if timezone: if isinstance(timezone, six.string_types): tz = pytz.timezone(timezone) else: tz = timezone elif isinstance(dt, datetime) and dt.tzinfo: tz = dt.tzinfo else: tz = pytz.UTC utc_dt = tz.localize(datetime.combine(dt, datetime.min.time())).astimezone(pytz.UTC) if naive: return utc_dt.replace(tzinfo=None) return utc_dt
def midnight_to_utc(dt, timezone=None, naive=False)
Returns a UTC datetime matching the midnight for the given date or datetime. >>> from datetime import date >>> midnight_to_utc(datetime(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1))) datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(datetime(2017, 1, 1), naive=True) datetime.datetime(2017, 1, 1, 0, 0) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)), naive=True) datetime.datetime(2016, 12, 31, 18, 30) >>> midnight_to_utc(date(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(date(2017, 1, 1), naive=True) datetime.datetime(2017, 1, 1, 0, 0) >>> midnight_to_utc(date(2017, 1, 1), timezone='Asia/Kolkata') datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(datetime(2017, 1, 1), timezone='Asia/Kolkata') datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)), timezone='UTC') datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>)
1.739809
2.211954
0.786549
value = str(value).lower() if value in ['1', 't', 'true', 'y', 'yes']: return True elif value in ['0', 'f', 'false', 'n', 'no']: return False return None
def getbool(value)
Returns a boolean from any of a range of values. Returns None for unrecognized values. Numbers other than 0 and 1 are considered unrecognized. >>> getbool(True) True >>> getbool(1) True >>> getbool('1') True >>> getbool('t') True >>> getbool(2) >>> getbool(0) False >>> getbool(False) False >>> getbool('n') False
1.87451
2.349326
0.797893
# Two ways to count number of non-None parameters: # # 1. sum([1 if v is not None else 0 for v in kwargs.values()]) # # Using a list comprehension instead of a generator comprehension as the # parameter to `sum` is faster on both Python 2 and 3. # # 2. len(kwargs) - kwargs.values().count(None) # # This is 2x faster than the first method under Python 2.7. Unfortunately, # it doesn't work in Python 3 because `kwargs.values()` is a view that doesn't # have a `count` method. It needs to be cast into a tuple/list first, but # remains faster despite the cast's slowdown. Tuples are faster than lists. if six.PY3: # pragma: no cover count = len(kwargs) - tuple(kwargs.values()).count(None) else: # pragma: no cover count = len(kwargs) - kwargs.values().count(None) if count == 0: raise TypeError("One of these parameters is required: " + ', '.join(kwargs.keys())) elif count != 1: raise TypeError("Only one of these parameters is allowed: " + ', '.join(kwargs.keys())) if _return: keys, values = zip(*[(k, 1 if v is not None else 0) for k, v in kwargs.items()]) k = keys[values.index(1)] return k, kwargs[k]
def require_one_of(_return=False, **kwargs)
Validator that raises :exc:`TypeError` unless one and only one parameter is not ``None``. Use this inside functions that take multiple parameters, but allow only one of them to be specified:: def my_func(this=None, that=None, other=None): # Require one and only one of `this` or `that` require_one_of(this=this, that=that) # If we need to know which parameter was passed in: param, value = require_one_of(True, this=this, that=that) # Carry on with function logic pass :param _return: Return the matching parameter :param kwargs: Parameters, of which one and only one is mandatory :return: If `_return`, matching parameter name and value :rtype: tuple :raises TypeError: If the count of parameters that aren't ``None`` is not 1
3.756746
3.684079
1.019725
r if six.PY3: # pragma: no cover # email.header.decode_header expects strings, not bytes. Your input data may be in bytes. # Since these bytes are almost always ASCII, calling `.decode()` on it without specifying # a charset should work fine. if isinstance(value, six.binary_type): value = value.decode() return u''.join([six.text_type(s, e or 'iso-8859-1') if not isinstance(s, six.text_type) else s for s, e in decode_header(value)])
def unicode_http_header(value)
r""" Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied. Expects headers to be RFC 2047 compliant. >>> unicode_http_header('=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header(b'=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header('p\xf6stal') == u'p\xf6stal' True
6.021856
6.225986
0.967213
realname, address = email.utils.parseaddr(emailaddr) try: username, domain = address.split('@') if not username: return None return domain or None except ValueError: return None
def get_email_domain(emailaddr)
Return the domain component of an email address. Returns None if the provided string cannot be parsed as an email address. >>> get_email_domain('test@example.com') 'example.com' >>> get_email_domain('test+trailing@example.com') 'example.com' >>> get_email_domain('Example Address <test@example.com>') 'example.com' >>> get_email_domain('foobar') >>> get_email_domain('foo@bar@baz') 'bar' >>> get_email_domain('foobar@') >>> get_email_domain('@foobar')
3.915631
5.261959
0.744139
def hourmin(delta): if delta.days < 0: hours, remaining = divmod(86400 - delta.seconds, 3600) else: hours, remaining = divmod(delta.seconds, 3600) minutes, remaining = divmod(remaining, 60) return hours, minutes now = datetime.utcnow() # Make a list of country code mappings timezone_country = {} for countrycode in pytz.country_timezones: for timezone in pytz.country_timezones[countrycode]: timezone_country[timezone] = countrycode # Make a list of timezones, discarding the US/* and Canada/* zones since they aren't reliable for # DST, and discarding UTC and GMT since timezones in that zone have their own names timezones = [(pytz.timezone(tzname).utcoffset(now, is_dst=False), tzname) for tzname in pytz.common_timezones if not tzname.startswith('US/') and not tzname.startswith('Canada/') and tzname not in ('GMT', 'UTC')] # Sort timezones by offset from UTC and their human-readable name presorted = [(delta, '%s%s - %s%s (%s)' % ( (delta.days < 0 and '-') or (delta.days == 0 and delta.seconds == 0 and ' ') or '+', '%02d:%02d' % hourmin(delta), (pytz.country_names[timezone_country[name]] + ': ') if name in timezone_country else '', name.replace('_', ' '), pytz.timezone(name).tzname(now, is_dst=False)), name) for delta, name in timezones] presorted.sort() # Return a list of (timezone, label) with the timezone offset included in the label. return [(name, label) for (delta, label, name) in presorted]
def sorted_timezones()
Return a list of timezones sorted by offset from UTC.
3.227013
3.128444
1.031507
parsed = urlparse(url) if parsed.hostname is None or parsed.hostname in ['localhost', 'localhost.localdomain'] or ( _ipv4_re.search(parsed.hostname)): return None namespace = parsed.hostname.split('.') namespace.reverse() if namespace and not namespace[0]: namespace.pop(0) if namespace and namespace[-1] == 'www': namespace.pop(-1) return type(url)('.'.join(namespace))
def namespace_from_url(url)
Construct a dotted namespace string from a URL.
3.354635
3.28251
1.021972
r1 = tldextract.extract(d1) r2 = tldextract.extract(d2) # r1 and r2 contain subdomain, domain and suffix. # We want to confirm that domain and suffix match. return r1.domain == r2.domain and r1.suffix == r2.suffix
def base_domain_matches(d1, d2)
Check if two domains have the same base domain, using the Public Suffix List. >>> base_domain_matches('https://hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.com', 'hasjob.co') False >>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.com') False >>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.co.in') True >>> base_domain_matches('example@example.com', 'example.com') True
3.16405
3.693691
0.856609
return composite(MarkdownComposite, Column(name + '_text', UnicodeText, **kwargs), Column(name + '_html', UnicodeText, **kwargs), deferred=deferred, group=group or name )
def MarkdownColumn(name, deferred=False, group=None, **kwargs)
Create a composite column that autogenerates HTML from Markdown text, storing data in db columns named with ``_html`` and ``_text`` prefixes.
5.087738
3.808099
1.336031
if not isinstance(value, MutableDict): if isinstance(value, dict): return MutableDict(value) elif isinstance(value, six.string_types): # Assume JSON string if value: return MutableDict(simplejson.loads(value, use_decimal=True)) else: return MutableDict() # Empty value is an empty dict # this call will raise ValueError return Mutable.coerce(key, value) else: return value
def coerce(cls, key, value)
Convert plain dictionaries to MutableDict.
4.368638
3.441278
1.269481
blacklist = set([n[1:] for n in namespecs if n.startswith('!')]) not_blacklist = [n for n in namespecs if not n.startswith('!')] return Bundle(*[bundle for name, version, bundle in self._require_recursive(*not_blacklist) if name not in blacklist])
def require(self, *namespecs)
Return a bundle of the requested assets and their dependencies.
5.637578
4.78127
1.179097
for statemanager, conditions in self.statetransition.transitions.items(): current_state = getattr(self.obj, statemanager.propname) if conditions['from'] is None: state_valid = True else: mstate = conditions['from'].get(current_state) state_valid = mstate and mstate(self.obj) if state_valid and conditions['if']: state_valid = all(v(self.obj) for v in conditions['if']) if not state_valid: return statemanager, current_state, statemanager.lenum.get(current_state)
def _state_invalid(self)
If the state is invalid for the transition, return details on what didn't match :return: Tuple of (state manager, current state, label for current state)
4.784698
4.429417
1.080209
if value not in self.lenum: raise ValueError("Not a valid value: %s" % value) type(obj).__dict__[self.propname].__set__(obj, value)
def _set(self, obj, value)
Internal method to set state, called by meth:`StateTransition.__call__`
6.885401
6.323578
1.088846
# See `_add_state_internal` for explanation of the following if hasattr(self, name): raise AttributeError( "State group name %s conflicts with existing attribute in the state manager" % name) mstate = ManagedStateGroup(name, self, states) self.states[name] = mstate setattr(self, name, mstate) setattr(self, 'is_' + name.lower(), mstate)
def add_state_group(self, name, *states)
Add a group of managed states. Groups can be specified directly in the :class:`~coaster.utils.classes.LabeledEnum`. This method is only useful for grouping a conditional state with existing states. It cannot be used to form a group of groups. :param str name: Name of this group :param states: :class:`ManagedState` instances to be grouped together
5.133136
5.886859
0.871965
# We'll accept a ManagedState with grouped values, but not a ManagedStateGroup if not isinstance(state, ManagedState): raise TypeError("Not a managed state: %s" % repr(state)) elif state.statemanager != self: raise ValueError("State %s is not associated with this state manager" % repr(state)) if isinstance(label, tuple) and len(label) == 2: label = NameTitle(*label) self._add_state_internal(name, state.value, label=label, validator=validator, class_validator=class_validator, cache_for=cache_for)
def add_conditional_state(self, name, state, validator, class_validator=None, cache_for=None, label=None)
Add a conditional state that combines an existing state with a validator that must also pass. The validator receives the object on which the property is present as a parameter. :param str name: Name of the new state :param ManagedState state: Existing state that this is based on :param validator: Function that will be called with the host object as a parameter :param class_validator: Function that will be called when the state is queried on the class instead of the instance. Falls back to ``validator`` if not specified. Receives the class as the parameter :param cache_for: Integer or function that indicates how long ``validator``'s result can be cached (not applicable to ``class_validator``). ``None`` implies no cache, ``0`` implies indefinite cache (until invalidated by a transition) and any other integer is the number of seconds for which to cache the assertion :param label: Label for this state (string or 2-tuple) TODO: `cache_for`'s implementation is currently pending a test case demonstrating how it will be used.
4.249356
4.474283
0.949729
def decorator(f): if isinstance(f, StateTransition): f.add_transition(self, from_, to, if_, data) st = f else: st = StateTransition(f, self, from_, to, if_, data) self.transitions.append(st.name) return st return decorator
def transition(self, from_, to, if_=None, **data)
Decorates a method to transition from one state to another. The decorated method can accept any necessary parameters and perform additional processing, or raise an exception to abort the transition. If it returns without an error, the state value is updated automatically. Transitions may also abort without raising an exception using :exc:`AbortTransition`. :param from_: Required state to allow this transition (can be a state group) :param to: The state of the object after this transition (automatically set if no exception is raised) :param if_: Validator(s) that, given the object, must all return True for the transition to proceed :param data: Additional metadata, stored on the `StateTransition` object as a :attr:`data` attribute
3.623134
3.975598
0.911343
return self.transition(from_, None, if_, **data)
def requires(self, from_, if_=None, **data)
Decorates a method that may be called if the given state is currently active. Registers a transition internally, but does not change the state. :param from_: Required state to allow this call (can be a state group) :param if_: Validator(s) that, given the object, must all return True for the call to proceed :param data: Additional metadata, stored on the `StateTransition` object as a :attr:`data` attribute
9.028352
11.684745
0.772661
if obj is not None: return getattr(obj, self.propname) else: return getattr(cls, self.propname)
def _value(self, obj, cls=None)
The state value (called from the wrapper)
3.678539
3.269275
1.125185
return CheckConstraint( str(column_constructor(column).in_(lenum.keys()).compile(compile_kwargs={'literal_binds': True})), **kwargs)
def check_constraint(column, lenum, **kwargs)
Returns a SQL CHECK constraint string given a column name and a :class:`~coaster.utils.classes.LabeledEnum`. Alembic may not detect the CHECK constraint when autogenerating migrations, so you may need to do this manually using the Python console to extract the SQL string:: from coaster.sqlalchemy import StateManager from your_app.models import YOUR_ENUM print str(StateManager.check_constraint('your_column', YOUR_ENUM).sqltext) :param str column: Column name :param LabeledEnum lenum: :class:`~coaster.utils.classes.LabeledEnum` to retrieve valid values from :param kwargs: Additional options passed to CheckConstraint
6.43736
8.26925
0.77847
if self.obj is not None: for mstate in self.statemanager.all_states_by_value[self.value]: msw = mstate(self.obj, self.cls) # This returns a wrapper if msw: # If the wrapper evaluates to True, it's our best match return msw
def bestmatch(self)
Best matching current scalar state (direct or conditional), only applicable when accessed via an instance.
9.698454
8.638727
1.122672
if self.obj is not None: return {name: mstate(self.obj, self.cls) for name, mstate in self.statemanager.states.items() if mstate(self.obj, self.cls)}
def current(self)
All states and state groups that are currently active.
6.820048
5.865564
1.162727
if current and isinstance(self.obj, RoleMixin): proxy = self.obj.current_access() else: proxy = {} current = False # In case the host object is not a RoleMixin return OrderedDict((name, transition) for name, transition in # Retrieve transitions from the host object to activate the descriptor. ((name, getattr(self.obj, name)) for name in self.statemanager.transitions) if transition.is_available and (name in proxy if current else True))
def transitions(self, current=True)
Returns available transitions for the current state, as a dictionary of name: :class:`StateTransitionWrapper`. :param bool current: Limit to transitions available in ``obj.`` :meth:`~coaster.sqlalchemy.mixins.RoleMixin.current_access`
8.873592
7.081093
1.253139
proxy = self.obj.access_for(roles, actor, anchors) return {name: transition for name, transition in self.transitions(current=False).items() if name in proxy}
def transitions_for(self, roles=None, actor=None, anchors=[])
For use on :class:`~coaster.sqlalchemy.mixins.RoleMixin` classes: returns currently available transitions for the specified roles or actor as a dictionary of name: :class:`StateTransitionWrapper`.
7.969698
7.099466
1.122577
cls = self.cls if self.cls is not None else type(self.obj) # Class of the item being managed groups = OrderedDict() for mstate in self.statemanager.states_by_value.values(): # Ensure we sort groups using the order of states in the source LabeledEnum. # We'll discard the unused states later. groups[mstate] = [] # Now process the items by state for item in items: # Use isinstance instead of `type(item) != cls` to account for subclasses if not isinstance(item, cls): raise TypeError("Item %s is not an instance of type %s" % (repr(item), repr(self.cls))) statevalue = self.statemanager._value(item) mstate = self.statemanager.states_by_value[statevalue] groups[mstate].append(item) if not keep_empty: for key, value in list(groups.items()): if not value: del groups[key] return groups
def group(self, items, keep_empty=False)
Given an iterable of instances, groups them by state using :class:`ManagedState` instances as dictionary keys. Returns an `OrderedDict` that preserves the order of states from the source :class:`~coaster.utils.classes.LabeledEnum`. :param bool keep_empty: If ``True``, empty states are included in the result
4.859067
4.12167
1.178907
def indent_code(matchobj): syntax = matchobj.group(1) code = matchobj.group(2) if syntax: result = ' :::' + syntax + '\n' else: result = '' # The last line will be blank since it had the closing "```". Discard it # when indenting the lines. return result + '\n'.join([' ' + line for line in code.split('\n')[:-1]]) use_crlf = text.find('\r') != -1 if use_crlf: text = text.replace('\r\n', '\n') # Render GitHub-style ```code blocks``` into Markdown-style 4-space indented blocks text = CODEPATTERN_RE.sub(indent_code, text) text, code_blocks = remove_pre_blocks(text) text, inline_blocks = remove_inline_code_blocks(text) # Prevent foo_bar_baz from ending up with an italic word in the middle. def italic_callback(matchobj): s = matchobj.group(0) # don't mess with URLs: if 'http:' in s or 'https:' in s: return s return s.replace('_', r'\_') # fix italics for code blocks text = ITALICSPATTERN_RE.sub(italic_callback, text) # linkify naked URLs # wrap the URL in brackets: http://foo -> [http://foo](http://foo) text = NAKEDURL_RE.sub(r'\1[\2](\2)\3', text) # In very clear cases, let newlines become <br /> tags. def newline_callback(matchobj): if len(matchobj.group(1)) == 1: return matchobj.group(0).rstrip() + ' \n' else: return matchobj.group(0) text = NEWLINE_RE.sub(newline_callback, text) # now restore removed code blocks removed_blocks = code_blocks + inline_blocks for removed_block in removed_blocks: text = text.replace('{placeholder}', removed_block, 1) if use_crlf: text = text.replace('\n', '\r\n') return text
def gfm(text)
Prepare text for rendering by a regular Markdown processor.
4.021921
3.977104
1.011269
if text is None: return None if html: return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid_tags=valid_tags)) else: return Markup(markdown_convert_text(gfm(text)))
def markdown(text, html=False, valid_tags=GFM_TAGS)
Return Markdown rendered text using GitHub Flavoured Markdown, with HTML escaped and syntax-highlighting enabled.
3.058632
2.979169
1.026673
if method_rule.startswith('/'): return method_rule else: return class_rule + ('' if class_rule.endswith('/') or not method_rule else '/') + method_rule
def rulejoin(class_rule, method_rule)
Join class and method rules. Used internally by :class:`ClassView` to combine rules from the :func:`route` decorators on the class and on the individual view handler methods:: >>> rulejoin('/', '') '/' >>> rulejoin('/', 'first') '/first' >>> rulejoin('/first', '/second') '/second' >>> rulejoin('/first', 'second') '/first/second' >>> rulejoin('/first/', 'second') '/first/second' >>> rulejoin('/first/<second>', '') '/first/<second>' >>> rulejoin('/first/<second>', 'third') '/first/<second>/third'
3.646801
4.352709
0.837823
def inner(f): def is_available_here(context): return bool(roles.intersection(context.obj.current_roles)) def is_available(context): result = is_available_here(context) if result and hasattr(f, 'is_available'): # We passed, but we're wrapping another test, so ask there as well return f.is_available(context) return result @wraps(f) def wrapper(self, *args, **kwargs): add_auth_attribute('login_required', True) if not is_available_here(self): abort(403) return f(self, *args, **kwargs) wrapper.requires_roles = roles wrapper.is_available = is_available return wrapper return inner
def requires_roles(roles)
Decorator for :class:`ModelView` views that limits access to the specified roles.
3.657922
3.7312
0.980361
@wraps(f) def wrapper(self, *args, **kwargs): if request.method == 'GET' and self.obj is not None: correct_url = self.obj.url_for(f.__name__, _external=True) if correct_url != request.base_url: if request.query_string: correct_url = correct_url + '?' + request.query_string.decode() return redirect(correct_url) # TODO: Decide if this should be 302 (default) or 301 return f(self, *args, **kwargs) return wrapper
def url_change_check(f)
View method decorator that checks the URL of the loaded object in ``self.obj`` against the URL in the request (using ``self.obj.url_for(__name__)``). If the URLs do not match, and the request is a ``GET``, it issues a redirect to the correct URL. Usage:: @route('/doc/<document>') class MyModelView(UrlForView, InstanceLoader, ModelView): model = MyModel route_model_map = {'document': 'url_id_name'} @route('') @url_change_check @render_with(json=True) def view(self): return self.obj.current_access() If the decorator is required for all view handlers in the class, use :class:`UrlChangeCheck`.
2.562593
2.345701
1.092464
def view_func(**view_args): # view_func does not make any reference to variables from init_app to avoid creating # a closure. Instead, the code further below sticks all relevant variables into # view_func's namespace. # Instantiate the view class. We depend on its __init__ requiring no parameters viewinst = view_func.view_class() # Declare ourselves (the ViewHandler) as the current view. The wrapper makes # equivalence tests possible, such as ``self.current_handler == self.index`` viewinst.current_handler = ViewHandlerWrapper(view_func.view, viewinst, view_func.view_class) # Place view arguments in the instance, in case they are needed outside the dispatch process viewinst.view_args = view_args # Place the view instance on the request stack for :obj:`current_view` to discover _request_ctx_stack.top.current_view = viewinst # Call the view instance's dispatch method. View classes can customise this for # desired behaviour. return viewinst.dispatch_request(view_func.wrapped_func, view_args) # Decorate the wrapped view function with the class's desired decorators. # Mixin classes may provide their own decorators, and all of them will be applied. # The oldest defined decorators (from mixins) will be applied first, and the # class's own decorators last. Within the list of decorators, we reverse the list # again, so that a list specified like this: # # __decorators__ = [first, second] # # Has the same effect as writing this: # # @first # @second # def myview(self): # pass wrapped_func = self.func for base in reversed(cls.__mro__): if '__decorators__' in base.__dict__: for decorator in reversed(base.__dict__['__decorators__']): wrapped_func = decorator(wrapped_func) wrapped_func.__name__ = self.name # See below # Make view_func resemble the underlying view handler method... view_func = update_wrapper(view_func, wrapped_func) # ...but give view_func the name of the method in the class (self.name), # self.name will differ from __name__ only if the view handler method # was defined outside the class and then added to the class with a # different name. view_func.__name__ = self.name # Stick `wrapped_func` and `cls` into view_func to avoid creating a closure. view_func.wrapped_func = wrapped_func view_func.view_class = cls view_func.view = self # Keep a copy of these functions (we already have self.func) self.wrapped_func = wrapped_func self.view_func = view_func for class_rule, class_options in cls.__routes__: for method_rule, method_options in self.routes: use_options = dict(method_options) use_options.update(class_options) endpoint = use_options.pop('endpoint', self.endpoint) self.endpoints.add(endpoint) use_rule = rulejoin(class_rule, method_rule) app.add_url_rule(use_rule, endpoint, view_func, **use_options) if callback: callback(use_rule, endpoint, view_func, **use_options)
def init_app(self, app, cls, callback=None)
Register routes for a given app and :class:`ClassView` class. At the time of this call, we will always be in the view class even if we were originally defined in a base class. :meth:`ClassView.init_app` ensures this. :meth:`init_app` therefore takes the liberty of adding additional attributes to ``self``: * :attr:`wrapped_func`: The function wrapped with all decorators added by the class * :attr:`view_func`: The view function registered as a Flask view handler * :attr:`endpoints`: The URL endpoints registered to this view handler
5.250796
5.173685
1.014904
if hasattr(self._viewh.wrapped_func, 'is_available'): return self._viewh.wrapped_func.is_available(self._obj) return True
def is_available(self)
Indicates whether this view is available in the current context
6.468046
5.321447
1.215467
# Call the :meth:`before_request` method resp = self.before_request() if resp: return self.after_request(make_response(resp)) # Call the view handler method, then pass the response to :meth:`after_response` return self.after_request(make_response(view(self, **view_args)))
def dispatch_request(self, view, view_args)
View dispatcher that calls before_request, the view, and then after_request. Subclasses may override this to provide a custom flow. :class:`ModelView` does this to insert a model loading phase. :param view: View method wrapped in specified decorators. The dispatcher must call this :param dict view_args: View arguments, to be passed on to the view method
4.243517
4.110312
1.032407
if self.is_always_available: return True for viewname in self.__views__: if getattr(self, viewname).is_available(): return True return False
def is_available(self)
Returns `True` if *any* view handler in the class is currently available via its `is_available` method.
5.016894
3.536884
1.41845
setattr(cls, _name, route(rule, **options)(cls.__get_raw_attr(_name)))
def add_route_for(cls, _name, rule, **options)
Add a route for an existing method or view. Useful for modifying routes that a subclass inherits from a base class:: class BaseView(ClassView): def latent_view(self): return 'latent-view' @route('other') def other_view(self): return 'other-view' @route('/path') class SubView(BaseView): pass SubView.add_route_for('latent_view', 'latent') SubView.add_route_for('other_view', 'another') SubView.init_app(app) # Created routes: # /path/latent -> SubView.latent (added) # /path/other -> SubView.other (inherited) # /path/another -> SubView.other (added) :param _name: Name of the method or view on the class :param rule: URL rule to be added :param options: Additional options for :meth:`~flask.Flask.add_url_rule`
9.58443
15.831733
0.605394
processed = set() cls.__views__ = set() cls.is_always_available = False for base in cls.__mro__: for name, attr in base.__dict__.items(): if name in processed: continue processed.add(name) if isinstance(attr, ViewHandler): if base != cls: # Copy ViewHandler instances into subclasses # TODO: Don't do this during init_app. Use a metaclass # and do this when the class is defined. attr = attr.copy_for_subclass() setattr(cls, name, attr) attr.__set_name__(cls, name) # Required for Python < 3.6 cls.__views__.add(name) attr.init_app(app, cls, callback=callback) if not hasattr(attr.wrapped_func, 'is_available'): cls.is_always_available = True
def init_app(cls, app, callback=None)
Register views on an app. If :attr:`callback` is specified, it will be called after ``app.``:meth:`~flask.Flask.add_url_rule`, with the same parameters.
4.269023
4.244739
1.005721
# Call the :meth:`before_request` method resp = self.before_request() if resp: return self.after_request(make_response(resp)) # Load the database model self.obj = self.loader(**view_args) # Trigger pre-view processing of the loaded object resp = self.after_loader() if resp: return self.after_request(make_response(resp)) # Call the view handler method, then pass the response to :meth:`after_response` return self.after_request(make_response(view(self)))
def dispatch_request(self, view, view_args)
View dispatcher that calls :meth:`before_request`, :meth:`loader`, :meth:`after_loader`, the view, and then :meth:`after_request`. :param view: View method wrapped in specified decorators. :param dict view_args: View arguments, to be passed on to the view method
4.653306
3.951389
1.177638
# Convert lists and None values to sets rw = set(rw) if rw else set() call = set(call) if call else set() read = set(read) if read else set() write = set(write) if write else set() # `rw` is shorthand for read+write read.update(rw) write.update(rw) def inner(attr): __cache__[attr] = {'call': call, 'read': read, 'write': write} try: attr._coaster_roles = {'call': call, 'read': read, 'write': write} # If the attr has a restrictive __slots__, we'll get an attribute error. # Unfortunately, because of the way SQLAlchemy works, by copying objects # into subclasses, the cache alone is not a reliable mechanism. We need both. except AttributeError: pass return attr if is_collection(obj): # Protect against accidental specification of roles instead of an object raise TypeError('Roles must be specified as named parameters') elif obj is not None: return inner(obj) else: return inner
def with_roles(obj=None, rw=None, call=None, read=None, write=None)
Convenience function and decorator to define roles on an attribute. Only works with :class:`RoleMixin`, which reads the annotations made by this function and populates :attr:`~RoleMixin.__roles__`. Examples:: id = db.Column(Integer, primary_key=True) with_roles(id, read={'all'}) @with_roles(read={'all'}) @hybrid_property def url_id(self): return str(self.id) When used with properties, with_roles must always be applied after the property is fully described:: @property def title(self): return self._title @title.setter def title(self, value): self._title = value # Either of the following is fine, since with_roles annotates objects # instead of wrapping them. The return value can be discarded if it's # already present on the host object: with_roles(title, read={'all'}, write={'owner', 'editor'}) title = with_roles(title, read={'all'}, write={'owner', 'editor'}) :param set rw: Roles which get read and write access to the decorated attribute :param set call: Roles which get call access to the decorated method :param set read: Roles which get read access to the decorated attribute :param set write: Roles which get write access to the decorated attribute
5.483829
5.808249
0.944145
def inner(f): @wraps(f) def attr(cls): # Pass f(cls) as a parameter to with_roles.inner to avoid the test for # iterables within with_roles. We have no idea about the use cases for # declared_attr in downstream code. There could be a declared_attr # that returns a list that should be accessible via the proxy. return with_roles(rw=rw, call=call, read=read, write=write)(f(cls)) return attr warnings.warn("declared_attr_roles is deprecated; use with_roles", stacklevel=2) return inner
def declared_attr_roles(rw=None, call=None, read=None, write=None)
Equivalent of :func:`with_roles` for use with ``@declared_attr``:: @declared_attr @declared_attr_roles(read={'all'}) def my_column(cls): return Column(Integer) While :func:`with_roles` is always the outermost decorator on properties and functions, :func:`declared_attr_roles` must appear below ``@declared_attr`` to work correctly. .. deprecated:: 0.6.1 Use :func:`with_roles` instead. It works for :class:`~sqlalchemy.ext.declarative.declared_attr` since 0.6.1
7.80649
7.481693
1.043412
# Don't mutate ``__roles__`` in the base class. # The subclass must have its own. # Since classes may specify ``__roles__`` directly without # using :func:`with_roles`, we must preserve existing content. if '__roles__' not in cls.__dict__: # If the following line is confusing, it's because reading an # attribute on an object invokes the Method Resolution Order (MRO) # mechanism to find it on base classes, while writing always writes # to the current object. cls.__roles__ = deepcopy(cls.__roles__) # An attribute may be defined more than once in base classes. Only handle the first processed = set() # Loop through all attributes in this and base classes, looking for role annotations for base in cls.__mro__: for name, attr in base.__dict__.items(): if name in processed or name.startswith('__'): continue if isinstance(attr, collections.Hashable) and attr in __cache__: data = __cache__[attr] del __cache__[attr] elif isinstance(attr, InstrumentedAttribute) and attr.property in __cache__: data = __cache__[attr.property] del __cache__[attr.property] elif hasattr(attr, '_coaster_roles'): data = attr._coaster_roles else: data = None if data is not None: for role in data.get('call', []): cls.__roles__.setdefault(role, {}).setdefault('call', set()).add(name) for role in data.get('read', []): cls.__roles__.setdefault(role, {}).setdefault('read', set()).add(name) for role in data.get('write', []): cls.__roles__.setdefault(role, {}).setdefault('write', set()).add(name) processed.add(name)
def __configure_roles(mapper, cls)
Run through attributes of the class looking for role decorations from :func:`with_roles` and add them to :attr:`cls.__roles__`
3.939518
3.788303
1.039916
return InspectableSet(self.roles_for(actor=current_auth.actor, anchors=current_auth.anchors))
def current_roles(self)
:class:`~coaster.utils.classes.InspectableSet` containing currently available roles on this object, using :obj:`~coaster.auth.current_auth`. Use in the view layer to inspect for a role being present: if obj.current_roles.editor: pass {% if obj.current_roles.editor %}...{% endif %} This property is also available in :class:`RoleAccessProxy`.
20.461571
10.844199
1.886868
if roles is None: roles = self.roles_for(actor=actor, anchors=anchors) elif actor is not None or anchors: raise TypeError('If roles are specified, actor/anchors must not be specified') return RoleAccessProxy(self, roles=roles)
def access_for(self, roles=None, actor=None, anchors=[])
Return a proxy object that limits read and write access to attributes based on the actor's roles. If the ``roles`` parameter isn't provided, :meth:`roles_for` is called with the other parameters:: # This typical call: obj.access_for(actor=current_auth.actor) # Is shorthand for: obj.access_for(roles=obj.roles_for(actor=current_auth.actor))
3.844693
3.359956
1.144269
return self.access_for(actor=current_auth.actor, anchors=current_auth.anchors)
def current_access(self)
Wraps :meth:`access_for` with :obj:`~coaster.auth.current_auth` to return a proxy for the currently authenticated user.
17.94174
8.278926
2.167158
if current_app.config.get('SERVER_NAME') and ( # Check current hostname against server name, ignoring port numbers, if any (split on ':') request.environ['HTTP_HOST'].split(':', 1)[0] != current_app.config['SERVER_NAME'].split(':', 1)[0]): return request.url url = url_for(request.endpoint, **request.view_args) query = request.query_string if query: return url + '?' + query.decode() else: return url
def get_current_url()
Return the current URL including the query string as a relative path. If the app uses subdomains, return an absolute path
3.534254
3.419292
1.033622
if session: next_url = request_session.pop('next', None) or request.args.get('next', '') else: next_url = request.args.get('next', '') if next_url and not external: next_url = __clean_external_url(next_url) if next_url: return next_url if default is __marker: usedefault = False else: usedefault = True if referrer and request.referrer: if external: return request.referrer else: return __clean_external_url(request.referrer) or (default if usedefault else __index_url()) else: return default if usedefault else __index_url()
def get_next_url(referrer=False, external=False, session=False, default=__marker)
Get the next URL to redirect to. Don't return external URLs unless explicitly asked for. This is to protect the site from being an unwitting redirector to external URLs. Subdomains are okay, however. This function looks for a ``next`` parameter in the request or in the session (depending on whether parameter ``session`` is True). If no ``next`` is present, it checks the referrer (if enabled), and finally returns either the provided default (which can be any value including ``None``) or the script root (typically ``/``).
2.666718
2.629724
1.014068
data = json.dumps(dict(*args, **kw), indent=2) callback = request.args.get('callback', request.args.get('jsonp')) if callback and __jsoncallback_re.search(callback) is not None: data = callback + u'(' + data + u');' mimetype = 'application/javascript' else: mimetype = 'application/json' return Response(data, mimetype=mimetype)
def jsonp(*args, **kw)
Returns a JSON response with a callback wrapper, if asked for. Consider using CORS instead, as JSONP makes the client app insecure. See the :func:`~coaster.views.decorators.cors` decorator.
2.538811
2.55396
0.994069
parsed_url = urlsplit(url) if not parsed_url.netloc: # We require an absolute URL return None, {} # Take the current runtime environment... environ = dict(request.environ) # ...but replace the HTTP host with the URL's host... environ['HTTP_HOST'] = parsed_url.netloc # ...and the path with the URL's path (after discounting the app path, if not hosted at root). environ['PATH_INFO'] = parsed_url.path[len(environ.get('SCRIPT_NAME', '')):] # Create a new request with this environment... url_request = current_app.request_class(environ) # ...and a URL adapter with the new request. url_adapter = current_app.create_url_adapter(url_request) # Run three hostname tests, one of which must pass: # 1. Does the URL map have host matching enabled? If so, the URL adapter will validate the hostname. if current_app.url_map.host_matching: pass # 2. If not, does the domain match? url_adapter.server_name will prefer app.config['SERVER_NAME'], # but if that is not specified, it will take it from the environment. elif parsed_url.netloc == url_adapter.server_name: pass # 3. If subdomain matching is enabled, does the subdomain match? elif current_app.subdomain_matching and parsed_url.netloc.endswith('.' + url_adapter.server_name): pass # If no test passed, we don't have a matching endpoint. else: return None, {} # Now retrieve the endpoint or rule, watching for redirects or resolution failures try: return url_adapter.match(parsed_url.path, method, return_rule=return_rule) except RequestRedirect as r: # A redirect typically implies `/folder` -> `/folder/` # This will not be a redirect response from a view, since the view isn't being called if follow_redirects: return endpoint_for(r.new_url, method=method, return_rule=return_rule, follow_redirects=follow_redirects) except (NotFound, MethodNotAllowed): pass # If we got here, no endpoint was found. return None, {}
def endpoint_for(url, method=None, return_rule=False, follow_redirects=True)
Given an absolute URL, retrieve the matching endpoint name (or rule) and view arguments. Requires a current request context to determine runtime environment. :param str method: HTTP method to use (defaults to GET) :param bool return_rule: Return the URL rule instead of the endpoint name :param bool follow_redirects: Follow redirects to final endpoint :return: Tuple of endpoint name or URL rule or `None`, view arguments
4.51112
4.317631
1.044814
perms = set(super(DocumentWorkflow, self).permissions()) if g: if hasattr(g, 'permissions'): perms.update(g.permissions or []) if hasattr(self.document, 'permissions'): perms = self.document.permissions(current_auth.actor, perms) return perms
def permissions(self)
Permissions for this workflow. Plays nice with :meth:`coaster.views.load_models` and :class:`coaster.sqlalchemy.PermissionMixin` to determine the available permissions to the current user.
6.968427
6.457468
1.079127
annotations = {} annotations_by_attr = {} # An attribute may be defined more than once in base classes. Only handle the first processed = set() # Loop through all attributes in the class and its base classes, looking for annotations for base in cls.__mro__: for name, attr in base.__dict__.items(): if name in processed or name.startswith('__'): continue # 'data' is a list of string annotations if isinstance(attr, collections.Hashable) and attr in __cache__: data = __cache__[attr] del __cache__[attr] elif isinstance(attr, InstrumentedAttribute) and attr.property in __cache__: data = __cache__[attr.property] del __cache__[attr.property] elif hasattr(attr, '_coaster_annotations'): data = attr._coaster_annotations else: data = None if data is not None: annotations_by_attr.setdefault(name, []).extend(data) for a in data: annotations.setdefault(a, []).append(name) processed.add(name) # Classes specifying ``__annotations__`` directly isn't supported, # so we don't bother preserving existing content, if any. if annotations: cls.__annotations__ = annotations if annotations_by_attr: cls.__annotations_by_attr__ = annotations_by_attr annotations_configured.send(cls)
def __configure_annotations(mapper, cls)
Run through attributes of the class looking for annotations from :func:`annotation_wrapper` and add them to :attr:`cls.__annotations__` and :attr:`cls.__annotations_by_attr__`
3.55573
3.521393
1.009751
def decorator(attr): __cache__.setdefault(attr, []).append(annotation) # Also mark the annotation on the object itself. This will # fail if the object has a restrictive __slots__, but it's # required for some objects like Column because SQLAlchemy copies # them in subclasses, changing their hash and making them # undiscoverable via the cache. try: if not hasattr(attr, '_coaster_annotations'): setattr(attr, '_coaster_annotations', []) attr._coaster_annotations.append(annotation) except AttributeError: pass return attr decorator.__name__ = decorator.name = annotation decorator.__doc__ = doc return decorator
def annotation_wrapper(annotation, doc=None)
Defines an annotation, which can be applied to attributes in a database model.
7.391641
7.181705
1.029232
if attr in ('actor', 'anchors', 'is_anonymous', 'not_anonymous', 'is_authenticated', 'not_authenticated'): raise AttributeError("Attribute name %s is reserved by current_auth" % attr) # Invoking current_auth will also create it on the local stack. We can # then proceed to set attributes on it. ca = current_auth._get_current_object() # Since :class:`CurrentAuth` overrides ``__setattr__``, we need to use :class:`object`'s. object.__setattr__(ca, attr, value) if attr == 'user': # Special-case 'user' for compatibility with Flask-Login _request_ctx_stack.top.user = value # A user is always an actor actor = True if actor: object.__setattr__(ca, 'actor', value)
def add_auth_attribute(attr, value, actor=False)
Helper function for login managers. Adds authorization attributes to :obj:`current_auth` for the duration of the request. :param str attr: Name of the attribute :param value: Value of the attribute :param bool actor: Whether this attribute is an actor (user or client app accessing own data) If the attribute is an actor and :obj:`current_auth` does not currently have an actor, the attribute is also made available as ``current_auth.actor``, which in turn is used by ``current_auth.is_authenticated``. The attribute name ``user`` is special-cased: 1. ``user`` is always treated as an actor 2. ``user`` is also made available as ``_request_ctx_stack.top.user`` for compatibility with Flask-Login
6.290623
5.564731
1.130445