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 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'``.
"""
# 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) | 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 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'``.
"""
# 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) | 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'``. | 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 find settings file %s for additional settings, skipping it" % filepath, file=sys.stderr)
return False | 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 find settings file %s for additional settings, skipping it" % filepath, file=sys.stderr)
return False | 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.
"""
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 | 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.
"""
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 | 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 this'&'phrase'"
>>> for_tsquery("This NOT that")
"'This'&!'that'"
>>> for_tsquery("This & NOT that")
"'This'&!'that'"
>>> for_tsquery("This > that")
"'This > that'"
>>> for_tsquery("Ruby AND (Python OR JavaScript)")
"'Ruby'&('Python'|'JavaScript')"
>>> for_tsquery("Ruby AND NOT (Python OR JavaScript)")
"'Ruby'&!('Python'|'JavaScript')"
>>> for_tsquery("Ruby NOT (Python OR JavaScript)")
"'Ruby'&!('Python'|'JavaScript')"
>>> for_tsquery("Ruby (Python OR JavaScript) Golang")
"'Ruby'&('Python'|'JavaScript')&'Golang'"
>>> for_tsquery("Ruby (Python OR JavaScript) NOT Golang")
"'Ruby'&('Python'|'JavaScript')&!'Golang'"
>>> for_tsquery("Java*")
"'Java':*"
>>> for_tsquery("Java**")
"'Java':*"
>>> for_tsquery("Android || Python")
"'Android'|'Python'"
>>> for_tsquery("Missing (bracket")
"'Missing'&('bracket')"
>>> for_tsquery("Extra bracket)")
"('Extra bracket')"
>>> for_tsquery("Android (Python ())")
"'Android'&('Python')"
>>> for_tsquery("Android (Python !())")
"'Android'&('Python')"
>>> for_tsquery("()")
''
>>> for_tsquery("(")
''
>>> for_tsquery("() Python")
"'Python'"
>>> for_tsquery("!() Python")
"'Python'"
>>> for_tsquery("*")
''
>>> for_tsquery("/etc/passwd\x00")
"'/etc/passwd'"
"""
tokens = [_token_map.get(t, t) for t in _tsquery_tokens_re.split(
_whitespace_re.sub(' ', text.replace("'", " ").replace('"', ' ').replace('\0', '')))]
tokens = [t if t in ('&', '|', '!', ':*', '(', ')', ' ') else "'" + t.strip() + "'"
for t in tokens]
tokens = [t for t in tokens if t not in ('', ' ', "''")]
if not tokens:
return ''
counterlength = len(tokens)
counter = 1
while counter < counterlength:
if tokens[counter] == '!' and tokens[counter - 1] not in ('&', '|', '('):
tokens.insert(counter, '&')
counter += 1
counterlength += 1
elif tokens[counter] == '(' and tokens[counter - 1] not in ('&', '|', '!'):
tokens.insert(counter, '&')
counter += 1
counterlength += 1
elif tokens[counter] == ')' and tokens[counter - 1] == '(':
# Empty ()
tokens.pop(counter)
tokens.pop(counter - 1)
counter -= 2
counterlength -= 2
# Pop the join with previous segment too
if tokens and tokens[counter] in ('&', '|'):
tokens.pop(counter)
counter -= 1
counterlength -= 1
elif tokens and counter == 0 and tokens[counter] == '!':
tokens.pop(counter)
counter -= 1
counterlength -= 1
elif tokens and counter > 0 and tokens[counter - 1:counter + 1] in (['&', '!'], ['|', '!']):
tokens.pop(counter)
tokens.pop(counter - 1)
counter -= 2
counterlength -= 2
elif tokens[counter].startswith("'") and tokens[counter - 1] not in ('&', '|', '!', '('):
tokens.insert(counter, '&')
counter += 1
counterlength += 1
elif (
tokens[counter] in ('&', '|') and tokens[counter - 1] in ('&', '|')) or (
tokens[counter] == '!' and tokens[counter - 1] not in ('&', '|')) or (
tokens[counter] == ':*' and not tokens[counter - 1].startswith("'")):
# Invalid token: is a dupe or follows a token it shouldn't follow
tokens.pop(counter)
counter -= 1
counterlength -= 1
counter += 1
while tokens and tokens[0] in ('&', '|', ':*', ')', '!', '*'):
tokens.pop(0) # Can't start with a binary or suffix operator
if tokens:
while tokens and tokens[-1] in ('&', '|', '!', '('):
tokens.pop(-1) # Can't end with a binary or prefix operator
if not tokens:
return '' # Did we just eliminate all tokens?
missing_brackets = sum([1 if t == '(' else -1 for t in tokens if t in ('(', ')')])
if missing_brackets > 0:
tokens.append(')' * missing_brackets)
elif missing_brackets < 0:
tokens.insert(0, '(' * -missing_brackets)
return ''.join(tokens) | 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 this'&'phrase'"
>>> for_tsquery("This NOT that")
"'This'&!'that'"
>>> for_tsquery("This & NOT that")
"'This'&!'that'"
>>> for_tsquery("This > that")
"'This > that'"
>>> for_tsquery("Ruby AND (Python OR JavaScript)")
"'Ruby'&('Python'|'JavaScript')"
>>> for_tsquery("Ruby AND NOT (Python OR JavaScript)")
"'Ruby'&!('Python'|'JavaScript')"
>>> for_tsquery("Ruby NOT (Python OR JavaScript)")
"'Ruby'&!('Python'|'JavaScript')"
>>> for_tsquery("Ruby (Python OR JavaScript) Golang")
"'Ruby'&('Python'|'JavaScript')&'Golang'"
>>> for_tsquery("Ruby (Python OR JavaScript) NOT Golang")
"'Ruby'&('Python'|'JavaScript')&!'Golang'"
>>> for_tsquery("Java*")
"'Java':*"
>>> for_tsquery("Java**")
"'Java':*"
>>> for_tsquery("Android || Python")
"'Android'|'Python'"
>>> for_tsquery("Missing (bracket")
"'Missing'&('bracket')"
>>> for_tsquery("Extra bracket)")
"('Extra bracket')"
>>> for_tsquery("Android (Python ())")
"'Android'&('Python')"
>>> for_tsquery("Android (Python !())")
"'Android'&('Python')"
>>> for_tsquery("()")
''
>>> for_tsquery("(")
''
>>> for_tsquery("() Python")
"'Python'"
>>> for_tsquery("!() Python")
"'Python'"
>>> for_tsquery("*")
''
>>> for_tsquery("/etc/passwd\x00")
"'/etc/passwd'"
"""
tokens = [_token_map.get(t, t) for t in _tsquery_tokens_re.split(
_whitespace_re.sub(' ', text.replace("'", " ").replace('"', ' ').replace('\0', '')))]
tokens = [t if t in ('&', '|', '!', ':*', '(', ')', ' ') else "'" + t.strip() + "'"
for t in tokens]
tokens = [t for t in tokens if t not in ('', ' ', "''")]
if not tokens:
return ''
counterlength = len(tokens)
counter = 1
while counter < counterlength:
if tokens[counter] == '!' and tokens[counter - 1] not in ('&', '|', '('):
tokens.insert(counter, '&')
counter += 1
counterlength += 1
elif tokens[counter] == '(' and tokens[counter - 1] not in ('&', '|', '!'):
tokens.insert(counter, '&')
counter += 1
counterlength += 1
elif tokens[counter] == ')' and tokens[counter - 1] == '(':
# Empty ()
tokens.pop(counter)
tokens.pop(counter - 1)
counter -= 2
counterlength -= 2
# Pop the join with previous segment too
if tokens and tokens[counter] in ('&', '|'):
tokens.pop(counter)
counter -= 1
counterlength -= 1
elif tokens and counter == 0 and tokens[counter] == '!':
tokens.pop(counter)
counter -= 1
counterlength -= 1
elif tokens and counter > 0 and tokens[counter - 1:counter + 1] in (['&', '!'], ['|', '!']):
tokens.pop(counter)
tokens.pop(counter - 1)
counter -= 2
counterlength -= 2
elif tokens[counter].startswith("'") and tokens[counter - 1] not in ('&', '|', '!', '('):
tokens.insert(counter, '&')
counter += 1
counterlength += 1
elif (
tokens[counter] in ('&', '|') and tokens[counter - 1] in ('&', '|')) or (
tokens[counter] == '!' and tokens[counter - 1] not in ('&', '|')) or (
tokens[counter] == ':*' and not tokens[counter - 1].startswith("'")):
# Invalid token: is a dupe or follows a token it shouldn't follow
tokens.pop(counter)
counter -= 1
counterlength -= 1
counter += 1
while tokens and tokens[0] in ('&', '|', ':*', ')', '!', '*'):
tokens.pop(0) # Can't start with a binary or suffix operator
if tokens:
while tokens and tokens[-1] in ('&', '|', '!', '('):
tokens.pop(-1) # Can't end with a binary or prefix operator
if not tokens:
return '' # Did we just eliminate all tokens?
missing_brackets = sum([1 if t == '(' else -1 for t in tokens if t in ('(', ')')])
if missing_brackets > 0:
tokens.append(')' * missing_brackets)
elif missing_brackets < 0:
tokens.insert(0, '(' * -missing_brackets)
return ''.join(tokens) | 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_tsquery("This NOT that")
"'This'&!'that'"
>>> for_tsquery("This & NOT that")
"'This'&!'that'"
>>> for_tsquery("This > that")
"'This > that'"
>>> for_tsquery("Ruby AND (Python OR JavaScript)")
"'Ruby'&('Python'|'JavaScript')"
>>> for_tsquery("Ruby AND NOT (Python OR JavaScript)")
"'Ruby'&!('Python'|'JavaScript')"
>>> for_tsquery("Ruby NOT (Python OR JavaScript)")
"'Ruby'&!('Python'|'JavaScript')"
>>> for_tsquery("Ruby (Python OR JavaScript) Golang")
"'Ruby'&('Python'|'JavaScript')&'Golang'"
>>> for_tsquery("Ruby (Python OR JavaScript) NOT Golang")
"'Ruby'&('Python'|'JavaScript')&!'Golang'"
>>> for_tsquery("Java*")
"'Java':*"
>>> for_tsquery("Java**")
"'Java':*"
>>> for_tsquery("Android || Python")
"'Android'|'Python'"
>>> for_tsquery("Missing (bracket")
"'Missing'&('bracket')"
>>> for_tsquery("Extra bracket)")
"('Extra bracket')"
>>> for_tsquery("Android (Python ())")
"'Android'&('Python')"
>>> for_tsquery("Android (Python !())")
"'Android'&('Python')"
>>> for_tsquery("()")
''
>>> for_tsquery("(")
''
>>> for_tsquery("() Python")
"'Python'"
>>> for_tsquery("!() Python")
"'Python'"
>>> for_tsquery("*")
''
>>> for_tsquery("/etc/passwd\x00")
"'/etc/passwd'" | 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 immutable(Column(Integer, primary_key=True, nullable=False)) | 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 immutable(Column(Integer, primary_key=True, nullable=False)) | 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)
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):
"""The URL id, integer primary key rendered as a string"""
return six.text_type(self.id)
def url_id_expression(cls):
"""The URL id, integer primary key"""
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 | 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)
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):
"""The URL id, integer primary key rendered as a string"""
return six.text_type(self.id)
def url_id_expression(cls):
"""The URL id, integer primary key"""
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 | 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, nullable=False)) | 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, nullable=False)) | 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, 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) | 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, 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) | 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: {}} # 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 | 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: {}} # 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 | 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, attr) | 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, attr) | 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=f, instance_type=self.__class__.__name__)) | 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=f, instance_type=self.__class__.__name__)) | 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_type, nullable=False, unique=True)
else:
return Column(column_type, CheckConstraint("name <> ''"), nullable=False, unique=True) | 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_type, nullable=False, unique=True)
else:
return Column(column_type, CheckConstraint("name <> ''"), nullable=False, unique=True) | 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)
return instance | 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)
return instance | 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 set of reserved names unavailable for use
"""
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)) | 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 set of reserved names unavailable for use
"""
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)) | 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):
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 | 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):
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 | 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(self.parent, PermissionMixin):
return self.parent.permissions(actor) | super(BaseScopedNameMixin, self).permissions(actor)
else:
return super(BaseScopedNameMixin, self).permissions(actor) | 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(self.parent, PermissionMixin):
return self.parent.permissions(actor) | super(BaseScopedNameMixin, self).permissions(actor)
else:
return super(BaseScopedNameMixin, self).permissions(actor) | 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 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
"""
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 | 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 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
"""
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 | 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 | 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 trigger is added as well to ensure foreign key integrity.
A SQLAlchemy relationship named ``parent.childrel`` is added that makes
usage seamless within SQLAlchemy.
The secondary table is named after the parent and child tables, with
``_primary`` appended, in the form ``parent_child_primary``. This table can
be found in the metadata in the ``parent.metadata.tables`` dictionary.
Multi-column primary keys on either parent or child are unsupported at
this time.
:param parent: The parent model (on which this relationship will be added)
:param childrel: The name of the relationship to the child that will be
added
:param child: The child model
:param str parentrel: Name of the existing relationship on the child model
that refers back to the parent model
:param str parentcol: Name of the existing table column on the child model
that refers back to the parent model
:return: None
"""
parent_table_name = parent.__tablename__
child_table_name = child.__tablename__
primary_table_name = parent_table_name + '_' + child_table_name + '_primary'
parent_id_columns = [c.name for c in inspect(parent).primary_key]
child_id_columns = [c.name for c in inspect(child).primary_key]
primary_table_columns = (
[Column(
parent_table_name + '_' + name,
None,
ForeignKey(parent_table_name + '.' + name, ondelete='CASCADE'),
primary_key=True,
nullable=False) for name in parent_id_columns]
+ [Column(
child_table_name + '_' + name,
None,
ForeignKey(child_table_name + '.' + name, ondelete='CASCADE'),
nullable=False) for name in child_id_columns]
+ list(make_timestamp_columns())
)
primary_table = Table(primary_table_name, parent.metadata, *primary_table_columns)
rel = relationship(child, uselist=False, secondary=primary_table)
setattr(parent, childrel, rel)
@event.listens_for(rel, 'set')
def _validate_child(target, value, oldvalue, initiator):
if value and getattr(value, parentrel) != target:
raise ValueError("The target is not affiliated with this parent")
# XXX: To support multi-column primary keys, update this SQL function
event.listen(primary_table, 'after_create',
DDL('''
CREATE FUNCTION %(function)s() RETURNS TRIGGER AS $$
DECLARE
target RECORD;
BEGIN
IF (NEW.%(rhs)s IS NOT NULL) THEN
SELECT %(parentcol)s INTO target FROM %(child_table_name)s WHERE %(child_id_column)s = NEW.%(rhs)s;
IF (target.%(parentcol)s != NEW.%(lhs)s) THEN
RAISE foreign_key_violation USING MESSAGE = 'The target is not affiliated with this parent';
END IF;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER %(trigger)s BEFORE INSERT OR UPDATE
ON %(table)s
FOR EACH ROW EXECUTE PROCEDURE %(function)s();
''',
context={
'table': primary_table_name,
'function': '%s_validate' % primary_table_name,
'trigger': '%s_trigger' % primary_table_name,
'parentcol': parentcol,
'child_table_name': child_table_name,
'child_id_column': child_id_columns[0],
'lhs': '%s_%s' % (parent_table_name, parent_id_columns[0]),
'rhs': '%s_%s' % (child_table_name, child_id_columns[0]),
}
).execute_if(dialect='postgresql')
)
event.listen(primary_table, 'before_drop',
DDL('''
DROP TRIGGER %(trigger)s ON %(table)s;
DROP FUNCTION %(function)s();
''',
context={
'table': primary_table_name,
'trigger': '%s_trigger' % primary_table_name,
'function': '%s_validate' % primary_table_name,
}
).execute_if(dialect='postgresql')
) | 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 trigger is added as well to ensure foreign key integrity.
A SQLAlchemy relationship named ``parent.childrel`` is added that makes
usage seamless within SQLAlchemy.
The secondary table is named after the parent and child tables, with
``_primary`` appended, in the form ``parent_child_primary``. This table can
be found in the metadata in the ``parent.metadata.tables`` dictionary.
Multi-column primary keys on either parent or child are unsupported at
this time.
:param parent: The parent model (on which this relationship will be added)
:param childrel: The name of the relationship to the child that will be
added
:param child: The child model
:param str parentrel: Name of the existing relationship on the child model
that refers back to the parent model
:param str parentcol: Name of the existing table column on the child model
that refers back to the parent model
:return: None
"""
parent_table_name = parent.__tablename__
child_table_name = child.__tablename__
primary_table_name = parent_table_name + '_' + child_table_name + '_primary'
parent_id_columns = [c.name for c in inspect(parent).primary_key]
child_id_columns = [c.name for c in inspect(child).primary_key]
primary_table_columns = (
[Column(
parent_table_name + '_' + name,
None,
ForeignKey(parent_table_name + '.' + name, ondelete='CASCADE'),
primary_key=True,
nullable=False) for name in parent_id_columns]
+ [Column(
child_table_name + '_' + name,
None,
ForeignKey(child_table_name + '.' + name, ondelete='CASCADE'),
nullable=False) for name in child_id_columns]
+ list(make_timestamp_columns())
)
primary_table = Table(primary_table_name, parent.metadata, *primary_table_columns)
rel = relationship(child, uselist=False, secondary=primary_table)
setattr(parent, childrel, rel)
@event.listens_for(rel, 'set')
def _validate_child(target, value, oldvalue, initiator):
if value and getattr(value, parentrel) != target:
raise ValueError("The target is not affiliated with this parent")
# XXX: To support multi-column primary keys, update this SQL function
event.listen(primary_table, 'after_create',
DDL('''
CREATE FUNCTION %(function)s() RETURNS TRIGGER AS $$
DECLARE
target RECORD;
BEGIN
IF (NEW.%(rhs)s IS NOT NULL) THEN
SELECT %(parentcol)s INTO target FROM %(child_table_name)s WHERE %(child_id_column)s = NEW.%(rhs)s;
IF (target.%(parentcol)s != NEW.%(lhs)s) THEN
RAISE foreign_key_violation USING MESSAGE = 'The target is not affiliated with this parent';
END IF;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER %(trigger)s BEFORE INSERT OR UPDATE
ON %(table)s
FOR EACH ROW EXECUTE PROCEDURE %(function)s();
''',
context={
'table': primary_table_name,
'function': '%s_validate' % primary_table_name,
'trigger': '%s_trigger' % primary_table_name,
'parentcol': parentcol,
'child_table_name': child_table_name,
'child_id_column': child_id_columns[0],
'lhs': '%s_%s' % (parent_table_name, parent_id_columns[0]),
'rhs': '%s_%s' % (child_table_name, child_id_columns[0]),
}
).execute_if(dialect='postgresql')
)
event.listen(primary_table, 'before_drop',
DDL('''
DROP TRIGGER %(trigger)s ON %(table)s;
DROP FUNCTION %(function)s();
''',
context={
'table': primary_table_name,
'trigger': '%s_trigger' % primary_table_name,
'function': '%s_validate' % primary_table_name,
}
).execute_if(dialect='postgresql')
) | 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 named ``parent.childrel`` is added that makes
usage seamless within SQLAlchemy.
The secondary table is named after the parent and child tables, with
``_primary`` appended, in the form ``parent_child_primary``. This table can
be found in the metadata in the ``parent.metadata.tables`` dictionary.
Multi-column primary keys on either parent or child are unsupported at
this time.
:param parent: The parent model (on which this relationship will be added)
:param childrel: The name of the relationship to the child that will be
added
:param child: The child model
:param str parentrel: Name of the existing relationship on the child model
that refers back to the parent model
:param str parentcol: Name of the existing table column on the child model
that refers back to the parent model
:return: None | 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, '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 | 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, '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 | 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 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])
"""
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 | 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 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])
"""
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 | 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]) | 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 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
"""
return load_models((model, attributes, parameter),
kwargs=kwargs, permission=permission, addlperms=addlperms, urlcheck=urlcheck) | 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 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
"""
return load_models((model, attributes, parameter),
kwargs=kwargs, permission=permission, addlperms=addlperms, urlcheck=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 | 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``).
Lists and tuples can be used interchangeably. All retrieved instances are passed as
parameters to the decorated function
:param permission: Same as in :func:`load_model`, except
:meth:`~coaster.sqlalchemy.PermissionMixin.permissions` is called on every instance
in the chain and the retrieved permissions are passed as the second parameter to the
next instance in the chain. This allows later instances to revoke permissions granted
by earlier instances. As an example, if a URL represents a hierarchy such as
``/<page>/<comment>``, the ``page`` can assign ``edit`` and ``delete`` permissions,
while the ``comment`` can revoke ``edit`` and retain ``delete`` if the current user
owns the page but not the comment
In the following example, load_models loads a Folder with a name matching the name in the
URL, then loads a Page with a matching name and with the just-loaded Folder as parent.
If the Page provides a 'view' permission to the current user, the decorated
function is called::
@app.route('/<folder_name>/<page_name>')
@load_models(
(Folder, {'name': 'folder_name'}, 'folder'),
(Page, {'name': 'page_name', 'parent': 'folder'}, 'page'),
permission='view')
def show_page(folder, page):
return render_template('page.html', folder=folder, page=page)
"""
def inner(f):
@wraps(f)
def decorated_function(*args, **kw):
permissions = None
permission_required = kwargs.get('permission')
url_check_attributes = kwargs.get('urlcheck', [])
if isinstance(permission_required, six.string_types):
permission_required = set([permission_required])
elif permission_required is not None:
permission_required = set(permission_required)
result = {}
for models, attributes, parameter in chain:
if not isinstance(models, (list, tuple)):
models = (models,)
item = None
for model in models:
query = model.query
url_check = False
url_check_paramvalues = {}
for k, v in attributes.items():
if callable(v):
query = query.filter_by(**{k: v(result, kw)})
else:
if '.' in v:
first, attrs = v.split('.', 1)
val = result.get(first)
for attr in attrs.split('.'):
val = getattr(val, attr)
else:
val = result.get(v, kw.get(v))
query = query.filter_by(**{k: val})
if k in url_check_attributes:
url_check = True
url_check_paramvalues[k] = (v, val)
item = query.first()
if item is not None:
# We found it, so don't look in additional models
break
if item is None:
abort(404)
if hasattr(item, 'redirect_view_args'):
# This item is a redirect object. Redirect to destination
view_args = dict(request.view_args)
view_args.update(item.redirect_view_args())
location = url_for(request.endpoint, **view_args)
if request.query_string:
location = location + u'?' + request.query_string.decode()
return redirect(location, code=307)
if permission_required:
permissions = item.permissions(current_auth.actor, inherited=permissions)
addlperms = kwargs.get('addlperms') or []
if callable(addlperms):
addlperms = addlperms() or []
permissions.update(addlperms)
if g: # XXX: Deprecated
g.permissions = permissions
if request:
add_auth_attribute('permissions', permissions)
if url_check and request.method == 'GET': # Only do urlcheck redirects on GET requests
url_redirect = False
view_args = None
for k, v in url_check_paramvalues.items():
uparam, uvalue = v
if getattr(item, k) != uvalue:
url_redirect = True
if view_args is None:
view_args = dict(request.view_args)
view_args[uparam] = getattr(item, k)
if url_redirect:
location = url_for(request.endpoint, **view_args)
if request.query_string:
location = location + u'?' + request.query_string.decode()
return redirect(location, code=302)
if parameter.startswith('g.'):
parameter = parameter[2:]
setattr(g, parameter, item)
result[parameter] = item
if permission_required and not permission_required & permissions:
abort(403)
if kwargs.get('kwargs'):
return f(*args, kwargs=kw, **result)
else:
return f(*args, **result)
return decorated_function
return inner | 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``).
Lists and tuples can be used interchangeably. All retrieved instances are passed as
parameters to the decorated function
:param permission: Same as in :func:`load_model`, except
:meth:`~coaster.sqlalchemy.PermissionMixin.permissions` is called on every instance
in the chain and the retrieved permissions are passed as the second parameter to the
next instance in the chain. This allows later instances to revoke permissions granted
by earlier instances. As an example, if a URL represents a hierarchy such as
``/<page>/<comment>``, the ``page`` can assign ``edit`` and ``delete`` permissions,
while the ``comment`` can revoke ``edit`` and retain ``delete`` if the current user
owns the page but not the comment
In the following example, load_models loads a Folder with a name matching the name in the
URL, then loads a Page with a matching name and with the just-loaded Folder as parent.
If the Page provides a 'view' permission to the current user, the decorated
function is called::
@app.route('/<folder_name>/<page_name>')
@load_models(
(Folder, {'name': 'folder_name'}, 'folder'),
(Page, {'name': 'page_name', 'parent': 'folder'}, 'page'),
permission='view')
def show_page(folder, page):
return render_template('page.html', folder=folder, page=page)
"""
def inner(f):
@wraps(f)
def decorated_function(*args, **kw):
permissions = None
permission_required = kwargs.get('permission')
url_check_attributes = kwargs.get('urlcheck', [])
if isinstance(permission_required, six.string_types):
permission_required = set([permission_required])
elif permission_required is not None:
permission_required = set(permission_required)
result = {}
for models, attributes, parameter in chain:
if not isinstance(models, (list, tuple)):
models = (models,)
item = None
for model in models:
query = model.query
url_check = False
url_check_paramvalues = {}
for k, v in attributes.items():
if callable(v):
query = query.filter_by(**{k: v(result, kw)})
else:
if '.' in v:
first, attrs = v.split('.', 1)
val = result.get(first)
for attr in attrs.split('.'):
val = getattr(val, attr)
else:
val = result.get(v, kw.get(v))
query = query.filter_by(**{k: val})
if k in url_check_attributes:
url_check = True
url_check_paramvalues[k] = (v, val)
item = query.first()
if item is not None:
# We found it, so don't look in additional models
break
if item is None:
abort(404)
if hasattr(item, 'redirect_view_args'):
# This item is a redirect object. Redirect to destination
view_args = dict(request.view_args)
view_args.update(item.redirect_view_args())
location = url_for(request.endpoint, **view_args)
if request.query_string:
location = location + u'?' + request.query_string.decode()
return redirect(location, code=307)
if permission_required:
permissions = item.permissions(current_auth.actor, inherited=permissions)
addlperms = kwargs.get('addlperms') or []
if callable(addlperms):
addlperms = addlperms() or []
permissions.update(addlperms)
if g: # XXX: Deprecated
g.permissions = permissions
if request:
add_auth_attribute('permissions', permissions)
if url_check and request.method == 'GET': # Only do urlcheck redirects on GET requests
url_redirect = False
view_args = None
for k, v in url_check_paramvalues.items():
uparam, uvalue = v
if getattr(item, k) != uvalue:
url_redirect = True
if view_args is None:
view_args = dict(request.view_args)
view_args[uparam] = getattr(item, k)
if url_redirect:
location = url_for(request.endpoint, **view_args)
if request.query_string:
location = location + u'?' + request.query_string.decode()
return redirect(location, code=302)
if parameter.startswith('g.'):
parameter = parameter[2:]
setattr(g, parameter, item)
result[parameter] = item
if permission_required and not permission_required & permissions:
abort(403)
if kwargs.get('kwargs'):
return f(*args, kwargs=kw, **result)
else:
return f(*args, **result)
return decorated_function
return inner | 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. All retrieved instances are passed as
parameters to the decorated function
:param permission: Same as in :func:`load_model`, except
:meth:`~coaster.sqlalchemy.PermissionMixin.permissions` is called on every instance
in the chain and the retrieved permissions are passed as the second parameter to the
next instance in the chain. This allows later instances to revoke permissions granted
by earlier instances. As an example, if a URL represents a hierarchy such as
``/<page>/<comment>``, the ``page`` can assign ``edit`` and ``delete`` permissions,
while the ``comment`` can revoke ``edit`` and retain ``delete`` if the current user
owns the page but not the comment
In the following example, load_models loads a Folder with a name matching the name in the
URL, then loads a Page with a matching name and with the just-loaded Folder as parent.
If the Page provides a 'view' permission to the current user, the decorated
function is called::
@app.route('/<folder_name>/<page_name>')
@load_models(
(Folder, {'name': 'folder_name'}, 'folder'),
(Page, {'name': 'page_name', 'parent': 'folder'}, 'page'),
permission='view')
def show_page(folder, page):
return render_template('page.html', folder=folder, page=page) | 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
a dictionary and is passed to the template as parameters. Callable templates get
a single parameter with the function's return value. Usage::
@app.route('/myview')
@render_with('myview.html')
def myview():
return {'data': 'value'}
@app.route('/myview_with_json')
@render_with('myview.html', json=True)
def myview_no_json():
return {'data': 'value'}
@app.route('/otherview')
@render_with({
'text/html': 'otherview.html',
'text/xml': 'otherview.xml'})
def otherview():
return {'data': 'value'}
@app.route('/404view')
@render_with('myview.html')
def myview():
return {'error': '404 Not Found'}, 404
@app.route('/headerview')
@render_with('myview.html')
def myview():
return {'data': 'value'}, 200, {'X-Header': 'Header value'}
When a mimetype is specified and the template is not a callable, the response is
returned with the same mimetype. Callable templates must return Response objects
to ensure the correct mimetype is set.
If a dictionary of templates is provided and does not include a handler for ``*/*``,
render_with will attempt to use the handler for (in order) ``text/html``, ``text/plain``
and the various JSON types, falling back to rendering the value into a unicode string.
If the method is called outside a request context, the wrapped method's original
return value is returned. This is meant to facilitate testing and should not be
used to call the method from within another view handler as the presence of a
request context will trigger template rendering.
Rendering may also be suspended by calling the view handler with ``_render=False``.
render_with provides JSON and JSONP handlers for the ``application/json``,
``text/json`` and ``text/x-json`` mimetypes if ``json`` or ``jsonp`` is True
(default is False).
:param template: Single template, or dictionary of MIME type to templates. If the
template is a callable, it is called with the output of the wrapped function
:param json: Helper to add a JSON handler (default is False)
:param jsonp: Helper to add a JSONP handler (if True, also provides JSON, default is False)
"""
if jsonp:
templates = {
'application/json': dict_jsonp,
'application/javascript': dict_jsonp,
}
elif json:
templates = {
'application/json': dict_jsonify,
}
else:
templates = {}
if isinstance(template, six.string_types):
templates['text/html'] = template
elif isinstance(template, dict):
templates.update(template)
elif template is None and (json or jsonp):
pass
else: # pragma: no cover
raise ValueError("Expected string or dict for template")
default_mimetype = '*/*'
if '*/*' not in templates:
templates['*/*'] = six.text_type
default_mimetype = 'text/plain'
for mimetype in ('text/html', 'text/plain', 'application/json'):
if mimetype in templates:
templates['*/*'] = templates[mimetype]
default_mimetype = mimetype # Remember which mimetype's handler is serving for */*
break
template_mimetypes = list(templates.keys())
template_mimetypes.remove('*/*') # */* messes up matching, so supply it only as last resort
def inner(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# Check if we need to bypass rendering
render = kwargs.pop('_render', True)
# Get the result
result = f(*args, **kwargs)
# Is the result a Response object? Don't attempt rendering
if isinstance(result, (Response, WerkzeugResponse, current_app.response_class)):
return result
# Did the result include status code and headers?
if isinstance(result, tuple):
resultset = result
result = resultset[0]
if len(resultset) > 1:
status_code = resultset[1]
else:
status_code = None
if len(resultset) > 2:
headers = Headers(resultset[2])
else:
headers = Headers()
else:
status_code = None
headers = Headers()
if len(templates) > 1: # If we have more than one template handler
if 'Vary' in headers:
vary_values = [item.strip() for item in headers['Vary'].split(',')]
if 'Accept' not in vary_values:
vary_values.append('Accept')
headers['Vary'] = ', '.join(vary_values)
else:
headers['Vary'] = 'Accept'
# Find a matching mimetype between Accept headers and available templates
use_mimetype = None
if render and request:
# We do not use request.accept_mimetypes.best_match because it turns out to
# be buggy: it returns the least match instead of the best match.
# use_mimetype = request.accept_mimetypes.best_match(template_mimetypes, '*/*')
use_mimetype = _best_mimetype_match(template_mimetypes, request.accept_mimetypes, '*/*')
# Now render the result with the template for the mimetype
if use_mimetype is not None:
if callable(templates[use_mimetype]):
rendered = templates[use_mimetype](result)
if isinstance(rendered, Response):
if status_code is not None:
rendered.status_code = status_code
if headers is not None:
rendered.headers.extend(headers)
else:
rendered = current_app.response_class(
rendered,
status=status_code,
headers=headers,
mimetype=default_mimetype if use_mimetype == '*/*' else use_mimetype)
else: # Not a callable mimetype. Render as a jinja2 template
rendered = current_app.response_class(
render_template(templates[use_mimetype], **result),
status=status_code or 200, headers=headers,
mimetype=default_mimetype if use_mimetype == '*/*' else use_mimetype)
return rendered
else:
return result
return decorated_function
return inner | 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
a dictionary and is passed to the template as parameters. Callable templates get
a single parameter with the function's return value. Usage::
@app.route('/myview')
@render_with('myview.html')
def myview():
return {'data': 'value'}
@app.route('/myview_with_json')
@render_with('myview.html', json=True)
def myview_no_json():
return {'data': 'value'}
@app.route('/otherview')
@render_with({
'text/html': 'otherview.html',
'text/xml': 'otherview.xml'})
def otherview():
return {'data': 'value'}
@app.route('/404view')
@render_with('myview.html')
def myview():
return {'error': '404 Not Found'}, 404
@app.route('/headerview')
@render_with('myview.html')
def myview():
return {'data': 'value'}, 200, {'X-Header': 'Header value'}
When a mimetype is specified and the template is not a callable, the response is
returned with the same mimetype. Callable templates must return Response objects
to ensure the correct mimetype is set.
If a dictionary of templates is provided and does not include a handler for ``*/*``,
render_with will attempt to use the handler for (in order) ``text/html``, ``text/plain``
and the various JSON types, falling back to rendering the value into a unicode string.
If the method is called outside a request context, the wrapped method's original
return value is returned. This is meant to facilitate testing and should not be
used to call the method from within another view handler as the presence of a
request context will trigger template rendering.
Rendering may also be suspended by calling the view handler with ``_render=False``.
render_with provides JSON and JSONP handlers for the ``application/json``,
``text/json`` and ``text/x-json`` mimetypes if ``json`` or ``jsonp`` is True
(default is False).
:param template: Single template, or dictionary of MIME type to templates. If the
template is a callable, it is called with the output of the wrapped function
:param json: Helper to add a JSON handler (default is False)
:param jsonp: Helper to add a JSONP handler (if True, also provides JSON, default is False)
"""
if jsonp:
templates = {
'application/json': dict_jsonp,
'application/javascript': dict_jsonp,
}
elif json:
templates = {
'application/json': dict_jsonify,
}
else:
templates = {}
if isinstance(template, six.string_types):
templates['text/html'] = template
elif isinstance(template, dict):
templates.update(template)
elif template is None and (json or jsonp):
pass
else: # pragma: no cover
raise ValueError("Expected string or dict for template")
default_mimetype = '*/*'
if '*/*' not in templates:
templates['*/*'] = six.text_type
default_mimetype = 'text/plain'
for mimetype in ('text/html', 'text/plain', 'application/json'):
if mimetype in templates:
templates['*/*'] = templates[mimetype]
default_mimetype = mimetype # Remember which mimetype's handler is serving for */*
break
template_mimetypes = list(templates.keys())
template_mimetypes.remove('*/*') # */* messes up matching, so supply it only as last resort
def inner(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# Check if we need to bypass rendering
render = kwargs.pop('_render', True)
# Get the result
result = f(*args, **kwargs)
# Is the result a Response object? Don't attempt rendering
if isinstance(result, (Response, WerkzeugResponse, current_app.response_class)):
return result
# Did the result include status code and headers?
if isinstance(result, tuple):
resultset = result
result = resultset[0]
if len(resultset) > 1:
status_code = resultset[1]
else:
status_code = None
if len(resultset) > 2:
headers = Headers(resultset[2])
else:
headers = Headers()
else:
status_code = None
headers = Headers()
if len(templates) > 1: # If we have more than one template handler
if 'Vary' in headers:
vary_values = [item.strip() for item in headers['Vary'].split(',')]
if 'Accept' not in vary_values:
vary_values.append('Accept')
headers['Vary'] = ', '.join(vary_values)
else:
headers['Vary'] = 'Accept'
# Find a matching mimetype between Accept headers and available templates
use_mimetype = None
if render and request:
# We do not use request.accept_mimetypes.best_match because it turns out to
# be buggy: it returns the least match instead of the best match.
# use_mimetype = request.accept_mimetypes.best_match(template_mimetypes, '*/*')
use_mimetype = _best_mimetype_match(template_mimetypes, request.accept_mimetypes, '*/*')
# Now render the result with the template for the mimetype
if use_mimetype is not None:
if callable(templates[use_mimetype]):
rendered = templates[use_mimetype](result)
if isinstance(rendered, Response):
if status_code is not None:
rendered.status_code = status_code
if headers is not None:
rendered.headers.extend(headers)
else:
rendered = current_app.response_class(
rendered,
status=status_code,
headers=headers,
mimetype=default_mimetype if use_mimetype == '*/*' else use_mimetype)
else: # Not a callable mimetype. Render as a jinja2 template
rendered = current_app.response_class(
render_template(templates[use_mimetype], **result),
status=status_code or 200, headers=headers,
mimetype=default_mimetype if use_mimetype == '*/*' else use_mimetype)
return rendered
else:
return result
return decorated_function
return inner | 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 templates get
a single parameter with the function's return value. Usage::
@app.route('/myview')
@render_with('myview.html')
def myview():
return {'data': 'value'}
@app.route('/myview_with_json')
@render_with('myview.html', json=True)
def myview_no_json():
return {'data': 'value'}
@app.route('/otherview')
@render_with({
'text/html': 'otherview.html',
'text/xml': 'otherview.xml'})
def otherview():
return {'data': 'value'}
@app.route('/404view')
@render_with('myview.html')
def myview():
return {'error': '404 Not Found'}, 404
@app.route('/headerview')
@render_with('myview.html')
def myview():
return {'data': 'value'}, 200, {'X-Header': 'Header value'}
When a mimetype is specified and the template is not a callable, the response is
returned with the same mimetype. Callable templates must return Response objects
to ensure the correct mimetype is set.
If a dictionary of templates is provided and does not include a handler for ``*/*``,
render_with will attempt to use the handler for (in order) ``text/html``, ``text/plain``
and the various JSON types, falling back to rendering the value into a unicode string.
If the method is called outside a request context, the wrapped method's original
return value is returned. This is meant to facilitate testing and should not be
used to call the method from within another view handler as the presence of a
request context will trigger template rendering.
Rendering may also be suspended by calling the view handler with ``_render=False``.
render_with provides JSON and JSONP handlers for the ``application/json``,
``text/json`` and ``text/x-json`` mimetypes if ``json`` or ``jsonp`` is True
(default is False).
:param template: Single template, or dictionary of MIME type to templates. If the
template is a callable, it is called with the output of the wrapped function
:param json: Helper to add a JSON handler (default is False)
:param jsonp: Helper to add a JSONP handler (if True, also provides JSON, default is False) | 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 (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()
"""
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 | 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 (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()
"""
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 | 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() | 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 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
"""
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 | 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 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
"""
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 | 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 | 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_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
"""
return not isinstance(item, six.string_types) and isinstance(item, (collections.Set, collections.Sequence)) | 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_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
"""
return not isinstance(item, six.string_types) and isinstance(item, (collections.Set, collections.Sequence)) | 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 | 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
"""
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('=')) | 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
"""
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('=')) | 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 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
"""
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)) | 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 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
"""
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)) | 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 | 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:
return six.text_type(urlsafe_b64encode(value.bytes).rstrip('=')) | 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:
return six.text_type(urlsafe_b64encode(value.bytes).rstrip('=')) | 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 = randint(0, 10 ** digits)
return (u'%%0%dd' % digits) % randnum | 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 = randint(0, 10 ** digits)
return (u'%%0%dd' % digits) % randnum | 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 string delim: Delimiter between words, default '-'
:param int maxlength: Maximum length of name, default 50
:param checkused: Function to check if a generated name is available for use
:param int counter: Starting position for name counter
>>> make_name('This is a title')
'this-is-a-title'
>>> make_name('Invalid URL/slug here')
'invalid-url-slug-here'
>>> make_name('this.that')
'this-that'
>>> make_name('this:that')
'this-that'
>>> make_name("How 'bout this?")
'how-bout-this'
>>> make_name(u"How’s that?")
'hows-that'
>>> make_name(u'K & D')
'k-d'
>>> make_name('billion+ pageviews')
'billion-pageviews'
>>> make_name(u'हिन्दी slug!')
'hindii-slug'
>>> make_name(u'Your webapps should talk not just in English, but in español, Kiswahili, 廣州話 and অসমীয়া too.', maxlength=250)
u'your-webapps-should-talk-not-just-in-english-but-in-espanol-kiswahili-guang-zhou-hua-and-asmiiyaa-too'
>>> make_name(u'__name__', delim=u'_')
'name'
>>> make_name(u'how_about_this', delim=u'_')
'how_about_this'
>>> make_name(u'and-that', delim=u'_')
'and_that'
>>> make_name(u'Umlauts in Mötörhead')
'umlauts-in-motorhead'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate'])
'candidate2'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate'], counter=1)
'candidate1'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate', 'candidate1', 'candidate2'], counter=1)
'candidate3'
>>> make_name('Long title, but snipped', maxlength=20)
'long-title-but-snipp'
>>> len(make_name('Long title, but snipped', maxlength=20))
20
>>> make_name('Long candidate', maxlength=10, checkused=lambda c: c in ['long-candi', 'long-cand1'])
'long-cand2'
>>> make_name(u'Lǝnkǝran')
'lankaran'
>>> make_name(u'[email protected]')
'example-example-com'
>>> make_name('trailing-delimiter', maxlength=10)
'trailing-d'
>>> make_name('trailing-delimiter', maxlength=9)
'trailing'
>>> make_name('''test this
... newline''')
'test-this-newline'
>>> make_name(u"testing an emoji😁")
u'testing-an-emoji'
>>> make_name('''testing\\t\\nmore\\r\\nslashes''')
'testing-more-slashes'
>>> make_name('What if a HTML <tag/>')
'what-if-a-html-tag'
>>> make_name('These are equivalent to \\x01 through \\x1A')
'these-are-equivalent-to-through'
"""
name = text.replace('@', delim)
name = unidecode(name).replace('@', 'a') # We don't know why unidecode uses '@' for 'a'-like chars
name = six.text_type(delim.join([_strip_re.sub('', x) for x in _punctuation_re.split(name.lower()) if x != '']))
if isinstance(text, six.text_type):
# Unidecode returns str. Restore to a unicode string if original was unicode
name = six.text_type(name)
candidate = name[:maxlength]
if candidate.endswith(delim):
candidate = candidate[:-1]
if checkused is None:
return candidate
existing = checkused(candidate)
while existing:
candidate = name[:maxlength - len(str(counter))] + str(counter)
counter += 1
existing = checkused(candidate)
return candidate | 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 string delim: Delimiter between words, default '-'
:param int maxlength: Maximum length of name, default 50
:param checkused: Function to check if a generated name is available for use
:param int counter: Starting position for name counter
>>> make_name('This is a title')
'this-is-a-title'
>>> make_name('Invalid URL/slug here')
'invalid-url-slug-here'
>>> make_name('this.that')
'this-that'
>>> make_name('this:that')
'this-that'
>>> make_name("How 'bout this?")
'how-bout-this'
>>> make_name(u"How’s that?")
'hows-that'
>>> make_name(u'K & D')
'k-d'
>>> make_name('billion+ pageviews')
'billion-pageviews'
>>> make_name(u'हिन्दी slug!')
'hindii-slug'
>>> make_name(u'Your webapps should talk not just in English, but in español, Kiswahili, 廣州話 and অসমীয়া too.', maxlength=250)
u'your-webapps-should-talk-not-just-in-english-but-in-espanol-kiswahili-guang-zhou-hua-and-asmiiyaa-too'
>>> make_name(u'__name__', delim=u'_')
'name'
>>> make_name(u'how_about_this', delim=u'_')
'how_about_this'
>>> make_name(u'and-that', delim=u'_')
'and_that'
>>> make_name(u'Umlauts in Mötörhead')
'umlauts-in-motorhead'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate'])
'candidate2'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate'], counter=1)
'candidate1'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate', 'candidate1', 'candidate2'], counter=1)
'candidate3'
>>> make_name('Long title, but snipped', maxlength=20)
'long-title-but-snipp'
>>> len(make_name('Long title, but snipped', maxlength=20))
20
>>> make_name('Long candidate', maxlength=10, checkused=lambda c: c in ['long-candi', 'long-cand1'])
'long-cand2'
>>> make_name(u'Lǝnkǝran')
'lankaran'
>>> make_name(u'[email protected]')
'example-example-com'
>>> make_name('trailing-delimiter', maxlength=10)
'trailing-d'
>>> make_name('trailing-delimiter', maxlength=9)
'trailing'
>>> make_name('''test this
... newline''')
'test-this-newline'
>>> make_name(u"testing an emoji😁")
u'testing-an-emoji'
>>> make_name('''testing\\t\\nmore\\r\\nslashes''')
'testing-more-slashes'
>>> make_name('What if a HTML <tag/>')
'what-if-a-html-tag'
>>> make_name('These are equivalent to \\x01 through \\x1A')
'these-are-equivalent-to-through'
"""
name = text.replace('@', delim)
name = unidecode(name).replace('@', 'a') # We don't know why unidecode uses '@' for 'a'-like chars
name = six.text_type(delim.join([_strip_re.sub('', x) for x in _punctuation_re.split(name.lower()) if x != '']))
if isinstance(text, six.text_type):
# Unidecode returns str. Restore to a unicode string if original was unicode
name = six.text_type(name)
candidate = name[:maxlength]
if candidate.endswith(delim):
candidate = candidate[:-1]
if checkused is None:
return candidate
existing = checkused(candidate)
while existing:
candidate = name[:maxlength - len(str(counter))] + str(counter)
counter += 1
existing = checkused(candidate)
return candidate | 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: Maximum length of name, default 50
:param checkused: Function to check if a generated name is available for use
:param int counter: Starting position for name counter
>>> make_name('This is a title')
'this-is-a-title'
>>> make_name('Invalid URL/slug here')
'invalid-url-slug-here'
>>> make_name('this.that')
'this-that'
>>> make_name('this:that')
'this-that'
>>> make_name("How 'bout this?")
'how-bout-this'
>>> make_name(u"How’s that?")
'hows-that'
>>> make_name(u'K & D')
'k-d'
>>> make_name('billion+ pageviews')
'billion-pageviews'
>>> make_name(u'हिन्दी slug!')
'hindii-slug'
>>> make_name(u'Your webapps should talk not just in English, but in español, Kiswahili, 廣州話 and অসমীয়া too.', maxlength=250)
u'your-webapps-should-talk-not-just-in-english-but-in-espanol-kiswahili-guang-zhou-hua-and-asmiiyaa-too'
>>> make_name(u'__name__', delim=u'_')
'name'
>>> make_name(u'how_about_this', delim=u'_')
'how_about_this'
>>> make_name(u'and-that', delim=u'_')
'and_that'
>>> make_name(u'Umlauts in Mötörhead')
'umlauts-in-motorhead'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate'])
'candidate2'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate'], counter=1)
'candidate1'
>>> make_name('Candidate', checkused=lambda c: c in ['candidate', 'candidate1', 'candidate2'], counter=1)
'candidate3'
>>> make_name('Long title, but snipped', maxlength=20)
'long-title-but-snipp'
>>> len(make_name('Long title, but snipped', maxlength=20))
20
>>> make_name('Long candidate', maxlength=10, checkused=lambda c: c in ['long-candi', 'long-cand1'])
'long-cand2'
>>> make_name(u'Lǝnkǝran')
'lankaran'
>>> make_name(u'[email protected]')
'example-example-com'
>>> make_name('trailing-delimiter', maxlength=10)
'trailing-d'
>>> make_name('trailing-delimiter', maxlength=9)
'trailing'
>>> make_name('''test this
... newline''')
'test-this-newline'
>>> make_name(u"testing an emoji😁")
u'testing-an-emoji'
>>> make_name('''testing\\t\\nmore\\r\\nslashes''')
'testing-more-slashes'
>>> make_name('What if a HTML <tag/>')
'what-if-a-html-tag'
>>> make_name('These are equivalent to \\x01 through \\x1A')
'these-are-equivalent-to-through' | 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_password('foo') == make_password('foo')
False
"""
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 | 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_password('foo') == make_password('foo')
False
"""
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 | 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-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
"""
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 | 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-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
"""
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 | 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 | 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'
>>> 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'
"""
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 | 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'
>>> 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'
"""
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 | 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' | 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 hashlib.md5(data.encode('utf-8')).hexdigest()
else: # pragma: no cover
return hashlib.md5(data).hexdigest() | 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 hashlib.md5(data.encode('utf-8')).hexdigest()
else: # pragma: no cover
return hashlib.md5(data).hexdigest() | 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, 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>)
"""
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 | 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, 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>)
"""
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 | 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>) | 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/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>)
"""
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 | 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/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>)
"""
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 | 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>) | 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)
>>> getbool(0)
False
>>> getbool(False)
False
>>> getbool('n')
False
"""
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 | 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)
>>> getbool(0)
False
>>> getbool(False)
False
>>> getbool('n')
False
"""
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 | 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 | 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):
# 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
"""
# 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] | 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):
# 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
"""
# 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] | 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 | 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=F6stal?=') == u'p\xf6stal'
True
>>> unicode_http_header('p\xf6stal') == u'p\xf6stal'
True
"""
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)]) | 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=F6stal?=') == u'p\xf6stal'
True
>>> unicode_http_header('p\xf6stal') == u'p\xf6stal'
True
"""
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)]) | 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 | 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('[email protected]')
'example.com'
>>> get_email_domain('[email protected]')
'example.com'
>>> get_email_domain('Example Address <[email protected]>')
'example.com'
>>> get_email_domain('foobar')
>>> get_email_domain('foo@bar@baz')
'bar'
>>> get_email_domain('foobar@')
>>> get_email_domain('@foobar')
"""
realname, address = email.utils.parseaddr(emailaddr)
try:
username, domain = address.split('@')
if not username:
return None
return domain or None
except ValueError:
return None | 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('[email protected]')
'example.com'
>>> get_email_domain('[email protected]')
'example.com'
>>> get_email_domain('Example Address <[email protected]>')
'example.com'
>>> get_email_domain('foobar')
>>> get_email_domain('foo@bar@baz')
'bar'
>>> get_email_domain('foobar@')
>>> get_email_domain('@foobar')
"""
realname, address = email.utils.parseaddr(emailaddr)
try:
username, domain = address.split('@')
if not username:
return None
return domain or None
except ValueError:
return None | Return the domain component of an email address. Returns None if the
provided string cannot be parsed as an email address.
>>> get_email_domain('[email protected]')
'example.com'
>>> get_email_domain('[email protected]')
'example.com'
>>> get_email_domain('Example Address <[email protected]>')
'example.com'
>>> get_email_domain('foobar')
>>> get_email_domain('foo@bar@baz')
'bar'
>>> get_email_domain('foobar@')
>>> get_email_domain('@foobar') | 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 = 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] | 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 = 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] | 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.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)) | 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.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)) | 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')
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('[email protected]', 'example.com')
True
"""
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 | 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')
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('[email protected]', 'example.com')
True
"""
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 | 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('[email protected]', 'example.com')
True | 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, **kwargs),
Column(name + '_html', UnicodeText, **kwargs),
deferred=deferred, group=group or name
) | 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, **kwargs),
Column(name + '_html', UnicodeText, **kwargs),
deferred=deferred, group=group or name
) | 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
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 | 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
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 | 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
in self._require_recursive(*not_blacklist) if name not in blacklist]) | 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
in self._require_recursive(*not_blacklist) if name not in blacklist]) | 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():
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) | 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():
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) | 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 groups.
:param str name: Name of this group
:param states: :class:`ManagedState` instances to be grouped together
"""
# 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) | 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 groups.
:param str name: Name of this group
:param states: :class:`ManagedState` instances to be grouped together
"""
# 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) | 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 | 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.
: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.
"""
# 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) | 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.
: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.
"""
# 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) | 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. | 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 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
"""
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 | 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 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
"""
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 | 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 | 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_: 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
"""
return self.transition(from_, None, if_, **data) | 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_: 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
"""
return self.transition(from_, None, if_, **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 | 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 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
"""
return CheckConstraint(
str(column_constructor(column).in_(lenum.keys()).compile(compile_kwargs={'literal_binds': True})),
**kwargs) | 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 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
"""
return CheckConstraint(
str(column_constructor(column).in_(lenum.keys()).compile(compile_kwargs={'literal_binds': True})),
**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 | 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, self.cls) # This returns a wrapper
if msw: # If the wrapper evaluates to True, it's our best match
return msw | 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, self.cls) # This returns a wrapper
if msw: # If the wrapper evaluates to True, it's our best match
return msw | 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`
"""
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)) | 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`
"""
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)) | 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`.
"""
proxy = self.obj.access_for(roles, actor, anchors)
return {name: transition for name, transition in self.transitions(current=False).items()
if name in proxy} | 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`.
"""
proxy = self.obj.access_for(roles, actor, anchors)
return {name: transition for name, transition in self.transitions(current=False).items()
if name in proxy} | 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`.
:param bool keep_empty: If ``True``, empty states are included in the result
"""
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 | 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`.
:param bool keep_empty: If ``True``, empty states are included in the result
"""
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 | 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 | 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 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 | 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 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 | 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_tags=valid_tags))
else:
return Markup(markdown_convert_text(gfm(text))) | 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_tags=valid_tags))
else:
return Markup(markdown_convert_text(gfm(text))) | 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')
'/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'
"""
if method_rule.startswith('/'):
return method_rule
else:
return class_rule + ('' if class_rule.endswith('/') or not method_rule else '/') + method_rule | 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')
'/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'
"""
if method_rule.startswith('/'):
return method_rule
else:
return class_rule + ('' if class_rule.endswith('/') or not method_rule else '/') + 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' | 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 = 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 | 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 = 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 | 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::
@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`.
"""
@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 | 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::
@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`.
"""
@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 | 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`. | 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_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
"""
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) | 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_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
"""
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) | 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 | 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 specified decorators. The dispatcher
must call this
:param dict view_args: View arguments, to be passed on to the view method
"""
# 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))) | 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 specified decorators. The dispatcher
must call this
:param dict view_args: View arguments, to be passed on to the view method
"""
# 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))) | 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 | 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():
return True
return False | 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():
return True
return False | 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'
@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`
"""
setattr(cls, _name, route(rule, **options)(cls.__get_raw_attr(_name))) | 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'
@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`
"""
setattr(cls, _name, route(rule, **options)(cls.__get_raw_attr(_name))) | 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` | 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_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 | 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_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 | 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 be passed on to the view method
"""
# 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))) | 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 be passed on to the view method
"""
# 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))) | 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.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
"""
# 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 | 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.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
"""
# 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 | 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 | 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 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
"""
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 | 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 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
"""
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 | 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 | 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__`` 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) | 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__`` 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) | 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:
pass
{% if obj.current_roles.editor %}...{% endif %}
This property is also available in :class:`RoleAccessProxy`.
"""
return InspectableSet(self.roles_for(actor=current_auth.actor, anchors=current_auth.anchors)) | 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:
pass
{% if obj.current_roles.editor %}...{% endif %}
This property is also available in :class:`RoleAccessProxy`.
"""
return InspectableSet(self.roles_for(actor=current_auth.actor, anchors=current_auth.anchors)) | :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`. | 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 call:
obj.access_for(actor=current_auth.actor)
# Is shorthand for:
obj.access_for(roles=obj.roles_for(actor=current_auth.actor))
"""
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) | 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 call:
obj.access_for(actor=current_auth.actor)
# Is shorthand for:
obj.access_for(roles=obj.roles_for(actor=current_auth.actor))
"""
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) | 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)) | 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 ':')
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 | 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 ':')
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 | 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 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 ``/``).
"""
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() | 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 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 ``/``).
"""
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() | 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 ``/``). | 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.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) | 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.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) | 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)
: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
"""
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, {} | 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)
: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
"""
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, {} | 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 | 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).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 | 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).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 | 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 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) | 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 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) | 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 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 | 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 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 | 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 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
"""
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) | 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 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
"""
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) | 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 | 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):
key = value_def.config_key or config_key
return '%s.%s' % (config_path, key) if config_path else key
def build_token(name, value_def):
config_key = build_config_key(value_def, name)
value_token = ValueToken.from_definition(
value_def, namespace, config_key)
getters.register_value_proxy(namespace, value_token, value_def.help)
tokens[name] = value_token
return name, build_property(value_token)
def build_attr(name, attribute):
if not isinstance(attribute, ValueTypeDefinition):
return name, attribute
return build_token(name, attribute)
attributes = dict(build_attr(*item)
for item in six.iteritems(attributes))
attributes['_tokens'] = tokens
return attributes | 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):
key = value_def.config_key or config_key
return '%s.%s' % (config_path, key) if config_path else key
def build_token(name, value_def):
config_key = build_config_key(value_def, name)
value_token = ValueToken.from_definition(
value_def, namespace, config_key)
getters.register_value_proxy(namespace, value_token, value_def.help)
tokens[name] = value_token
return name, build_property(value_token)
def build_attr(name, attribute):
if not isinstance(attribute, ValueTypeDefinition):
return name, attribute
return build_token(name, attribute)
attributes = dict(build_attr(*item)
for item in six.iteritems(attributes))
attributes['_tokens'] = tokens
return attributes | 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:
return value
ret = func(self, *args, **kwargs)
setattr(self, cache_name, ret)
return ret
return inner_wrapper
return cache_wrapper | 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:
return value
ret = func(self, *args, **kwargs)
setattr(self, cache_name, ret)
return ret
return inner_wrapper
return cache_wrapper | 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 missing value for: %s" %
(proxy.namespace, proxy.config_key))
try:
return proxy.validator(value)
except errors.ValidationError as e:
raise errors.ConfigurationError("%s failed to validate %s: %s" %
(proxy.namespace, proxy.config_key, e)) | 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 missing value for: %s" %
(proxy.namespace, proxy.config_key))
try:
return proxy.validator(value)
except errors.ValidationError as e:
raise errors.ConfigurationError("%s failed to validate %s: %s" %
(proxy.namespace, proxy.config_key, e)) | 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
the appropriate type.
:param reader_namespace: the default namespace to use. Defaults to
`DEFAULT`.
"""
def reader(config_key, default=UndefToken, namespace=None):
config_namespace = config.get_namespace(namespace or reader_namespace)
return validator(_read_config(config_key, config_namespace, default))
return reader | 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
the appropriate type.
:param reader_namespace: the default namespace to use. Defaults to
`DEFAULT`.
"""
def reader(config_key, default=UndefToken, namespace=None):
config_namespace = config.get_namespace(namespace or reader_namespace)
return validator(_read_config(config_key, config_namespace, default))
return reader | 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 default namespace to use. Defaults to
`DEFAULT`. | https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/readers.py#L103-L116 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.