repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
hasgeek/coaster
coaster/app.py
init_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 Fla...
python
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 Fla...
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 ap...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/app.py#L84-L121
hasgeek/coaster
coaster/app.py
load_config_from_file
def load_config_from_file(app, filepath): """Helper function to load config from a specified file""" 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 fi...
python
def load_config_from_file(app, filepath): """Helper function to load config from a specified file""" 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 fi...
Helper function to load config from a specified file
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/app.py#L124-L133
hasgeek/coaster
coaster/app.py
SandboxedFlask.create_jinja_environment
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. """ ...
python
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. """ ...
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.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/app.py#L59-L81
hasgeek/coaster
coaster/utils/tsquery.py
for_tsquery
def for_tsquery(text): r""" Tokenize text into a valid PostgreSQL to_tsquery query. >>> for_tsquery(" ") '' >>> for_tsquery("This is a test") "'This is a test'" >>> for_tsquery('Match "this AND phrase"') "'Match this'&'phrase'" >>> for_tsquery('Match "this & phrase"') "'Match th...
python
def for_tsquery(text): r""" Tokenize text into a valid PostgreSQL to_tsquery query. >>> for_tsquery(" ") '' >>> for_tsquery("This is a test") "'This is a test'" >>> for_tsquery('Match "this AND phrase"') "'Match this'&'phrase'" >>> for_tsquery('Match "this & phrase"') "'Match th...
r""" Tokenize text into a valid PostgreSQL to_tsquery query. >>> for_tsquery(" ") '' >>> for_tsquery("This is a test") "'This is a test'" >>> for_tsquery('Match "this AND phrase"') "'Match this'&'phrase'" >>> for_tsquery('Match "this & phrase"') "'Match this'&'phrase'" >>> for_t...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/tsquery.py#L19-L137
hasgeek/coaster
coaster/sqlalchemy/mixins.py
IdMixin.id
def id(cls): """ Database identity for this model, used for foreign key references from other models """ if cls.__uuid_primary_key__: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, primary_key=True, nullable=False)) else: return immut...
python
def id(cls): """ Database identity for this model, used for foreign key references from other models """ if cls.__uuid_primary_key__: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, primary_key=True, nullable=False)) else: return immut...
Database identity for this model, used for foreign key references from other models
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L61-L68
hasgeek/coaster
coaster/sqlalchemy/mixins.py
IdMixin.url_id
def url_id(cls): """The URL id""" if cls.__uuid_primary_key__: def url_id_func(self): """The URL id, UUID primary key rendered as a hex string""" return self.id.hex def url_id_is(cls): return SqlHexUuidComparator(cls.id) ...
python
def url_id(cls): """The URL id""" if cls.__uuid_primary_key__: def url_id_func(self): """The URL id, UUID primary key rendered as a hex string""" return self.id.hex def url_id_is(cls): return SqlHexUuidComparator(cls.id) ...
The URL id
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L71-L97
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UuidMixin.uuid
def uuid(cls): """UUID column, or synonym to existing :attr:`id` column if that is a UUID""" 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, ...
python
def uuid(cls): """UUID column, or synonym to existing :attr:`id` column if that is a UUID""" 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, ...
UUID column, or synonym to existing :attr:`id` column if that is a UUID
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L112-L117
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.url_for
def url_for(self, action='view', **kwargs): """ Return public URL to this instance for a given action (default 'view') """ 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, ...
python
def url_for(self, action='view', **kwargs): """ Return public URL to this instance for a given action (default 'view') """ 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, ...
Return public URL to this instance for a given action (default 'view')
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L213-L248
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.is_url_for
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. """ def decorator(f): if 'url_for_endpoints' not in cls.__dict__: cls.url_for_endpoints = {None: {}} ...
python
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. """ def decorator(f): if 'url_for_endpoints' not in cls.__dict__: cls.url_for_endpoints = {None: {}} ...
View decorator that registers the view as a :meth:`url_for` target.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L258-L272
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.register_view_for
def register_view_for(cls, app, action, classview, attr): """ Register a classview and viewhandler for a given app and action """ if 'view_for_endpoints' not in cls.__dict__: cls.view_for_endpoints = {} cls.view_for_endpoints.setdefault(app, {})[action] = (classview, ...
python
def register_view_for(cls, app, action, classview, attr): """ Register a classview and viewhandler for a given app and action """ if 'view_for_endpoints' not in cls.__dict__: cls.view_for_endpoints = {} cls.view_for_endpoints.setdefault(app, {})[action] = (classview, ...
Register a classview and viewhandler for a given app and action
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L275-L281
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.view_for
def view_for(self, action='view'): """ Return the classview viewhandler that handles the specified action """ app = current_app._get_current_object() view, attr = self.view_for_endpoints[app][action] return getattr(view(self), attr)
python
def view_for(self, action='view'): """ Return the classview viewhandler that handles the specified action """ app = current_app._get_current_object() view, attr = self.view_for_endpoints[app][action] return getattr(view(self), attr)
Return the classview viewhandler that handles the specified action
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L283-L289
hasgeek/coaster
coaster/sqlalchemy/mixins.py
UrlForMixin.classview_for
def classview_for(self, action='view'): """ Return the classview that contains the viewhandler for the specified action """ app = current_app._get_current_object() return self.view_for_endpoints[app][action][0](self)
python
def classview_for(self, action='view'): """ Return the classview that contains the viewhandler for the specified action """ app = current_app._get_current_object() return self.view_for_endpoints[app][action][0](self)
Return the classview that contains the viewhandler for the specified action
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L291-L296
hasgeek/coaster
coaster/sqlalchemy/mixins.py
NoIdMixin._set_fields
def _set_fields(self, fields): """Helper method for :meth:`upsert` in the various subclasses""" 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=...
python
def _set_fields(self, fields): """Helper method for :meth:`upsert` in the various subclasses""" 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=...
Helper method for :meth:`upsert` in the various subclasses
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L305-L311
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseNameMixin.name
def name(cls): """The URL name of this object, unique across all instances of this model""" if cls.__name_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__name_length__) if cls.__name_blank_allowed__: return Column(column...
python
def name(cls): """The URL name of this object, unique across all instances of this model""" if cls.__name_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__name_length__) if cls.__name_blank_allowed__: return Column(column...
The URL name of this object, unique across all instances of this model
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L347-L356
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseNameMixin.title
def title(cls): """The title of this object""" if cls.__title_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__title_length__) return Column(column_type, nullable=False)
python
def title(cls): """The title of this object""" if cls.__title_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__title_length__) return Column(column_type, nullable=False)
The title of this object
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L359-L365
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseNameMixin.upsert
def upsert(cls, name, **fields): """Insert or update an instance""" 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) ret...
python
def upsert(cls, name, **fields): """Insert or update an instance""" 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) ret...
Insert or update an instance
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L386-L394
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseNameMixin.make_name
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 se...
python
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 se...
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
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L396-L414
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedNameMixin.get
def get(cls, parent, name): """Get an instance matching the parent and name""" return cls.query.filter_by(parent=parent, name=name).one_or_none()
python
def get(cls, parent, name): """Get an instance matching the parent and name""" return cls.query.filter_by(parent=parent, name=name).one_or_none()
Get an instance matching the parent and name
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L483-L485
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedNameMixin.short_title
def short_title(self): """ Generates an abbreviated title by subtracting the parent's title from this instance's title. """ 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): ...
python
def short_title(self): """ Generates an abbreviated title by subtracting the parent's title from this instance's title. """ 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): ...
Generates an abbreviated title by subtracting the parent's title from this instance's title.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L517-L529
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedNameMixin.permissions
def permissions(self, actor, inherited=None): """ Permissions for this model, plus permissions inherited from the parent. """ if inherited is not None: return inherited | super(BaseScopedNameMixin, self).permissions(actor) elif self.parent is not None and isinstance(s...
python
def permissions(self, actor, inherited=None): """ Permissions for this model, plus permissions inherited from the parent. """ if inherited is not None: return inherited | super(BaseScopedNameMixin, self).permissions(actor) elif self.parent is not None and isinstance(s...
Permissions for this model, plus permissions inherited from the parent.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L536-L545
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseIdNameMixin.make_name
def make_name(self): """Autogenerates a :attr:`name` from :attr:`title_for_name`""" if self.title: self.name = six.text_type(make_name(self.title_for_name, maxlength=self.__name_length__))
python
def make_name(self): """Autogenerates a :attr:`name` from :attr:`title_for_name`""" if self.title: self.name = six.text_type(make_name(self.title_for_name, maxlength=self.__name_length__))
Autogenerates a :attr:`name` from :attr:`title_for_name`
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L605-L608
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedIdMixin.get
def get(cls, parent, url_id): """Get an instance matching the parent and url_id""" return cls.query.filter_by(parent=parent, url_id=url_id).one_or_none()
python
def get(cls, parent, url_id): """Get an instance matching the parent and url_id""" return cls.query.filter_by(parent=parent, url_id=url_id).one_or_none()
Get an instance matching the parent and url_id
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L673-L675
hasgeek/coaster
coaster/sqlalchemy/mixins.py
BaseScopedIdMixin.make_id
def make_id(self): """Create a new URL id that is unique to the parent container""" 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)
python
def make_id(self): """Create a new URL id that is unique to the parent container""" 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)
Create a new URL id that is unique to the parent container
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L677-L681
hasgeek/coaster
coaster/sqlalchemy/functions.py
make_timestamp_columns
def make_timestamp_columns(): """Return two columns, created_at and updated_at, with appropriate defaults""" return ( Column('created_at', DateTime, default=func.utcnow(), nullable=False), Column('updated_at', DateTime, default=func.utcnow(), onupdate=func.utcnow(), nullable=False), )
python
def make_timestamp_columns(): """Return two columns, created_at and updated_at, with appropriate defaults""" return ( Column('created_at', DateTime, default=func.utcnow(), nullable=False), Column('updated_at', DateTime, default=func.utcnow(), onupdate=func.utcnow(), nullable=False), )
Return two columns, created_at and updated_at, with appropriate defaults
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/functions.py#L49-L54
hasgeek/coaster
coaster/sqlalchemy/functions.py
failsafe_add
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 envi...
python
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 envi...
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 save...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/functions.py#L57-L105
hasgeek/coaster
coaster/sqlalchemy/functions.py
add_primary_relationship
def add_primary_relationship(parent, childrel, child, parentrel, parentcol): """ When a parent-child relationship is defined as one-to-many, :func:`add_primary_relationship` lets the parent refer to one child as the primary, by creating a secondary table to hold the reference. Under PostgreSQL, a tr...
python
def add_primary_relationship(parent, childrel, child, parentrel, parentcol): """ When a parent-child relationship is defined as one-to-many, :func:`add_primary_relationship` lets the parent refer to one child as the primary, by creating a secondary table to hold the reference. Under PostgreSQL, a tr...
When a parent-child relationship is defined as one-to-many, :func:`add_primary_relationship` lets the parent refer to one child as the primary, by creating a secondary table to hold the reference. Under PostgreSQL, a trigger is added as well to ensure foreign key integrity. A SQLAlchemy relationship na...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/functions.py#L108-L210
hasgeek/coaster
coaster/sqlalchemy/functions.py
auto_init_default
def auto_init_default(column): """ Set the default value for a column when it's first accessed rather than first committed to the database. """ if isinstance(column, ColumnProperty): default = column.columns[0].default else: default = column.default @event.listens_for(column...
python
def auto_init_default(column): """ Set the default value for a column when it's first accessed rather than first committed to the database. """ if isinstance(column, ColumnProperty): default = column.columns[0].default else: default = column.default @event.listens_for(column...
Set the default value for a column when it's first accessed rather than first committed to the database.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/functions.py#L213-L234
hasgeek/coaster
coaster/views/decorators.py
requestargs
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 take...
python
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 take...
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 ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L42-L130
hasgeek/coaster
coaster/views/decorators.py
load_model
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 pro...
python
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 pro...
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: # p...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L147-L203
hasgeek/coaster
coaster/views/decorators.py
load_models
def load_models(*chain, **kwargs): """ Decorator to load a chain of models from the given parameters. This works just like :func:`load_model` and accepts the same parameters, with some small differences. :param chain: The chain is a list of tuples of (``model``, ``attributes``, ``parameter``). ...
python
def load_models(*chain, **kwargs): """ Decorator to load a chain of models from the given parameters. This works just like :func:`load_model` and accepts the same parameters, with some small differences. :param chain: The chain is a list of tuples of (``model``, ``attributes``, ``parameter``). ...
Decorator to load a chain of models from the given parameters. This works just like :func:`load_model` and accepts the same parameters, with some small differences. :param chain: The chain is a list of tuples of (``model``, ``attributes``, ``parameter``). Lists and tuples can be used interchangeably. A...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L206-L323
hasgeek/coaster
coaster/views/decorators.py
dict_jsonify
def dict_jsonify(param): """Convert the parameter into a dictionary before calling jsonify, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonify(param)
python
def dict_jsonify(param): """Convert the parameter into a dictionary before calling jsonify, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonify(param)
Convert the parameter into a dictionary before calling jsonify, if it's not already one
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L334-L338
hasgeek/coaster
coaster/views/decorators.py
dict_jsonp
def dict_jsonp(param): """Convert the parameter into a dictionary before calling jsonp, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonp(param)
python
def dict_jsonp(param): """Convert the parameter into a dictionary before calling jsonp, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonp(param)
Convert the parameter into a dictionary before calling jsonp, if it's not already one
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L341-L345
hasgeek/coaster
coaster/views/decorators.py
render_with
def render_with(template=None, json=False, jsonp=False): """ Decorator to render the wrapped function with the given template (or dictionary of mimetype keys to templates, where the template is a string name of a template file or a callable that returns a Response). The function's return value must be ...
python
def render_with(template=None, json=False, jsonp=False): """ Decorator to render the wrapped function with the given template (or dictionary of mimetype keys to templates, where the template is a string name of a template file or a callable that returns a Response). The function's return value must be ...
Decorator to render the wrapped function with the given template (or dictionary of mimetype keys to templates, where the template is a string name of a template file or a callable that returns a Response). The function's return value must be a dictionary and is passed to the template as parameters. Callable...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L348-L510
hasgeek/coaster
coaster/views/decorators.py
cors
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...
python
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...
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...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L513-L598
hasgeek/coaster
coaster/views/decorators.py
requires_permission
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 tha...
python
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 tha...
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. ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/decorators.py#L601-L639
hasgeek/coaster
coaster/utils/misc.py
is_collection
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_colle...
python
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_colle...
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_collec...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L48-L75
hasgeek/coaster
coaster/utils/misc.py
buid
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 """ ...
python
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 """ ...
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
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L78-L94
hasgeek/coaster
coaster/utils/misc.py
uuid1mc_from_datetime
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 con...
python
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 con...
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() ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L104-L145
hasgeek/coaster
coaster/utils/misc.py
uuid2buid
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' """ if six.PY3: # pragma: no cover return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=') else...
python
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' """ if six.PY3: # pragma: no cover return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=') else...
Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ'
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L148-L159
hasgeek/coaster
coaster/utils/misc.py
newpin
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 """ randnum = randint(0, 10 ** digits) while len(str(randnum)) > digits: randnum = randin...
python
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 """ randnum = randint(0, 10 ** digits) while len(str(randnum)) > digits: randnum = randin...
Return a random numeric string with the specified number of digits, default 4. >>> len(newpin()) 4 >>> len(newpin(5)) 5 >>> newpin().isdigit() True
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L186-L201
hasgeek/coaster
coaster/utils/misc.py
make_name
def make_name(text, delim=u'-', maxlength=50, checkused=None, counter=2): u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param str...
python
def make_name(text, delim=u'-', maxlength=50, checkused=None, counter=2): u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param str...
u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param string delim: Delimiter between words, default '-' :param int maxlength: Maxi...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L204-L291
hasgeek/coaster
coaster/utils/misc.py
make_password
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_...
python
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_...
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
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L294-L338
hasgeek/coaster
coaster/utils/misc.py
check_password
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-encodin...
python
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-encodin...
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/uVU8r...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L341-L398
hasgeek/coaster
coaster/utils/misc.py
format_currency
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' >>> form...
python
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' >>> form...
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_curren...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L401-L437
hasgeek/coaster
coaster/utils/misc.py
md5sum
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 """ if six.PY3: # pragma: no cover return h...
python
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 """ if six.PY3: # pragma: no cover return h...
Return md5sum of data as a 32-character string. >>> md5sum('random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> md5sum(u'random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> len(md5sum('random text')) 32
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L440-L454
hasgeek/coaster
coaster/utils/misc.py
isoweek_datetime
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, ...
python
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, ...
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')...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L464-L488
hasgeek/coaster
coaster/utils/misc.py
midnight_to_utc
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...
python
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...
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(...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L491-L528
hasgeek/coaster
coaster/utils/misc.py
getbool
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...
python
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...
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 ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L531-L558
hasgeek/coaster
coaster/utils/misc.py
require_one_of
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): ...
python
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): ...
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` ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L592-L642
hasgeek/coaster
coaster/utils/misc.py
unicode_http_header
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=F6...
python
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=F6...
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 ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L645-L664
hasgeek/coaster
coaster/utils/misc.py
get_email_domain
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_...
python
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_...
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.c...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L667-L691
hasgeek/coaster
coaster/utils/misc.py
sorted_timezones
def sorted_timezones(): """ Return a list of timezones sorted by offset from UTC. """ def hourmin(delta): if delta.days < 0: hours, remaining = divmod(86400 - delta.seconds, 3600) else: hours, remaining = divmod(delta.seconds, 3600) minutes, remaining = di...
python
def sorted_timezones(): """ Return a list of timezones sorted by offset from UTC. """ def hourmin(delta): if delta.days < 0: hours, remaining = divmod(86400 - delta.seconds, 3600) else: hours, remaining = divmod(delta.seconds, 3600) minutes, remaining = di...
Return a list of timezones sorted by offset from UTC.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L714-L746
hasgeek/coaster
coaster/utils/misc.py
namespace_from_url
def namespace_from_url(url): """ Construct a dotted namespace string from a URL. """ 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...
python
def namespace_from_url(url): """ Construct a dotted namespace string from a URL. """ 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...
Construct a dotted namespace string from a URL.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L749-L764
hasgeek/coaster
coaster/utils/misc.py
base_domain_matches
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'...
python
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'...
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('stat...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/misc.py#L767-L788
hasgeek/coaster
coaster/sqlalchemy/columns.py
MarkdownColumn
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. """ return composite(MarkdownComposite, Column(name + '_text', UnicodeText, **kwar...
python
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. """ return composite(MarkdownComposite, Column(name + '_text', UnicodeText, **kwar...
Create a composite column that autogenerates HTML from Markdown text, storing data in db columns named with ``_html`` and ``_text`` prefixes.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/columns.py#L177-L186
hasgeek/coaster
coaster/sqlalchemy/columns.py
MutableDict.coerce
def coerce(cls, key, value): """Convert plain dictionaries to MutableDict.""" if not isinstance(value, MutableDict): if isinstance(value, dict): return MutableDict(value) elif isinstance(value, six.string_types): # Assume JSON string ...
python
def coerce(cls, key, value): """Convert plain dictionaries to MutableDict.""" if not isinstance(value, MutableDict): if isinstance(value, dict): return MutableDict(value) elif isinstance(value, six.string_types): # Assume JSON string ...
Convert plain dictionaries to MutableDict.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/columns.py#L79-L95
hasgeek/coaster
coaster/assets.py
VersionedAssets.require
def require(self, *namespecs): """Return a bundle of the requested assets and their dependencies.""" 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 ...
python
def require(self, *namespecs): """Return a bundle of the requested assets and their dependencies.""" 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 ...
Return a bundle of the requested assets and their dependencies.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/assets.py#L165-L170
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateTransitionWrapper._state_invalid
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) """ for statemanager, conditions in self.statetransition.transitions.items(): curre...
python
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) """ for statemanager, conditions in self.statetransition.transitions.items(): curre...
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)
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L538-L554
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager._set
def _set(self, obj, value): """Internal method to set state, called by meth:`StateTransition.__call__`""" if value not in self.lenum: raise ValueError("Not a valid value: %s" % value) type(obj).__dict__[self.propname].__set__(obj, value)
python
def _set(self, obj, value): """Internal method to set state, called by meth:`StateTransition.__call__`""" if value not in self.lenum: raise ValueError("Not a valid value: %s" % value) type(obj).__dict__[self.propname].__set__(obj, value)
Internal method to set state, called by meth:`StateTransition.__call__`
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L662-L667
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.add_state_group
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...
python
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...
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 ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L690-L707
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.add_conditional_state
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. ...
python
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. ...
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 ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L709-L738
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.transition
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 e...
python
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 e...
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...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L740-L763
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.requires
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_: Val...
python
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_: Val...
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 ca...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L765-L774
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager._value
def _value(self, obj, cls=None): """The state value (called from the wrapper)""" if obj is not None: return getattr(obj, self.propname) else: return getattr(cls, self.propname)
python
def _value(self, obj, cls=None): """The state value (called from the wrapper)""" if obj is not None: return getattr(obj, self.propname) else: return getattr(cls, self.propname)
The state value (called from the wrapper)
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L776-L781
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManager.check_constraint
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 t...
python
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 t...
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:: ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L784-L804
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManagerWrapper.bestmatch
def bestmatch(self): """ Best matching current scalar state (direct or conditional), only applicable when accessed via an instance. """ if self.obj is not None: for mstate in self.statemanager.all_states_by_value[self.value]: msw = mstate(self.obj, sel...
python
def bestmatch(self): """ Best matching current scalar state (direct or conditional), only applicable when accessed via an instance. """ if self.obj is not None: for mstate in self.statemanager.all_states_by_value[self.value]: msw = mstate(self.obj, sel...
Best matching current scalar state (direct or conditional), only applicable when accessed via an instance.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L832-L841
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManagerWrapper.current
def current(self): """ All states and state groups that are currently active. """ 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)}
python
def current(self): """ All states and state groups that are currently active. """ 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)}
All states and state groups that are currently active.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L843-L850
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManagerWrapper.transitions
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` ...
python
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` ...
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`
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L852-L868
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManagerWrapper.transitions_for
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`. """ prox...
python
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`. """ prox...
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`.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L870-L878
hasgeek/coaster
coaster/sqlalchemy/statemanager.py
StateManagerWrapper.group
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`. :...
python
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`. :...
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 ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/statemanager.py#L880-L906
hasgeek/coaster
coaster/gfm.py
gfm
def gfm(text): """ Prepare text for rendering by a regular Markdown processor. """ def indent_code(matchobj): syntax = matchobj.group(1) code = matchobj.group(2) if syntax: result = ' :::' + syntax + '\n' else: result = '' # The last lin...
python
def gfm(text): """ Prepare text for rendering by a regular Markdown processor. """ def indent_code(matchobj): syntax = matchobj.group(1) code = matchobj.group(2) if syntax: result = ' :::' + syntax + '\n' else: result = '' # The last lin...
Prepare text for rendering by a regular Markdown processor.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/gfm.py#L111-L169
hasgeek/coaster
coaster/gfm.py
markdown
def markdown(text, html=False, valid_tags=GFM_TAGS): """ Return Markdown rendered text using GitHub Flavoured Markdown, with HTML escaped and syntax-highlighting enabled. """ if text is None: return None if html: return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid...
python
def markdown(text, html=False, valid_tags=GFM_TAGS): """ Return Markdown rendered text using GitHub Flavoured Markdown, with HTML escaped and syntax-highlighting enabled. """ if text is None: return None if html: return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid...
Return Markdown rendered text using GitHub Flavoured Markdown, with HTML escaped and syntax-highlighting enabled.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/gfm.py#L172-L182
hasgeek/coaster
coaster/views/classview.py
rulejoin
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') ...
python
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') ...
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')...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L56-L80
hasgeek/coaster
coaster/views/classview.py
requires_roles
def requires_roles(roles): """ Decorator for :class:`ModelView` views that limits access to the specified roles. """ def inner(f): def is_available_here(context): return bool(roles.intersection(context.obj.current_roles)) def is_available(context): result = i...
python
def requires_roles(roles): """ Decorator for :class:`ModelView` views that limits access to the specified roles. """ def inner(f): def is_available_here(context): return bool(roles.intersection(context.obj.current_roles)) def is_available(context): result = i...
Decorator for :class:`ModelView` views that limits access to the specified roles.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L568-L594
hasgeek/coaster
coaster/views/classview.py
url_change_check
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:: @ro...
python
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:: @ro...
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 ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L634-L665
hasgeek/coaster
coaster/views/classview.py
ViewHandler.init_app
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_ap...
python
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_ap...
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 attri...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L149-L226
hasgeek/coaster
coaster/views/classview.py
ViewHandlerWrapper.is_available
def is_available(self): """Indicates whether this view is available in the current context""" if hasattr(self._viewh.wrapped_func, 'is_available'): return self._viewh.wrapped_func.is_available(self._obj) return True
python
def is_available(self): """Indicates whether this view is available in the current context""" if hasattr(self._viewh.wrapped_func, 'is_available'): return self._viewh.wrapped_func.is_available(self._obj) return True
Indicates whether this view is available in the current context
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L254-L258
hasgeek/coaster
coaster/views/classview.py
ClassView.dispatch_request
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 ...
python
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 ...
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 ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L342-L357
hasgeek/coaster
coaster/views/classview.py
ClassView.is_available
def is_available(self): """ Returns `True` if *any* view handler in the class is currently available via its `is_available` method. """ if self.is_always_available: return True for viewname in self.__views__: if getattr(self, viewname).is_available...
python
def is_available(self): """ Returns `True` if *any* view handler in the class is currently available via its `is_available` method. """ if self.is_always_available: return True for viewname in self.__views__: if getattr(self, viewname).is_available...
Returns `True` if *any* view handler in the class is currently available via its `is_available` method.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L387-L397
hasgeek/coaster
coaster/views/classview.py
ClassView.add_route_for
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' ...
python
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' ...
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): ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L407-L437
hasgeek/coaster
coaster/views/classview.py
ClassView.init_app
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. """ processed = set() cls.__views__ = set() cls.is_always_av...
python
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. """ processed = set() cls.__views__ = set() cls.is_always_av...
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.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L440-L464
hasgeek/coaster
coaster/views/classview.py
ModelView.dispatch_request
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...
python
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...
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
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/classview.py#L518-L537
hasgeek/coaster
coaster/sqlalchemy/roles.py
with_roles
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....
python
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....
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'}) @...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L210-L277
hasgeek/coaster
coaster/sqlalchemy/roles.py
declared_attr_roles
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...
python
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...
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...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L285-L312
hasgeek/coaster
coaster/sqlalchemy/roles.py
__configure_roles
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__` """ # Don't mutate ``__roles__`` in the base class. # The subclass must have its own. # Since classes may specify ``__roles__...
python
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__` """ # Don't mutate ``__roles__`` in the base class. # The subclass must have its own. # Since classes may specify ``__roles__...
Run through attributes of the class looking for role decorations from :func:`with_roles` and add them to :attr:`cls.__roles__`
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L414-L456
hasgeek/coaster
coaster/sqlalchemy/roles.py
RoleMixin.current_roles
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: ...
python
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: ...
: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_ro...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L363-L377
hasgeek/coaster
coaster/sqlalchemy/roles.py
RoleMixin.access_for
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 c...
python
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 c...
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 sho...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L388-L403
hasgeek/coaster
coaster/sqlalchemy/roles.py
RoleMixin.current_access
def current_access(self): """ Wraps :meth:`access_for` with :obj:`~coaster.auth.current_auth` to return a proxy for the currently authenticated user. """ return self.access_for(actor=current_auth.actor, anchors=current_auth.anchors)
python
def current_access(self): """ Wraps :meth:`access_for` with :obj:`~coaster.auth.current_auth` to return a proxy for the currently authenticated user. """ return self.access_for(actor=current_auth.actor, anchors=current_auth.anchors)
Wraps :meth:`access_for` with :obj:`~coaster.auth.current_auth` to return a proxy for the currently authenticated user.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L405-L410
hasgeek/coaster
coaster/views/misc.py
get_current_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 """ if current_app.config.get('SERVER_NAME') and ( # Check current hostname against server name, ignoring port numbers, if any (split on ':...
python
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 """ if current_app.config.get('SERVER_NAME') and ( # Check current hostname against server name, ignoring port numbers, if any (split on ':...
Return the current URL including the query string as a relative path. If the app uses subdomains, return an absolute path
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/misc.py#L43-L58
hasgeek/coaster
coaster/views/misc.py
get_next_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 functio...
python
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 functio...
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 par...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/misc.py#L64-L96
hasgeek/coaster
coaster/views/misc.py
jsonp
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. """ data = json.dumps(dict(*args, **kw), indent=2) callback = request.args...
python
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. """ data = json.dumps(dict(*args, **kw), indent=2) callback = request.args...
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.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/misc.py#L99-L112
hasgeek/coaster
coaster/views/misc.py
endpoint_for
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) ...
python
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) ...
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...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/views/misc.py#L115-L172
hasgeek/coaster
coaster/docflow.py
DocumentWorkflow.permissions
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. """ perms = set(super(DocumentWorkflow, self).pe...
python
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. """ perms = set(super(DocumentWorkflow, self).pe...
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.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/docflow.py#L71-L84
hasgeek/coaster
coaster/sqlalchemy/annotations.py
__configure_annotations
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__` """ annotations = {} annotations_by_attr = {} # An attribute may ...
python
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__` """ annotations = {} annotations_by_attr = {} # An attribute may ...
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__`
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/annotations.py#L62-L103
hasgeek/coaster
coaster/sqlalchemy/annotations.py
annotation_wrapper
def annotation_wrapper(annotation, doc=None): """ Defines an annotation, which can be applied to attributes in a database model. """ def decorator(attr): __cache__.setdefault(attr, []).append(annotation) # Also mark the annotation on the object itself. This will # fail if the obj...
python
def annotation_wrapper(annotation, doc=None): """ Defines an annotation, which can be applied to attributes in a database model. """ def decorator(attr): __cache__.setdefault(attr, []).append(annotation) # Also mark the annotation on the object itself. This will # fail if the obj...
Defines an annotation, which can be applied to attributes in a database model.
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/annotations.py#L114-L135
hasgeek/coaster
coaster/auth.py
add_auth_attribute
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 i...
python
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 i...
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) ...
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/auth.py#L29-L66
dnephin/PyStaticConfiguration
staticconf/schema.py
SchemaMeta.build_attributes
def build_attributes(cls, attributes, namespace): """Return an attributes dictionary with ValueTokens replaced by a property which returns the config value. """ config_path = attributes.get('config_path') tokens = {} def build_config_key(value_def, config_key): ...
python
def build_attributes(cls, attributes, namespace): """Return an attributes dictionary with ValueTokens replaced by a property which returns the config value. """ config_path = attributes.get('config_path') tokens = {} def build_config_key(value_def, config_key): ...
Return an attributes dictionary with ValueTokens replaced by a property which returns the config value.
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/schema.py#L166-L193
dnephin/PyStaticConfiguration
staticconf/proxy.py
cache_as_field
def cache_as_field(cache_name): """Cache a functions return value as the field 'cache_name'.""" def cache_wrapper(func): @functools.wraps(func) def inner_wrapper(self, *args, **kwargs): value = getattr(self, cache_name, UndefToken) if value != UndefToken: ...
python
def cache_as_field(cache_name): """Cache a functions return value as the field 'cache_name'.""" def cache_wrapper(func): @functools.wraps(func) def inner_wrapper(self, *args, **kwargs): value = getattr(self, cache_name, UndefToken) if value != UndefToken: ...
Cache a functions return value as the field 'cache_name'.
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/proxy.py#L74-L87
dnephin/PyStaticConfiguration
staticconf/proxy.py
extract_value
def extract_value(proxy): """Given a value proxy type, Retrieve a value from a namespace, raising exception if no value is found, or the value does not validate. """ value = proxy.namespace.get(proxy.config_key, proxy.default) if value is UndefToken: raise errors.ConfigurationError("%s is mi...
python
def extract_value(proxy): """Given a value proxy type, Retrieve a value from a namespace, raising exception if no value is found, or the value does not validate. """ value = proxy.namespace.get(proxy.config_key, proxy.default) if value is UndefToken: raise errors.ConfigurationError("%s is mi...
Given a value proxy type, Retrieve a value from a namespace, raising exception if no value is found, or the value does not validate.
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/proxy.py#L90-L103
dnephin/PyStaticConfiguration
staticconf/readers.py
build_reader
def build_reader(validator, reader_namespace=config.DEFAULT): """A factory method for creating a custom config reader from a validation function. :param validator: a validation function which acceptance one argument (the configuration value), and returns that value casted to ...
python
def build_reader(validator, reader_namespace=config.DEFAULT): """A factory method for creating a custom config reader from a validation function. :param validator: a validation function which acceptance one argument (the configuration value), and returns that value casted to ...
A factory method for creating a custom config reader from a validation function. :param validator: a validation function which acceptance one argument (the configuration value), and returns that value casted to the appropriate type. :param reader_namespace: the d...
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/readers.py#L103-L116