repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
jhermann/rudiments | src/rudiments/reamed/click.py | Configuration.from_context | python | def from_context(cls, ctx, config_paths=None, project=None):
if ctx.obj is None:
ctx.obj = Bunch()
ctx.obj.cfg = cls(ctx.info_name, config_paths, project=project)
return ctx.obj.cfg | Create a configuration object, and initialize the Click context with it. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/reamed/click.py#L97-L102 | null | class Configuration(object):
""" Configuration container that is initialized early in the main command.
The default instance is available via the Click context as ``ctx.obj.cfg``.
Configuration is lazily loaded, on first access.
"""
NO_DEFAULT = object()
DEFAULT_PATH = [
'/etc/... |
jhermann/rudiments | src/rudiments/reamed/click.py | Configuration.locations | python | def locations(self, exists=True):
result = []
for config_files in self.config_paths:
if not config_files:
continue
if os.path.isdir(config_files):
config_files = [os.path.join(config_files, i)
for i in sorted(os.list... | Return the location of the config file(s).
A given directory will be scanned for ``*.conf`` files, in alphabetical order.
Any duplicates will be eliminated.
If ``exists`` is True, only existing configuration locations are returned. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/reamed/click.py#L137-L161 | null | class Configuration(object):
""" Configuration container that is initialized early in the main command.
The default instance is available via the Click context as ``ctx.obj.cfg``.
Configuration is lazily loaded, on first access.
"""
NO_DEFAULT = object()
DEFAULT_PATH = [
'/etc/... |
jhermann/rudiments | src/rudiments/reamed/click.py | Configuration.load | python | def load(self):
if not self.loaded:
self.values = configobj.ConfigObj({}, **self.DEFAULT_CONFIG_OPTS)
for path in self.locations():
try:
part = configobj.ConfigObj(infile=path, **self.DEFAULT_CONFIG_OPTS)
except configobj.ConfigObjError... | Load configuration from the defined locations. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/reamed/click.py#L163-L174 | [
"def pretty_path(path, _home_re=re.compile('^' + re.escape(os.path.expanduser('~') + os.sep))):\n \"\"\"Prettify path for humans, and make it Unicode.\"\"\"\n path = format_filename(path)\n path = _home_re.sub('~' + os.sep, path)\n return path\n"
] | class Configuration(object):
""" Configuration container that is initialized early in the main command.
The default instance is available via the Click context as ``ctx.obj.cfg``.
Configuration is lazily loaded, on first access.
"""
NO_DEFAULT = object()
DEFAULT_PATH = [
'/etc/... |
jhermann/rudiments | src/rudiments/reamed/click.py | Configuration.section | python | def section(self, ctx, optional=False):
values = self.load()
try:
return values[ctx.info_name]
except KeyError:
if optional:
return configobj.ConfigObj({}, **self.DEFAULT_CONFIG_OPTS)
raise LoggedFailure("Configuration section '{}' not found!".... | Return section of the config for a specific context (sub-command).
Parameters:
ctx (Context): The Click context object.
optional (bool): If ``True``, return an empty config object when section is missing.
Returns:
Section: The configuration secti... | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/reamed/click.py#L180-L199 | null | class Configuration(object):
""" Configuration container that is initialized early in the main command.
The default instance is available via the Click context as ``ctx.obj.cfg``.
Configuration is lazily loaded, on first access.
"""
NO_DEFAULT = object()
DEFAULT_PATH = [
'/etc/... |
jhermann/rudiments | src/rudiments/reamed/click.py | Configuration.get | python | def get(self, name, default=NO_DEFAULT):
values = self.load()
try:
return values[name]
except KeyError:
if default is self.NO_DEFAULT:
raise LoggedFailure("Configuration value '{}' not found in root section!".format(name))
return default | Return the specified name from the root section.
Parameters:
name (str): The name of the requested value.
default (optional): If set, the default value to use
instead of raising :class:`LoggedFailure` for
unknown names.
Re... | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/reamed/click.py#L201-L223 | null | class Configuration(object):
""" Configuration container that is initialized early in the main command.
The default instance is available via the Click context as ``ctx.obj.cfg``.
Configuration is lazily loaded, on first access.
"""
NO_DEFAULT = object()
DEFAULT_PATH = [
'/etc/... |
jhermann/rudiments | src/rudiments/pysupport.py | import_name | python | def import_name(modulename, name=None):
if name is None:
modulename, name = modulename.rsplit(':', 1)
module = __import__(modulename, globals(), {}, [name])
return getattr(module, name) | Import identifier ``name`` from module ``modulename``.
If ``name`` is omitted, ``modulename`` must contain the name after the
module path, delimited by a colon.
Parameters:
modulename (str): Fully qualified module name, e.g. ``x.y.z``.
name (str): Name to import from ``... | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/pysupport.py#L25-L41 | null | # -*- coding: utf-8 -*-
# pylint: disable=bad-continuation
""" Python helpers + magic.
"""
# Copyright © 2015 Jürgen Hermann <jh@web.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... |
jhermann/rudiments | src/rudiments/pysupport.py | load_module | python | def load_module(modulename, modulepath):
if '.' in modulename:
modulepackage, modulebase = modulename.rsplit('.', 1)
else:
modulepackage = ''
imp.acquire_lock()
try:
# Check if module is already loaded
if modulename not in sys.modules:
# Find module on disk a... | Load a Python module from a path under a specified name.
Parameters:
modulename (str): Fully qualified module name, e.g. ``x.y.z``.
modulepath (str): Filename of the module.
Returns:
Loaded module. | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/pysupport.py#L44-L79 | null | # -*- coding: utf-8 -*-
# pylint: disable=bad-continuation
""" Python helpers + magic.
"""
# Copyright © 2015 Jürgen Hermann <jh@web.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... |
jhermann/rudiments | src/rudiments/www.py | url_as_file | python | def url_as_file(url, ext=None):
if ext:
ext = '.' + ext.strip('.') # normalize extension
url_hint = 'www-{}-'.format(urlparse(url).hostname or 'any')
content = requests.get(url).content
with tempfile.NamedTemporaryFile(suffix=ext or '', prefix=url_hint, delete=False) as handle:
handle.... | Context manager that GETs a given `url` and provides it as a local file.
The file is in a closed state upon entering the context,
and removed when leaving it, if still there.
To give the file name a specific extension, use `ext`;
the extension can optionally include a separating dot,
... | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/www.py#L38-L78 | null | # -*- coding: utf-8 -*-
# pylint: disable=bad-continuation
""" WWW access helpers.
You need a dependency on
`requests <http://docs.python-requests.org/en/latest/api/>`_
in your project if you use this module.
"""
# Copyright © 2015 Jürgen Hermann <jh@web.de>
#
# Licensed under the Apache License, Version ... |
jhermann/rudiments | src/rudiments/humanize.py | bytes2iec | python | def bytes2iec(size, compact=False):
postfn = lambda text: text.replace(' ', '') if compact else text
if size < 0:
raise ValueError("Negative byte size value {}".format(size))
if size < 1024:
return postfn('{:4d} bytes'.format(size))
scaled = size
for iec_unit in IEC_UNITS[1:]:
... | Convert a size value in bytes to its equivalent in IEC notation.
See `<http://physics.nist.gov/cuu/Units/binary.html>`_.
Parameters:
size (int): Number of bytes.
compact (bool): If ``True``, the result contains no spaces.
Return:
String representation of ``... | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/humanize.py#L24-L51 | [
"postfn = lambda text: text.replace(' ', '') if compact else text\n"
] | # -*- coding: utf-8 -*-
# pylint: disable=bad-continuation
""" I/O of common values in forms understood by humans.
"""
# Copyright © 2015 Jürgen Hermann <jh@web.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a ... |
jhermann/rudiments | src/rudiments/humanize.py | iec2bytes | python | def iec2bytes(size_spec, only_positive=True):
scale = 1
try:
size = int(0 + size_spec) # return numeric values as-is
except (TypeError, ValueError):
spec = size_spec.strip().lower()
for exp, iec_unit in enumerate(IEC_UNITS[1:], 1):
iec_unit = iec_unit.lower()
... | Convert a size specification, optionally containing a scaling
unit in IEC notation, to a number of bytes.
Parameters:
size_spec (str): Number, optionally followed by a unit.
only_positive (bool): Allow only positive values?
Return:
Numeric bytes size.
... | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/humanize.py#L54-L99 | null | # -*- coding: utf-8 -*-
# pylint: disable=bad-continuation
""" I/O of common values in forms understood by humans.
"""
# Copyright © 2015 Jürgen Hermann <jh@web.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a ... |
jhermann/rudiments | src/rudiments/humanize.py | merge_adjacent | python | def merge_adjacent(numbers, indicator='..', base=0):
integers = list(sorted([(int("%s" % i, base), i) for i in numbers]))
idx = 0
result = []
while idx < len(numbers):
end = idx + 1
while end < len(numbers) and integers[end-1][0] == integers[end][0] - 1:
end += 1
res... | Merge adjacent numbers in an iterable of numbers.
Parameters:
numbers (list): List of integers or numeric strings.
indicator (str): Delimiter to indicate generated ranges.
base (int): Passed to the `int()` conversion when comparing numbers.
Return:
list ... | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/humanize.py#L102-L125 | null | # -*- coding: utf-8 -*-
# pylint: disable=bad-continuation
""" I/O of common values in forms understood by humans.
"""
# Copyright © 2015 Jürgen Hermann <jh@web.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a ... |
quantmind/pulsar-odm | odm/mapper.py | model_base | python | def model_base(bind_label=None, info=None):
Model = type('Model', (BaseModel,), {'__odm_abstract__': True})
info = {}
Model.__table_args__ = table_args(info=info)
if bind_label:
info['bind_label'] = bind_label
return Model | Create a base declarative class | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L114-L122 | [
"def table_args(*args, **kwargs):\n targs = ()\n tkwargs = {}\n\n if args:\n if hasattr(args[0], '__table_args__'):\n targs = args[0].__table_args__\n targs, tkwargs = targs[:-1], targs[-1].copy()\n args = args[1:]\n\n targs += args\n\n for key, value in kw... | import logging
import sys
from copy import copy
from inspect import getmodule
from contextlib import contextmanager
from collections import OrderedDict
import sqlalchemy
from sqlalchemy.engine import url
from sqlalchemy.engine.strategies import PlainEngineStrategy
from sqlalchemy import MetaData, Table, event
from sql... |
quantmind/pulsar-odm | odm/mapper.py | copy_models | python | def copy_models(module_from, module_to):
module_from = get_module(module_from)
module_to = get_module(module_to)
models = get_models(module_from)
if models:
models = models.copy()
models.update(((t.key, t) for t in module_tables(module_from)))
module_to.__odm_models__ = models
... | Copy models from one module to another
:param module_from:
:param module_to:
:return: | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L131-L144 | [
"def module_tables(module):\n for name, table in vars(module).items():\n if isinstance(table, Table):\n yield table\n",
"def get_module(module_or_name):\n if isinstance(module_or_name, str):\n return sys.modules[module_or_name]\n else:\n return getmodule(module_or_name)\n"... | import logging
import sys
from copy import copy
from inspect import getmodule
from contextlib import contextmanager
from collections import OrderedDict
import sqlalchemy
from sqlalchemy.engine import url
from sqlalchemy.engine.strategies import PlainEngineStrategy
from sqlalchemy import MetaData, Table, event
from sql... |
quantmind/pulsar-odm | odm/mapper.py | Mapper.register | python | def register(self, model, **attr):
metadata = self.metadata
if not isinstance(model, Table):
model_name = self._create_model(model, **attr)
if not model_name:
return
model, name = model_name
table = model.__table__
self._declara... | Register a model or a table with this mapper
:param model: a table or a :class:`.BaseModel` class
:return: a Model class or a table | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L223-L259 | [
"def register(self, model, **attr):\n \"\"\"Register a model or a table with this mapper\n\n :param model: a table or a :class:`.BaseModel` class\n :return: a Model class or a table\n \"\"\"\n metadata = self.metadata\n if not isinstance(model, Table):\n model_name = self._create_model(mode... | class Mapper:
"""SQLAlchemy wrapper
.. attribute:: binds
Dictionary of labels-engine pairs. The "default" label is always
present and it is used for tables without `bind_label` in their
`info` dictionary.
"""
def __init__(self, binds):
# Setup mdoels and engines
... |
quantmind/pulsar-odm | odm/mapper.py | Mapper.create_table | python | def create_table(self, name, *columns, **kwargs):
targs = table_args(**kwargs)
args, kwargs = targs[:-1], targs[-1]
return Table(name, self.metadata, *columns, *args, **kwargs) | Create a new table with the same metadata and info | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L274-L279 | [
"def table_args(*args, **kwargs):\n targs = ()\n tkwargs = {}\n\n if args:\n if hasattr(args[0], '__table_args__'):\n targs = args[0].__table_args__\n targs, tkwargs = targs[:-1], targs[-1].copy()\n args = args[1:]\n\n targs += args\n\n for key, value in kw... | class Mapper:
"""SQLAlchemy wrapper
.. attribute:: binds
Dictionary of labels-engine pairs. The "default" label is always
present and it is used for tables without `bind_label` in their
`info` dictionary.
"""
def __init__(self, binds):
# Setup mdoels and engines
... |
quantmind/pulsar-odm | odm/mapper.py | Mapper.database_create | python | def database_create(self, database, **params):
binds = {}
dbname = database
for key, engine in self.keys_engines():
if hasattr(database, '__call__'):
dbname = database(engine)
assert dbname, "Cannot create a database, no db name given"
key = ke... | Create databases for each engine and return a new :class:`.Mapper`. | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L281-L292 | [
"def copy(self, binds):\n return self.__class__(binds)\n",
"def keys_engines(self):\n return self._engines.items()\n",
"def _database_create(self, engine, database):\n \"\"\"Create a new database and return a new url representing\n a connection to the new database\n \"\"\"\n logger.info('Creat... | class Mapper:
"""SQLAlchemy wrapper
.. attribute:: binds
Dictionary of labels-engine pairs. The "default" label is always
present and it is used for tables without `bind_label` in their
`info` dictionary.
"""
def __init__(self, binds):
# Setup mdoels and engines
... |
quantmind/pulsar-odm | odm/mapper.py | Mapper.database_exist | python | def database_exist(self):
binds = {}
for key, engine in self.keys_engines():
key = key if key else 'default'
binds[key] = self._database_exist(engine)
return binds | Create databases for each engine and return a new :class:`.Mapper`. | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L294-L301 | [
"def keys_engines(self):\n return self._engines.items()\n",
"def _database_exist(self, engine):\n return database_operation(engine, 'exists')\n"
] | class Mapper:
"""SQLAlchemy wrapper
.. attribute:: binds
Dictionary of labels-engine pairs. The "default" label is always
present and it is used for tables without `bind_label` in their
`info` dictionary.
"""
def __init__(self, binds):
# Setup mdoels and engines
... |
quantmind/pulsar-odm | odm/mapper.py | Mapper.database_all | python | def database_all(self):
all = {}
for engine in self.engines():
all[engine] = self._database_all(engine)
return all | Return a dictionary mapping engines with databases | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L303-L309 | [
"def engines(self):\n \"\"\"Iterator over all engines\n \"\"\"\n return self._engines.values()\n",
"def _database_all(self, engine):\n return database_operation(engine, 'all')\n"
] | class Mapper:
"""SQLAlchemy wrapper
.. attribute:: binds
Dictionary of labels-engine pairs. The "default" label is always
present and it is used for tables without `bind_label` in their
`info` dictionary.
"""
def __init__(self, binds):
# Setup mdoels and engines
... |
quantmind/pulsar-odm | odm/mapper.py | Mapper.table_create | python | def table_create(self, remove_existing=False):
for engine in self.engines():
tables = self._get_tables(engine, create_drop=True)
logger.info('Create all tables for %s', engine)
try:
self.metadata.create_all(engine, tables=tables)
except Exception a... | Creates all tables. | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L327-L336 | [
"def engines(self):\n \"\"\"Iterator over all engines\n \"\"\"\n return self._engines.values()\n",
"def _get_tables(self, engine, create_drop=False):\n tables = []\n for table, eng in self.binds.items():\n if eng == engine:\n if table.key in self._declarative_register:\n ... | class Mapper:
"""SQLAlchemy wrapper
.. attribute:: binds
Dictionary of labels-engine pairs. The "default" label is always
present and it is used for tables without `bind_label` in their
`info` dictionary.
"""
def __init__(self, binds):
# Setup mdoels and engines
... |
quantmind/pulsar-odm | odm/mapper.py | Mapper.table_drop | python | def table_drop(self):
for engine in self.engines():
tables = self._get_tables(engine, create_drop=True)
logger.info('Drop all tables for %s', engine)
self.metadata.drop_all(engine, tables=tables) | Drops all tables. | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L338-L344 | [
"def engines(self):\n \"\"\"Iterator over all engines\n \"\"\"\n return self._engines.values()\n",
"def _get_tables(self, engine, create_drop=False):\n tables = []\n for table, eng in self.binds.items():\n if eng == engine:\n if table.key in self._declarative_register:\n ... | class Mapper:
"""SQLAlchemy wrapper
.. attribute:: binds
Dictionary of labels-engine pairs. The "default" label is always
present and it is used for tables without `bind_label` in their
`info` dictionary.
"""
def __init__(self, binds):
# Setup mdoels and engines
... |
quantmind/pulsar-odm | odm/mapper.py | Mapper.begin | python | def begin(self, close=True, expire_on_commit=False, session=None,
commit=False, **options):
if not session:
commit = True
session = self.session(expire_on_commit=expire_on_commit,
**options)
else:
close = False
... | Provide a transactional scope around a series of operations.
By default, ``expire_on_commit`` is set to False so that instances
can be used outside the session. | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L347-L369 | [
"def session(self, **options):\n options['binds'] = self.binds\n return OdmSession(self, **options)\n"
] | class Mapper:
"""SQLAlchemy wrapper
.. attribute:: binds
Dictionary of labels-engine pairs. The "default" label is always
present and it is used for tables without `bind_label` in their
`info` dictionary.
"""
def __init__(self, binds):
# Setup mdoels and engines
... |
quantmind/pulsar-odm | odm/mapper.py | Mapper._database_create | python | def _database_create(self, engine, database):
logger.info('Creating database "%s" in "%s"', database, engine)
database_operation(engine, 'create', database)
url = copy(engine.url)
url.database = database
return str(url) | Create a new database and return a new url representing
a connection to the new database | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/mapper.py#L459-L467 | [
"def database_operation(engine, oper, *args):\n operation = _database_operation(engine, oper)\n return operation(engine, *args)\n"
] | class Mapper:
"""SQLAlchemy wrapper
.. attribute:: binds
Dictionary of labels-engine pairs. The "default" label is always
present and it is used for tables without `bind_label` in their
`info` dictionary.
"""
def __init__(self, binds):
# Setup mdoels and engines
... |
quantmind/pulsar-odm | benchmark/app.py | Router.get | python | def get(self, request):
'''Simply list test urls
'''
data = {}
for router in self.routes:
data[router.name] = request.absolute_uri(router.path())
return Json(data).http_response(request) | Simply list test urls | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/benchmark/app.py#L38-L44 | null | class Router(wsgi.Router):
'''WSGI Router for the benchmarking application
'''
@route()
def json(self, request):
return Json({'message': "Hello, World!"}).http_response(request)
@route()
def plaintext(self, request):
return String('Hello, World!').http_response(request)
@... |
quantmind/pulsar-odm | benchmark/app.py | Router.db | python | def db(self, request):
'''Single Database Query'''
with self.mapper.begin() as session:
world = session.query(World).get(randint(1, 10000))
return Json(self.get_json(world)).http_response(request) | Single Database Query | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/benchmark/app.py#L55-L59 | [
"def get_json(self, world):\n return {'id': world.id, 'randomNumber': world.randomNumber}\n"
] | class Router(wsgi.Router):
'''WSGI Router for the benchmarking application
'''
def get(self, request):
'''Simply list test urls
'''
data = {}
for router in self.routes:
data[router.name] = request.absolute_uri(router.path())
return Json(data).http_response... |
quantmind/pulsar-odm | benchmark/app.py | Router.queries | python | def queries(self, request):
'''Multiple Database Queries'''
queries = self.get_queries(request)
worlds = []
with self.mapper.begin() as session:
for _ in range(queries):
world = session.query(World).get(randint(1, MAXINT))
worlds.append(self.ge... | Multiple Database Queries | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/benchmark/app.py#L62-L70 | [
"def get_queries(self, request):\n queries = request.url_data.get(\"queries\", \"1\")\n try:\n queries = int(queries.strip())\n except ValueError:\n queries = 1\n\n return min(max(1, queries), 500)\n",
"def get_json(self, world):\n return {'id': world.id, 'randomNumber': world.randomN... | class Router(wsgi.Router):
'''WSGI Router for the benchmarking application
'''
def get(self, request):
'''Simply list test urls
'''
data = {}
for router in self.routes:
data[router.name] = request.absolute_uri(router.path())
return Json(data).http_response... |
quantmind/pulsar-odm | odm/utils.py | get_columns | python | def get_columns(mixed):
if isinstance(mixed, sa.Table):
return mixed.c
if isinstance(mixed, sa.orm.util.AliasedClass):
return sa.inspect(mixed).mapper.columns
if isinstance(mixed, sa.sql.selectable.Alias):
return mixed.c
if isinstance(mixed, sa.orm.Mapper):
return mixed.c... | Return a collection of all Column objects for given SQLAlchemy
object.
The type of the collection depends on the type of the object to return the
columns from.
::
get_columns(User)
get_columns(User())
get_columns(User.__table__)
get_columns(User.__mapper__)
get_co... | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/utils.py#L9-L37 | null | import os
from inspect import isclass
import sqlalchemy as sa
from sqlalchemy import inspect
from sqlalchemy.exc import OperationalError, ProgrammingError
def database_operation(engine, oper, *args):
operation = _database_operation(engine, oper)
return operation(engine, *args)
def _database_operation(engi... |
quantmind/pulsar-odm | benchmark/bench.py | run_benchmark | python | def run_benchmark(monitor):
'''Run the benchmarks
'''
url = urlparse(monitor.cfg.test_url)
name = slugify(url.path) or 'home'
name = '%s_%d.csv' % (name, monitor.cfg.workers)
monitor.logger.info('WRITING RESULTS ON "%s"', name)
total = REQUESTS//monitor.cfg.workers
with open(name, 'w') ... | Run the benchmarks | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/benchmark/bench.py#L99-L143 | null | import csv
from asyncio import async, wait
from random import randint
from urllib.parse import urlparse
from functools import reduce
import pulsar
from pulsar.apps.http import HttpClient
from pulsar.apps.greenio import GreenPool
from pulsar.utils.slugify import slugify
POOL_SIZES = [8, 16, 32, 64, 128, 256, 512, 102... |
quantmind/pulsar-odm | benchmark/bench.py | Bench.filldb | python | def filldb(self):
'''Fill database
'''
from app import World, Fortune, odm, MAXINT
mapper = odm.Mapper(self.cfg.postgresql)
mapper.register(World)
mapper.register(Fortune)
mapper.table_create()
with mapper.begin() as session:
query = session.... | Fill database | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/benchmark/bench.py#L163-L185 | null | class Bench(pulsar.Application):
cfg = pulsar.Config(apps=['bench'])
def monitor_start(self, monitor, exc=None):
if monitor.cfg.filldb:
self.pool = GreenPool()
try:
yield from self.pool.submit(self.filldb)
finally:
monitor._loop.stop()... |
quantmind/pulsar-odm | odm/dialects/postgresql/green.py | psycopg2_wait_callback | python | def psycopg2_wait_callback(conn):
while True:
state = conn.poll()
if state == extensions.POLL_OK:
# Done with waiting
break
elif state == extensions.POLL_READ:
_wait_fd(conn)
elif state == extensions.POLL_WRITE:
_wait_fd(conn, read=Fals... | A wait callback to allow greenlet to work with Psycopg.
The caller must be from a greenlet other than the main one.
:param conn: psycopg2 connection or file number
This function must be invoked from a coroutine with parent, therefore
invoking it from the main greenlet will raise an exception. | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/dialects/postgresql/green.py#L12-L31 | [
"def _wait_fd(conn, read=True):\n '''Wait for an event on file descriptor ``fd``.\n\n :param conn: file descriptor\n :param read: wait for a read event if ``True``, otherwise a wait\n for write event.\n\n This function must be invoked from a coroutine with parent, therefore\n invoking it from ... | from asyncio import Future
from greenlet import getcurrent
import psycopg2
from psycopg2 import * # noqa
from psycopg2 import extensions, OperationalError
__version__ = psycopg2.__version__
# INTERNALS
def _wait_fd(conn, read=True):
'''Wait for an event on file descriptor ``fd``.
:param conn: file desc... |
quantmind/pulsar-odm | odm/dialects/postgresql/green.py | _wait_fd | python | def _wait_fd(conn, read=True):
'''Wait for an event on file descriptor ``fd``.
:param conn: file descriptor
:param read: wait for a read event if ``True``, otherwise a wait
for write event.
This function must be invoked from a coroutine with parent, therefore
invoking it from the main gree... | Wait for an event on file descriptor ``fd``.
:param conn: file descriptor
:param read: wait for a read event if ``True``, otherwise a wait
for write event.
This function must be invoked from a coroutine with parent, therefore
invoking it from the main greenlet will raise an exception. | train | https://github.com/quantmind/pulsar-odm/blob/5955c20beca0a89270c2b390335838deb7d5915e/odm/dialects/postgresql/green.py#L36-L62 | null | from asyncio import Future
from greenlet import getcurrent
import psycopg2
from psycopg2 import * # noqa
from psycopg2 import extensions, OperationalError
__version__ = psycopg2.__version__
def psycopg2_wait_callback(conn):
"""A wait callback to allow greenlet to work with Psycopg.
The caller must be from... |
xguse/table_enforcer | setup.py | filter_req_paths | python | def filter_req_paths(paths, func):
if not isinstance(paths, list):
raise ValueError("Paths must be a list of paths.")
libs = set()
junk = set(['\n'])
for p in paths:
with p.open(mode='r') as reqs:
lines = set([line for line in reqs if func(line)])
libs.update(lin... | Return list of filtered libs. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/setup.py#L9-L21 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
from pathlib import Path
def is_pipable(line):
"""Filter for pipable reqs."""
if "# not_pipable" in line:
return False
elif line.startswith('#'):
return False
else:
... |
xguse/table_enforcer | table_enforcer/utils/validate/decorators.py | minmax | python | def minmax(low, high):
def decorator(function):
"""Decorate a function with args."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
"""Wrap the function."""
series = function(*args, **kwargs)
lo_pass = low <= series
hi_pass = series <... | Test that the data items fall within range: low <= x <= high. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/utils/validate/decorators.py#L5-L20 | null | """Provide decoration functions to augment the behavior of validator functions."""
import functools
def choice(choices):
"""Test that the data items are members of the set `choices`."""
def decorator(function):
"""Decorate a function with args."""
@functools.wraps(function)
def wrappe... |
xguse/table_enforcer | table_enforcer/utils/validate/decorators.py | choice | python | def choice(choices):
def decorator(function):
"""Decorate a function with args."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
"""Wrap the function."""
series = function(*args, **kwargs)
return series.isin(set(choices))
return wrapper... | Test that the data items are members of the set `choices`. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/utils/validate/decorators.py#L23-L35 | null | """Provide decoration functions to augment the behavior of validator functions."""
import functools
def minmax(low, high):
"""Test that the data items fall within range: low <= x <= high."""
def decorator(function):
"""Decorate a function with args."""
@functools.wraps(function)
def wr... |
xguse/table_enforcer | table_enforcer/utils/validate/decorators.py | bounded_length | python | def bounded_length(low, high=None):
def decorator(function):
"""Decorate a function with args."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
"""Wrap the function."""
series = function(*args, **kwargs)
if high is None:
return s... | Test that the length of the data items fall within range: low <= x <= high.
If high is None, treat as exact length. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/utils/validate/decorators.py#L38-L59 | null | """Provide decoration functions to augment the behavior of validator functions."""
import functools
def minmax(low, high):
"""Test that the data items fall within range: low <= x <= high."""
def decorator(function):
"""Decorate a function with args."""
@functools.wraps(function)
def wr... |
xguse/table_enforcer | table_enforcer/utils/validate/funcs.py | unique | python | def unique(series: pd.Series) -> pd.Series:
return ~series.duplicated(keep=False) | Test that the data items do not repeat. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/utils/validate/funcs.py#L30-L32 | null | """Provide builtin validator functions for common use cases.
In general, validators take a single `pandas.Series` object as
input and return a `pandas.Series` of the same shape and indexes
containing `True` or `False` relative to which items passed the
validation logic.
"""
import pandas as pd
# import numpy as np
# ... |
xguse/table_enforcer | table_enforcer/main_classes.py | Enforcer._make_validations | python | def _make_validations(self, table: pd.DataFrame) -> Box:
results = []
for column in self.columns:
results.append(column.validate(table))
return results | Return a dict-like object containing dataframes of which tests passed/failed for each column. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L42-L49 | null | class Enforcer(object):
"""Class to define table definitions."""
def __init__(self, columns):
"""Initialize an enforcer instance."""
self.columns = columns
def validate(self, table: pd.DataFrame) -> bool:
"""Return True if all validation tests pass: False otherwise."""
val... |
xguse/table_enforcer | table_enforcer/main_classes.py | Enforcer.validate | python | def validate(self, table: pd.DataFrame) -> bool:
validations = self._make_validations(table=table)
results = [df.all().all() for df in validations]
return all(results) | Return True if all validation tests pass: False otherwise. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L51-L57 | [
"def _make_validations(self, table: pd.DataFrame) -> Box:\n \"\"\"Return a dict-like object containing dataframes of which tests passed/failed for each column.\"\"\"\n results = []\n\n for column in self.columns:\n results.append(column.validate(table))\n\n return results\n"
] | class Enforcer(object):
"""Class to define table definitions."""
def __init__(self, columns):
"""Initialize an enforcer instance."""
self.columns = columns
def _make_validations(self, table: pd.DataFrame) -> Box:
"""Return a dict-like object containing dataframes of which tests pas... |
xguse/table_enforcer | table_enforcer/main_classes.py | Enforcer.recode | python | def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame:
df = pd.DataFrame(index=table.index)
for column in self.columns:
df = column.update_dataframe(df, table=table, validate=validate)
return df | Return a fully recoded dataframe.
Args:
table (pd.DataFrame): A dataframe on which to apply recoding logic.
validate (bool): If ``True``, recoded table must pass validation tests. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L59-L71 | null | class Enforcer(object):
"""Class to define table definitions."""
def __init__(self, columns):
"""Initialize an enforcer instance."""
self.columns = columns
def _make_validations(self, table: pd.DataFrame) -> Box:
"""Return a dict-like object containing dataframes of which tests pas... |
xguse/table_enforcer | table_enforcer/main_classes.py | BaseColumn.update_dataframe | python | def update_dataframe(self, df, table, validate=False):
df = df.copy()
recoded_columns = self.recode(table=table, validate=validate)
return pd.concat([df, recoded_columns], axis=1) | Perform ``self.recode`` and add resulting column(s) to ``df`` and return ``df``. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L80-L84 | [
"def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame:\n \"\"\"Pass the appropriate columns through each recoder function sequentially and return the final result.\n\n Args:\n table (pd.DataFrame): A dataframe on which to apply recoding logic.\n validate (bool): If ``True``, rec... | class BaseColumn(object):
"""Base Class for Columns.
Lays out essential methods api.
"""
def validate(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame:
"""Return a dataframe of validation results for the appropriate series vs the vector of validators.
Args:
t... |
xguse/table_enforcer | table_enforcer/main_classes.py | BaseColumn.validate | python | def validate(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame:
raise NotImplementedError("This method must be defined for each subclass.") | Return a dataframe of validation results for the appropriate series vs the vector of validators.
Args:
table (pd.DataFrame): A dataframe on which to apply validation logic.
failed_only (bool): If ``True``: return only the indexes that failed to validate. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L86-L93 | null | class BaseColumn(object):
"""Base Class for Columns.
Lays out essential methods api.
"""
def update_dataframe(self, df, table, validate=False):
"""Perform ``self.recode`` and add resulting column(s) to ``df`` and return ``df``."""
df = df.copy()
recoded_columns = self.recode(ta... |
xguse/table_enforcer | table_enforcer/main_classes.py | BaseColumn.recode | python | def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame:
raise NotImplementedError("This method must be defined for each subclass.") | Pass the appropriate columns through each recoder function sequentially and return the final result.
Args:
table (pd.DataFrame): A dataframe on which to apply recoding logic.
validate (bool): If ``True``, recoded table must pass validation tests. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L95-L102 | null | class BaseColumn(object):
"""Base Class for Columns.
Lays out essential methods api.
"""
def update_dataframe(self, df, table, validate=False):
"""Perform ``self.recode`` and add resulting column(s) to ``df`` and return ``df``."""
df = df.copy()
recoded_columns = self.recode(ta... |
xguse/table_enforcer | table_enforcer/main_classes.py | Column._dict_of_funcs | python | def _dict_of_funcs(self, funcs: list) -> pd.Series:
return {func.__name__: func for func in funcs} | Return a pd.Series of functions with index derived from the function name. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L135-L137 | null | class Column(BaseColumn):
"""Class representing a single table column."""
def __init__(
self,
name: str,
dtype: type,
unique: bool,
validators: t.List[VALIDATOR_FUNCTION],
recoders: t.List[RECODER_FUNCTION],) -> None:
"""Construct ... |
xguse/table_enforcer | table_enforcer/main_classes.py | Column._validate_series_dtype | python | def _validate_series_dtype(self, series: pd.Series) -> pd.Series:
return series.apply(lambda i: isinstance(i, self.dtype)) | Validate that the series data is the correct dtype. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L139-L141 | null | class Column(BaseColumn):
"""Class representing a single table column."""
def __init__(
self,
name: str,
dtype: type,
unique: bool,
validators: t.List[VALIDATOR_FUNCTION],
recoders: t.List[RECODER_FUNCTION],) -> None:
"""Construct ... |
xguse/table_enforcer | table_enforcer/main_classes.py | Column.validate | python | def validate(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame:
series = table[self.name]
self._check_series_name(series)
validators = self.validators
results = pd.DataFrame({validator: series for validator in validators}, index=series.index)
for name, func in val... | Return a dataframe of validation results for the appropriate series vs the vector of validators.
Args:
table (pd.DataFrame): A dataframe on which to apply validation logic.
failed_only (bool): If ``True``: return only the indexes that failed to validate. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L152-L178 | [
"def unique(series: pd.Series) -> pd.Series:\n \"\"\"Test that the data items do not repeat.\"\"\"\n return ~series.duplicated(keep=False)\n",
"def find_failed_rows(results):\n failed_rows = results.apply(lambda vec: ~vec.all(), axis=1)\n return results.loc[failed_rows]\n",
"def _validate_series_dty... | class Column(BaseColumn):
"""Class representing a single table column."""
def __init__(
self,
name: str,
dtype: type,
unique: bool,
validators: t.List[VALIDATOR_FUNCTION],
recoders: t.List[RECODER_FUNCTION],) -> None:
"""Construct ... |
xguse/table_enforcer | table_enforcer/main_classes.py | Column.recode | python | def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame:
series = table[self.name]
self._check_series_name(series)
col = self.name
data = series.copy()
for recoder in self.recoders.values():
try:
data = recoder(data)
excep... | Pass the provided series obj through each recoder function sequentially and return the final result.
Args:
table (pd.DataFrame): A dataframe on which to apply recoding logic.
validate (bool): If ``True``, recoded table must pass validation tests. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L180-L206 | [
"def find_failed_rows(results):\n failed_rows = results.apply(lambda vec: ~vec.all(), axis=1)\n return results.loc[failed_rows]\n",
"def _check_series_name(self, series, override_name=None):\n if override_name is None:\n name = self.name\n else:\n name = override_name\n\n if series.na... | class Column(BaseColumn):
"""Class representing a single table column."""
def __init__(
self,
name: str,
dtype: type,
unique: bool,
validators: t.List[VALIDATOR_FUNCTION],
recoders: t.List[RECODER_FUNCTION],) -> None:
"""Construct ... |
xguse/table_enforcer | table_enforcer/main_classes.py | CompoundColumn._do_validation_set | python | def _do_validation_set(self, table: pd.DataFrame, columns, validation_type, failed_only=False) -> pd.DataFrame:
validations = []
for column in columns:
validation = column.validate(table=table, failed_only=failed_only)
validation["column_name"] = column.name
validati... | Return a dataframe of validation results for the appropriate series vs the vector of validators. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L228-L241 | null | class CompoundColumn(BaseColumn):
"""Class representing multiple columns and the logic governing their transformation from source table to recoded table."""
def __init__(
self,
input_columns: t.List[Column],
output_columns: t.List[Column],
column_transform,) -> N... |
xguse/table_enforcer | table_enforcer/main_classes.py | CompoundColumn._validate_input | python | def _validate_input(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame:
return self._do_validation_set(
table=table,
columns=self.input_columns,
validation_type="input",
failed_only=failed_only,) | Return a dataframe of validation results for the appropriate series vs the vector of validators. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L243-L249 | [
"def _do_validation_set(self, table: pd.DataFrame, columns, validation_type, failed_only=False) -> pd.DataFrame:\n \"\"\"Return a dataframe of validation results for the appropriate series vs the vector of validators.\"\"\"\n validations = []\n\n for column in columns:\n validation = column.validate... | class CompoundColumn(BaseColumn):
"""Class representing multiple columns and the logic governing their transformation from source table to recoded table."""
def __init__(
self,
input_columns: t.List[Column],
output_columns: t.List[Column],
column_transform,) -> N... |
xguse/table_enforcer | table_enforcer/main_classes.py | CompoundColumn.validate | python | def validate(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame:
return pd.concat([
self._validate_input(table, failed_only=failed_only),
self._validate_output(table, failed_only=failed_only),
]).fillna(True) | Return a dataframe of validation results for the appropriate series vs the vector of validators.
Args:
table (pd.DataFrame): A dataframe on which to apply validation logic.
failed_only (bool): If ``True``: return only the indexes that failed to validate. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L275-L285 | [
"def _validate_input(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame:\n \"\"\"Return a dataframe of validation results for the appropriate series vs the vector of validators.\"\"\"\n return self._do_validation_set(\n table=table,\n columns=self.input_columns,\n validation_ty... | class CompoundColumn(BaseColumn):
"""Class representing multiple columns and the logic governing their transformation from source table to recoded table."""
def __init__(
self,
input_columns: t.List[Column],
output_columns: t.List[Column],
column_transform,) -> N... |
xguse/table_enforcer | table_enforcer/main_classes.py | CompoundColumn.recode | python | def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame:
return self._recode_output(self._recode_input(table, validate=validate), validate=validate) | Pass the appropriate columns through each recoder function sequentially and return the final result.
Args:
table (pd.DataFrame): A dataframe on which to apply recoding logic.
validate (bool): If ``True``, recoded table must pass validation tests. | train | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/main_classes.py#L287-L294 | [
"def _recode_input(self, table: pd.DataFrame, validate=False) -> pd.DataFrame:\n return self._recode_set(table=table, columns=self.input_columns, validate=validate)\n",
"def _recode_output(self, table: pd.DataFrame, validate=False) -> pd.DataFrame:\n transformed_columns = self.column_transform(table)\n r... | class CompoundColumn(BaseColumn):
"""Class representing multiple columns and the logic governing their transformation from source table to recoded table."""
def __init__(
self,
input_columns: t.List[Column],
output_columns: t.List[Column],
column_transform,) -> N... |
snbuback/django_services | django_services/api/utils.py | get_view_doc | python | def get_view_doc(view, html=True):
try:
description = view.__doc__ or ''
description = formatting.dedent(smart_text(description))
# include filters in description
filter_fields = get_filter_fields(view)
if filter_fields:
filter_doc = ['\n\n\n## Filters', '']
... | Build view documentation. Return in html format.
If you want in markdown format, use html=False | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/api/utils.py#L16-L42 | [
"def get_filter_fields(view):\n filter_fields = list(getattr(view, 'filter_fields', []))\n for filter_backend in getattr(view, 'filter_backends', []):\n if hasattr(filter_backend, 'filter_field'):\n filter_fields.append(filter_backend.filter_field)\n return filter_fields\n"
] | # -*- coding:utf-8 -*-
from django.utils.safestring import mark_safe
from rest_framework.utils import formatting
from rest_framework.compat import smart_text
def get_filter_fields(view):
filter_fields = list(getattr(view, 'filter_fields', []))
for filter_backend in getattr(view, 'filter_backends', []):
... |
snbuback/django_services | django_services/api/utils.py | wrap_accordion | python | def wrap_accordion(text_body_list):
html = ['<div class="accordion" id="accordion2">']
for i, item in enumerate(text_body_list):
params = {
'index': i,
'title': item[0],
'body': item[1]
}
html.append('''
<div class="accordion-group">
<div class="... | Wrap text_body_list in twitter bootstrap accordion. text_body_list must be list with tuple with title and body | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/api/utils.py#L45-L73 | null | # -*- coding:utf-8 -*-
from django.utils.safestring import mark_safe
from rest_framework.utils import formatting
from rest_framework.compat import smart_text
def get_filter_fields(view):
filter_fields = list(getattr(view, 'filter_fields', []))
for filter_backend in getattr(view, 'filter_backends', []):
... |
snbuback/django_services | django_services/service/base.py | ListServiceMixin.list | python | def list(self, **filters):
LOG.debug(u'Querying %s by filters=%s', self.model_class.__name__, filters)
query = self.__queryset__()
perm = build_permission_name(self.model_class, 'view')
LOG.debug(u"Checking if user %s has_perm %s" % (self.user, perm))
query_with_permission = filt... | Returns a queryset filtering object by user permission. If you want,
you can specify filter arguments.
See https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter for more details | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/service/base.py#L51-L70 | [
"def build_permission_name(model_class, prefix):\n \"\"\" Build permission name for model_class (like 'app.add_model'). \"\"\"\n model_name = model_class._meta.object_name.lower()\n app_label = model_class._meta.app_label\n action_name = prefix\n perm = '%s.%s_%s' % (app_label, action_name, model_nam... | class ListServiceMixin(object):
"""
Performe pre-filter in object list to avoid unauthorized access
"""
@nocheckpermission()
def __queryset__(self):
""" Returns basic queryset """
return self.model_class.objects.get_query_set()
@nocheckpermission()
def get(self, pk=None,... |
snbuback/django_services | django_services/service/base.py | ListServiceMixin.get | python | def get(self, pk=None, **filters):
LOG.debug(u'Querying (GET) %s by pk=%s and filters=%s', self.model_class.__name__, repr(pk), filters)
query = self.model_class.objects.filter(**filters)
if pk is None:
obj = query.get()
else:
if (isinstance(pk, basestring) and pk... | Retrieve an object instance. If a single argument is supplied, object is queried by
primary key, else filter queries will be applyed.
If more than one object was found raise MultipleObjectsReturned.
If no object found, raise DoesNotExist.
Raise PermissionDenied if user has no permission ... | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/service/base.py#L77-L102 | [
"def build_permission_name(model_class, prefix):\n \"\"\" Build permission name for model_class (like 'app.add_model'). \"\"\"\n model_name = model_class._meta.object_name.lower()\n app_label = model_class._meta.app_label\n action_name = prefix\n perm = '%s.%s_%s' % (app_label, action_name, model_nam... | class ListServiceMixin(object):
"""
Performe pre-filter in object list to avoid unauthorized access
"""
@nocheckpermission()
def list(self, **filters):
""" Returns a queryset filtering object by user permission. If you want,
you can specify filter arguments.
See https://do... |
snbuback/django_services | django_services/admin/__init__.py | DjangoServicesAdmin.get_object | python | def get_object(self, request, object_id):
queryset = self.queryset(request)
model = queryset.model
try:
object_id = model._meta.pk.to_python(object_id)
return queryset.get(pk=object_id)
except (model.DoesNotExist, ValidationError):
return None | Returns an instance matching the primary key provided. ``None`` is
returned if no match is found (or the object_id failed validation
against the primary key field). | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/admin/__init__.py#L36-L48 | [
"def queryset(self, request):\n service = self.get_service(request)\n qs = service.list()\n return qs\n"
] | class DjangoServicesAdmin(admin.ModelAdmin):
actions = ['delete_selected']
def __init__(self, *args, **kwargs):
if getattr(self, 'service_class', None) is None:
raise RuntimeError("Missing service_class attribute on %s" % self.__class__.__name__)
super(DjangoServicesAdmin, self).__... |
snbuback/django_services | django_services/admin/__init__.py | DjangoServicesAdmin.has_add_permission | python | def has_add_permission(self, request):
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()) | Returns True if the given request has permission to add an object.
Can be overriden by the user in subclasses. | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/admin/__init__.py#L61-L67 | null | class DjangoServicesAdmin(admin.ModelAdmin):
actions = ['delete_selected']
def __init__(self, *args, **kwargs):
if getattr(self, 'service_class', None) is None:
raise RuntimeError("Missing service_class attribute on %s" % self.__class__.__name__)
super(DjangoServicesAdmin, self).__... |
snbuback/django_services | django_services/admin/__init__.py | DjangoServicesAdmin.has_change_permission | python | def has_change_permission(self, request, obj=None):
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_change_permission(), obj) | Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to change the `o... | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/admin/__init__.py#L69-L81 | null | class DjangoServicesAdmin(admin.ModelAdmin):
actions = ['delete_selected']
def __init__(self, *args, **kwargs):
if getattr(self, 'service_class', None) is None:
raise RuntimeError("Missing service_class attribute on %s" % self.__class__.__name__)
super(DjangoServicesAdmin, self).__... |
snbuback/django_services | django_services/admin/__init__.py | DjangoServicesAdmin.has_delete_permission | python | def has_delete_permission(self, request, obj=None):
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission(), obj) | Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to delete the `o... | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/admin/__init__.py#L83-L95 | null | class DjangoServicesAdmin(admin.ModelAdmin):
actions = ['delete_selected']
def __init__(self, *args, **kwargs):
if getattr(self, 'service_class', None) is None:
raise RuntimeError("Missing service_class attribute on %s" % self.__class__.__name__)
super(DjangoServicesAdmin, self).__... |
snbuback/django_services | django_services/admin/__init__.py | DjangoServicesAdmin.delete_view | python | def delete_view(self, request, object_id, extra_context=None):
"The 'delete' admin view for this model."
opts = self.model._meta
app_label = opts.app_label
obj = self.get_object(request, unquote(object_id))
if not self.has_delete_permission(request, obj):
raise Perm... | The 'delete' admin view for this model. | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/admin/__init__.py#L99-L159 | [
"def get_object(self, request, object_id):\n \"\"\"\n Returns an instance matching the primary key provided. ``None`` is\n returned if no match is found (or the object_id failed validation\n against the primary key field).\n \"\"\"\n queryset = self.queryset(request)\n model = queryset.model\n... | class DjangoServicesAdmin(admin.ModelAdmin):
actions = ['delete_selected']
def __init__(self, *args, **kwargs):
if getattr(self, 'service_class', None) is None:
raise RuntimeError("Missing service_class attribute on %s" % self.__class__.__name__)
super(DjangoServicesAdmin, self).__... |
snbuback/django_services | django_services/admin/__init__.py | DjangoServicesAdmin.delete_selected | python | def delete_selected(self, request, queryset):
opts = self.model._meta
app_label = opts.app_label
# Check that the user has delete permission for the actual model
if not self.has_delete_permission(request):
raise PermissionDenied
using = router.db_for_write(self.mode... | Overrides django's default delete_selected action do call _model_.delete() to
pass through services
Default action which deletes the selected objects.
This action first displays a confirmation page whichs shows all the
deleteable objects, or, if the user has no permission one of the re... | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/admin/__init__.py#L161-L234 | [
"def has_delete_permission(self, request, obj=None):\n \"\"\"\n Returns True if the given request has permission to change the given\n Django model instance, the default implementation doesn't examine the\n `obj` parameter.\n\n Can be overriden by the user in subclasses. In such case it should\n r... | class DjangoServicesAdmin(admin.ModelAdmin):
actions = ['delete_selected']
def __init__(self, *args, **kwargs):
if getattr(self, 'service_class', None) is None:
raise RuntimeError("Missing service_class attribute on %s" % self.__class__.__name__)
super(DjangoServicesAdmin, self).__... |
snbuback/django_services | django_services/service/core.py | build_permission_name | python | def build_permission_name(model_class, prefix):
model_name = model_class._meta.object_name.lower()
app_label = model_class._meta.app_label
action_name = prefix
perm = '%s.%s_%s' % (app_label, action_name, model_name)
return perm | Build permission name for model_class (like 'app.add_model'). | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/service/core.py#L15-L21 | null | # encoding: utf-8
import logging
from functools import wraps
from django.core.exceptions import ValidationError, PermissionDenied
LOG = logging.getLogger(__name__)
LOG_PERM = logging.getLogger('%s.perm' % __name__)
METHOD_PERMISSION_TRANSLATION = {
'create': 'add',
'update': 'change'
}
class checkpermissio... |
snbuback/django_services | django_services/service/core.py | checkpermission.get_permission | python | def get_permission(self, service, func):
if self.permission:
perm = self.permission
elif self.prefix is False:
# No permission will be checked
perm = False
elif self.prefix:
perm = build_permission_name(service.model_class, self.prefix)
... | Build permission required to access function "func" | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/service/core.py#L58-L78 | [
"def build_permission_name(model_class, prefix):\n \"\"\" Build permission name for model_class (like 'app.add_model'). \"\"\"\n model_name = model_class._meta.object_name.lower()\n app_label = model_class._meta.app_label\n action_name = prefix\n perm = '%s.%s_%s' % (app_label, action_name, model_nam... | class checkpermission(object):
"""
Decorator only to BaseService methods, to protect it from unauthorized calls.
If no arguments given, permission will be build from method name.
For example, for method 'start' in VirtualMachineService
the default permission required will be 'virtualmachine.start_v... |
snbuback/django_services | django_services/service/core.py | checkpermission.has_perm | python | def has_perm(self, service, perm_name, obj, call_name):
user = service.user
if not (perm_name is False):
if not user.has_perm(perm_name, obj=obj):
LOG_PERM.warn(
u'User %s has no permission %s. Access to %s with obj=%s',
user, perm_name... | Raise PermissionDenied if user has no permission in object | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/service/core.py#L80-L94 | null | class checkpermission(object):
"""
Decorator only to BaseService methods, to protect it from unauthorized calls.
If no arguments given, permission will be build from method name.
For example, for method 'start' in VirtualMachineService
the default permission required will be 'virtualmachine.start_v... |
snbuback/django_services | django_services/service/core.py | BaseService.validate | python | def validate(self, obj):
if not isinstance(obj, self.model_class):
raise ValidationError('Invalid object(%s) for service %s' % (type(obj), type(self)))
LOG.debug(u'Object %s state: %s', self.model_class, obj.__dict__)
obj.full_clean() | Raises django.core.exceptions.ValidationError if any validation error exists | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/service/core.py#L142-L148 | null | class BaseService(object):
__metaclass__ = CheckMethodPermissions
# no_perm = ('model_class',)
'''
Base service class. All bussiness logic must be in services class.
Methods, not starting with '_', will have check permission before call it.
If you want to change permission required to execute t... |
snbuback/django_services | django_services/service/core.py | BaseService.filter_objects | python | def filter_objects(self, objects, perm=None):
if perm is None:
perm = build_permission_name(self.model_class, 'view')
return filter(lambda o: self.user.has_perm(perm, obj=o), objects) | Return only objects with specified permission in objects list. If perm not specified, 'view' perm will be used. | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/service/core.py#L151-L155 | [
"def build_permission_name(model_class, prefix):\n \"\"\" Build permission name for model_class (like 'app.add_model'). \"\"\"\n model_name = model_class._meta.object_name.lower()\n app_label = model_class._meta.app_label\n action_name = prefix\n perm = '%s.%s_%s' % (app_label, action_name, model_nam... | class BaseService(object):
__metaclass__ = CheckMethodPermissions
# no_perm = ('model_class',)
'''
Base service class. All bussiness logic must be in services class.
Methods, not starting with '_', will have check permission before call it.
If you want to change permission required to execute t... |
snbuback/django_services | django_services/api/api.py | exception_translation | python | def exception_translation(func):
@wraps(func)
def decorator(*arg, **kwargs):
try:
return func(*arg, **kwargs)
except InvalidOperationException, e:
return Response(status=status.HTTP_412_PRECONDITION_FAILED, data={'detail': e.message}, headers={'Content-Type': 'application... | Catch exception and build correct api response for it. | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/api/api.py#L26-L36 | null | # -*- coding:utf-8 -*-
import logging
import json
from functools import wraps
from django.http import Http404
from rest_framework import generics, mixins, status, viewsets
from rest_framework.response import Response
from django_services.service.exceptions import InvalidOperationException
LIST = 'list'
CREATE = 'crea... |
snbuback/django_services | django_services/api/api.py | getattr_in_cls_list | python | def getattr_in_cls_list(cls_list, attr, default):
for cls in cls_list:
if hasattr(cls, attr):
return getattr(cls, attr)
return default | Search for an attribute (attr) in class list (cls_list). Returns
attribute value if exists or None if not. | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/api/api.py#L39-L45 | null | # -*- coding:utf-8 -*-
import logging
import json
from functools import wraps
from django.http import Http404
from rest_framework import generics, mixins, status, viewsets
from rest_framework.response import Response
from django_services.service.exceptions import InvalidOperationException
LIST = 'list'
CREATE = 'crea... |
snbuback/django_services | django_services/api/api.py | DjangoServiceAPI.service | python | def service(self):
'''
Instantiate service class with django http_request
'''
service_class = getattr(self, 'service_class')
service = service_class(self.http_request)
return service | Instantiate service class with django http_request | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/api/api.py#L154-L160 | null | class DjangoServiceAPI(viewsets.GenericViewSet):
__metaclass__ = create_api_class
@property
def http_request(self):
return self.request._request
@property
def user(self):
return self.http_request and self.http_request.user
@property
def get_queryset(self):
# allo... |
snbuback/django_services | django_services/api/api.py | DjangoServiceAPI.get_object | python | def get_object(self, queryset=None):
try:
pk = self.kwargs.get('pk', None)
# allow serializer without service
obj = self.service.get(pk)
return obj
except self.model.DoesNotExist:
raise Http404() | Override default to add support for object-level permissions. | train | https://github.com/snbuback/django_services/blob/58cbdea878bb11197add0ed1008a9206e4d92671/django_services/api/api.py#L167-L178 | null | class DjangoServiceAPI(viewsets.GenericViewSet):
__metaclass__ = create_api_class
@property
def http_request(self):
return self.request._request
@property
def user(self):
return self.http_request and self.http_request.user
@property
def service(self):
'''
I... |
kmike/django-generic-images | generic_images/admin.py | attachedimage_form_factory | python | def attachedimage_form_factory(lang='en', debug=False):
''' Returns ModelForm class to be used in admin.
'lang' is the language for GearsUploader (can be 'en' and 'ru' at the
moment).
'''
yui = '' if debug else '.yui'
class _AttachedImageAdminForm(forms.ModelForm):
caption = for... | Returns ModelForm class to be used in admin.
'lang' is the language for GearsUploader (can be 'en' and 'ru' at the
moment). | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_images/admin.py#L10-L29 | null | from django import forms
from django.contrib import admin
from django.contrib.contenttypes.generic import GenericTabularInline
from django.utils.translation import ugettext_lazy as _
from generic_images.models import AttachedImage
admin.site.register(AttachedImage)
AttachedImageAdminForm = attachedimage_form_factor... |
kmike/django-generic-images | generic_images/admin.py | attachedimages_inline_factory | python | def attachedimages_inline_factory(lang='en', max_width='', debug=False):
''' Returns InlineModelAdmin for attached images.
'lang' is the language for GearsUploader (can be 'en' and 'ru' at the
moment). 'max_width' is default resize width parameter to be set in
widget.
'''
class _At... | Returns InlineModelAdmin for attached images.
'lang' is the language for GearsUploader (can be 'en' and 'ru' at the
moment). 'max_width' is default resize width parameter to be set in
widget. | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_images/admin.py#L35-L48 | null | from django import forms
from django.contrib import admin
from django.contrib.contenttypes.generic import GenericTabularInline
from django.utils.translation import ugettext_lazy as _
from generic_images.models import AttachedImage
admin.site.register(AttachedImage)
def attachedimage_form_factory(lang='en', debug=Fal... |
kmike/django-generic-images | generic_images/managers.py | ImagesAndUserManager.select_with_main_images | python | def select_with_main_images(self, limit=None, **kwargs):
''' Select all objects with filters passed as kwargs.
For each object it's main image instance is accessible as ``object.main_image``.
Results can be limited using ``limit`` parameter.
Selection is performed using on... | Select all objects with filters passed as kwargs.
For each object it's main image instance is accessible as ``object.main_image``.
Results can be limited using ``limit`` parameter.
Selection is performed using only 2 or 3 sql queries. | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_images/managers.py#L26-L34 | null | class ImagesAndUserManager(models.Manager):
""" Useful manager for models that have AttachedImage (or subclass) field
and 'injector=GenericIngector()' manager.
"""
def __init__(self, *args, **kwargs):
try:
image_model_class = kwargs.pop('image_model_class')
except... |
kmike/django-generic-images | generic_images/managers.py | AttachedImageManager.get_main_for | python | def get_main_for(self, model):
'''
Returns main image for given model
'''
try:
return self.for_model(model).get(is_main=True)
except models.ObjectDoesNotExist:
return None | Returns main image for given model | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_images/managers.py#L54-L61 | [
"def for_model(self, model, content_type=None):\n ''' Returns all objects that are attached to given model '''\n content_type = content_type or ContentType.objects.get_for_model(model)\n kwargs = {\n self.ct_field: content_type,\n self.fk_field: model.pk\n }\n o... | class AttachedImageManager(GenericModelManager):
''' Manager with helpful functions for attached images
'''
def get_for_model(self, model):
''' Returns all images that are attached to given model.
Deprecated. Use `for_model` instead.
'''
return self.for_model(model)
|
kmike/django-generic-images | generic_utils/managers.py | RelatedInjector.inject_to | python | def inject_to(self, objects, field_name, get_inject_object = lambda obj: obj,
select_related = None, **kwargs):
'''
``objects`` is an iterable. Related objects
will be attached to elements of this iterable.
``field_name`` is the attached object attribute name
... | ``objects`` is an iterable. Related objects
will be attached to elements of this iterable.
``field_name`` is the attached object attribute name
``get_injector_object`` is a callable that takes object in `objects`
iterable. Related objects will be available as an attribute of th... | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_utils/managers.py#L20-L90 | [
"def inject_to(self, objects, field_name, get_inject_object = lambda obj: obj,\n",
"def inject_to(self, objects, field_name, get_inject_object = lambda obj: obj, **kwargs):\n"
] | class RelatedInjector(models.Manager):
""" Manager that can emulate ``select_related`` fetching
reverse relations using 1 additional SQL query.
"""
def __init__(self, fk_field='object_id', *args, **kwargs):
self.fk_field = fk_field
super(RelatedInjector, self).__init__(*args, **kwarg... |
kmike/django-generic-images | generic_utils/managers.py | GenericInjector.inject_to | python | def inject_to(self, objects, field_name, get_inject_object = lambda obj: obj, **kwargs):
'''
``objects`` is an iterable. Images (or other generic-related model instances)
will be attached to elements of this iterable.
``field_name`` is the attached object attribute name
``g... | ``objects`` is an iterable. Images (or other generic-related model instances)
will be attached to elements of this iterable.
``field_name`` is the attached object attribute name
``get_inject_object`` is a callable that takes object in `objects` iterable.
Image will be available... | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_utils/managers.py#L130-L159 | [
"def inject_to(self, objects, field_name, get_inject_object = lambda obj: obj,\n select_related = None, **kwargs):\n '''\n ``objects`` is an iterable. Related objects\n will be attached to elements of this iterable.\n\n ``field_name`` is the attached object attribute name\n\n ``get_i... | class GenericInjector(RelatedInjector):
''' RelatedInjector but for GenericForeignKey's.
Manager for selecting all generic-related objects in one (two) SQL queries.
Selection is performed for a list of objects. Resulting data is aviable as attribute
of original model. Only one instance per o... |
kmike/django-generic-images | generic_utils/managers.py | GenericModelManager.for_model | python | def for_model(self, model, content_type=None):
''' Returns all objects that are attached to given model '''
content_type = content_type or ContentType.objects.get_for_model(model)
kwargs = {
self.ct_field: content_type,
self.fk_field: model.pk
... | Returns all objects that are attached to given model | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_utils/managers.py#L169-L177 | null | class GenericModelManager(models.Manager):
""" Manager with for_model method. """
def __init__(self, *args, **kwargs):
self.ct_field, self.fk_field = _pop_data_from_kwargs(kwargs)
super(GenericModelManager, self).__init__(*args, **kwargs)
|
kmike/django-generic-images | generic_utils/__init__.py | get_template_search_list | python | def get_template_search_list(app_name, object, template_name):
ctype = ContentType.objects.get_for_model(object)
return [
u"%s/%s/%s/%s" % (app_name, ctype.app_label, ctype.model, template_name),
u"%s/%s/%s" % (app_name, ctype.app_label, template_name,),
u"%s/%s" % (app_name, template_na... | Returns template search list.
Example::
>>> from django.contrib.auth.models import User
>>> user=User()
>>> get_template_search_list('my_app', user, 'list.html')
[u'my_app/auth/user/list.html', u'my_app/auth/list.html', 'my_app/list.html'] | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_utils/__init__.py#L3-L18 | null | from django.contrib.contenttypes.models import ContentType
def get_template_search_list(app_name, object, template_name):
""" Returns template search list.
Example::
>>> from django.contrib.auth.models import User
>>> user=User()
>>> get_template_search_list('my_app', user, 'list.html')
[u... |
kmike/django-generic-images | generic_utils/templatetags.py | validate_params | python | def validate_params(bits, arguments_count, keyword_positions):
'''
Raises exception if passed params (`bits`) do not match signature.
Signature is defined by `arguments_count` (acceptible number of params) and
keyword_positions (dictionary with positions in keys and keywords in values,
... | Raises exception if passed params (`bits`) do not match signature.
Signature is defined by `arguments_count` (acceptible number of params) and
keyword_positions (dictionary with positions in keys and keywords in values,
for ex. {2:'by', 4:'of', 5:'type', 7:'as'}). | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_utils/templatetags.py#L9-L23 | null | from django import template
class InvalidParamsError(template.TemplateSyntaxError):
''' Custom exception class to distinguish usual TemplateSyntaxErrors
and validation errors for templatetags introduced by ``validate_params``
function'''
pass
def validate_params(bits, arguments_count, keyword... |
kmike/django-generic-images | generic_images/fields.py | force_recalculate | python | def force_recalculate(obj):
''' Recalculate all ImageCountField and UserImageCountField fields
in object ``obj``.
This should be used if auto-updating of these fields was disabled for
some reason.
To disable auto-update when saving AttachedImage instance
(... | Recalculate all ImageCountField and UserImageCountField fields
in object ``obj``.
This should be used if auto-updating of these fields was disabled for
some reason.
To disable auto-update when saving AttachedImage instance
(for example when you need to save a ... | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_images/fields.py#L18-L38 | null | #coding: utf-8
'''
django-generic-images provides fields for storing information about
attached images count. Value is stored in model that images are
attached to. Value is updated automatically when image is saved or deleted.
Access to this value is much faster than additional "count()" queries.
'''
from django.db ... |
kmike/django-generic-images | generic_utils/app_utils.py | get_site_decorator | python | def get_site_decorator(site_param='site', obj_param='obj', context_param='context'):
''' It is a function that returns decorator factory useful for PluggableSite
views. This decorator factory returns decorator that do some
boilerplate work and make writing PluggableSite views easier.
It pass... | It is a function that returns decorator factory useful for PluggableSite
views. This decorator factory returns decorator that do some
boilerplate work and make writing PluggableSite views easier.
It passes PluggableSite instance to decorated view,
retreives and passes object that site is... | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_utils/app_utils.py#L10-L61 | null | #coding: utf-8
from django.conf.urls.defaults import *
from django.http import Http404
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.db import models
from django.db.models.query import QuerySet
from django.utils.functional import wraps
def simple_getter(queryset,... |
kmike/django-generic-images | generic_utils/app_utils.py | simple_getter | python | def simple_getter(queryset, object_regex=None, lookup_field=None):
''' Returns simple object_getter function for use with PluggableSite.
It takes 'queryset' with QuerySet or Model instance, 'object_regex' with
url regex and 'lookup_field' with lookup field.
'''
object_regex = object_regex or r'\d+'
... | Returns simple object_getter function for use with PluggableSite.
It takes 'queryset' with QuerySet or Model instance, 'object_regex' with
url regex and 'lookup_field' with lookup field. | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_utils/app_utils.py#L64-L81 | null | #coding: utf-8
from django.conf.urls.defaults import *
from django.http import Http404
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.db import models
from django.db.models.query import QuerySet
from django.utils.functional import wraps
def get_site_decorator(site_p... |
kmike/django-generic-images | generic_utils/app_utils.py | PluggableSite.reverse | python | def reverse(self, url, args=None, kwargs=None):
''' Reverse an url taking self.app_name in account '''
return reverse("%s:%s" % (self.instance_name, url,),
args=args,
kwargs=kwargs,
current_app = self.app_name) | Reverse an url taking self.app_name in account | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_utils/app_utils.py#L121-L126 | null | class PluggableSite(object):
''' Base class for reusable apps.
The approach is similar to django AdminSite.
For usage case please check photo_albums app.
'''
def __init__(self,
instance_name,
app_name,
queryset = None,
objec... |
kmike/django-generic-images | generic_utils/app_utils.py | PluggableSite.make_regex | python | def make_regex(self, url):
'''
Make regex string for ``PluggableSite`` urlpatterns: prepend url
with parent object's url and app name.
See also: http://code.djangoproject.com/ticket/11559.
'''
return r"^%s/%s%s$" % (self.object_getter.regex, self.app_name, ur... | Make regex string for ``PluggableSite`` urlpatterns: prepend url
with parent object's url and app name.
See also: http://code.djangoproject.com/ticket/11559. | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_utils/app_utils.py#L141-L148 | null | class PluggableSite(object):
''' Base class for reusable apps.
The approach is similar to django AdminSite.
For usage case please check photo_albums app.
'''
def __init__(self,
instance_name,
app_name,
queryset = None,
objec... |
kmike/django-generic-images | generic_images/models.py | ReplaceOldImageModel._replace_old_image | python | def _replace_old_image(self):
''' Override this in subclass if you don't want
image replacing or want to customize image replacing
'''
try:
old_obj = self.__class__.objects.get(pk=self.pk)
if old_obj.image.path != self.image.path:
path = old_ob... | Override this in subclass if you don't want
image replacing or want to customize image replacing | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_images/models.py#L44-L54 | null | class ReplaceOldImageModel(BaseImageModel):
'''
Abstract Model class with image field.
If the file for image is re-uploaded, old file is deleted.
'''
def save(self, *args, **kwargs):
if self.pk:
self._replace_old_image()
super(ReplaceOldImageModel, self).save(*a... |
kmike/django-generic-images | generic_images/models.py | AbstractAttachedImage.next | python | def next(self):
''' Returns next image for same content_object and None if image is
the last. '''
try:
return self.__class__.objects.for_model(self.content_object,
self.content_type).\
filter(order__lt=se... | Returns next image for same content_object and None if image is
the last. | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_images/models.py#L102-L110 | null | class AbstractAttachedImage(ReplaceOldImageModel, GenericModelBase):
'''
Abstract Image model that can be attached to any other Django model
using generic relations.
.. attribute:: is_main
BooleanField. Whether the image is the main image for object.
This field is s... |
kmike/django-generic-images | generic_images/models.py | AbstractAttachedImage.previous | python | def previous(self):
''' Returns previous image for same content_object and None if image
is the first. '''
try:
return self.__class__.objects.for_model(self.content_object,
self.content_type).\
filter(ord... | Returns previous image for same content_object and None if image
is the first. | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_images/models.py#L112-L120 | null | class AbstractAttachedImage(ReplaceOldImageModel, GenericModelBase):
'''
Abstract Image model that can be attached to any other Django model
using generic relations.
.. attribute:: is_main
BooleanField. Whether the image is the main image for object.
This field is s... |
kmike/django-generic-images | generic_images/models.py | AbstractAttachedImage.get_order_in_album | python | def get_order_in_album(self, reversed_ordering=True):
''' Returns image order number. It is calculated as (number+1) of images
attached to the same content_object whose order is greater
(if 'reverse_ordering' is True) or lesser (if 'reverse_ordering' is
False) than image's order.
... | Returns image order number. It is calculated as (number+1) of images
attached to the same content_object whose order is greater
(if 'reverse_ordering' is True) or lesser (if 'reverse_ordering' is
False) than image's order. | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_images/models.py#L122-L131 | null | class AbstractAttachedImage(ReplaceOldImageModel, GenericModelBase):
'''
Abstract Image model that can be attached to any other Django model
using generic relations.
.. attribute:: is_main
BooleanField. Whether the image is the main image for object.
This field is s... |
kmike/django-generic-images | generic_images/models.py | AbstractAttachedImage.get_upload_path | python | def get_upload_path(self, filename):
''' Override this in proxy subclass to customize upload path.
Default upload path is
:file:`/media/images/<user.id>/<filename>.<ext>`
or :file:`/media/images/common/<filename>.<ext>` if user is not set.
``<filename>`` is retur... | Override this in proxy subclass to customize upload path.
Default upload path is
:file:`/media/images/<user.id>/<filename>.<ext>`
or :file:`/media/images/common/<filename>.<ext>` if user is not set.
``<filename>`` is returned by
:meth:`~generic_images.models.... | train | https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_images/models.py#L164-L179 | [
" def get_file_name(self, filename):\n ''' Returns file name (without path and extenstion)\n for uploaded image. Default is 'max(pk)+1'.\n Override this in subclass or assign another functions per-instance\n if you want different file names (ex: random string).\n ''... | class AbstractAttachedImage(ReplaceOldImageModel, GenericModelBase):
'''
Abstract Image model that can be attached to any other Django model
using generic relations.
.. attribute:: is_main
BooleanField. Whether the image is the main image for object.
This field is s... |
zulily/pudl | pudl/ad_group.py | ADGroup.group | python | def group(self, base_dn, samaccountname, attributes=(), explicit_membership_only=False):
groups = self.groups(base_dn, samaccountnames=[samaccountname], attributes=attributes,
explicit_membership_only=explicit_membership_only)
try:
# Usually we will find a matc... | Produces a single, populated ADGroup object through the object factory.
Does not populate attributes for the caller instance.
sAMAccountName may not be present in group objects in modern AD schemas.
Searching by common name and object class (group) may be an alternative
approach if requ... | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_group.py#L34-L57 | [
"def groups(self, base_dn, samaccountnames=(), attributes=(), explicit_membership_only=False):\n \"\"\"Gathers a list of ADGroup objects\n\n sAMAccountName may not be present in group objects in modern AD schemas.\n Searching by common name and object class (group) may be an alternative\n approach if re... | class ADGroup(ADObject):
"""A class to represent AD group objects. Includes a number of
helper methods, particularly object-factory related.
ADGroup objects have minimal depth, with attributes set to
strings or lists. Available attributes are dependent
on the results returned by the LDAP query.
... |
zulily/pudl | pudl/ad_group.py | ADGroup.groups | python | def groups(self, base_dn, samaccountnames=(), attributes=(), explicit_membership_only=False):
ad_groups = []
search_filter = '(&(objectClass=group)(!(objectClass=user))(!(objectClass=computer)){0})'
# If no samaccountnames specified, filter will pull all group objects under
# base_dn
... | Gathers a list of ADGroup objects
sAMAccountName may not be present in group objects in modern AD schemas.
Searching by common name and object class (group) may be an alternative
approach if required in the future.
:param str base_dn: The base DN to search within
:param list sa... | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_group.py#L60-L106 | [
"def _object_factory(self, search_result):\n \"\"\"Given a single search result, create and return an object\n\n :param tuple search_result: a single search result returned by an LDAP query,\n position 0 is the DN and position 1 is a dictionary of key/value pairs\n\n :return: A single AD object inst... | class ADGroup(ADObject):
"""A class to represent AD group objects. Includes a number of
helper methods, particularly object-factory related.
ADGroup objects have minimal depth, with attributes set to
strings or lists. Available attributes are dependent
on the results returned by the LDAP query.
... |
zulily/pudl | pudl/scripts/cli.py | main | python | def main():
# Parse all command line argument
args = parse_arguments().parse_args()
# Setup logging
configure_logging(args)
logging.debug(args)
# Prompt for a password if necessary
if not args.password:
password = getpass.getpass(prompt='Password ({0}): '.format(args.user))
els... | Do some stuff | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/scripts/cli.py#L34-L76 | [
"def serialize(ad_objects, output_format='json', indent=2, attributes_only=False):\n \"\"\"Serialize the object to the specified format\n\n :param ad_objects list: A list of ADObjects to serialize\n :param output_format str: The output format, json or yaml. Defaults to json\n :param indent int: The num... | #! /usr/bin/env python
#
# Copyright (C) 2015 zulily, llc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
zulily/pudl | pudl/scripts/cli.py | configure_logging | python | def configure_logging(args):
log_format = logging.Formatter('%(levelname)s:%(name)s:line %(lineno)s:%(message)s')
log_level = logging.INFO if args.verbose else logging.WARN
log_level = logging.DEBUG if args.debug else log_level
console = logging.StreamHandler()
console.setFormatter(log_format)
c... | Logging to console | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/scripts/cli.py#L79-L92 | null | #! /usr/bin/env python
#
# Copyright (C) 2015 zulily, llc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
zulily/pudl | pudl/scripts/cli.py | parse_arguments | python | def parse_arguments():
# Pull a few settings from the environment, should they exist
base_dn = os.environ['PUDL_BASE_DN'] if 'PUDL_BASE_DN' in os.environ \
else 'OU=Departments,DC=example,DC=com'
domain = os.environ['PUDL_DOMAIN'].upper() if 'PUDL_DOMAIN' in os.environ else 'EXAMPLE'
page_... | Collect command-line arguments. Let the caller run parse_args(), as
sphinx-argparse requires a function that returns an instance of
argparse.ArgumentParser | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/scripts/cli.py#L95-L199 | null | #! /usr/bin/env python
#
# Copyright (C) 2015 zulily, llc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
zulily/pudl | pudl/ad_computer.py | ADComputer.computer | python | def computer(self, base_dn, samaccountname, attributes=()):
computers = self.computers(base_dn, samaccountnames=[samaccountname], attributes=attributes)
try:
# Usually we will find a match, but perhaps not always
return computers[0]
except IndexError:
loggin... | Produces a single, populated ADComputer object through the object factory.
Does not populate attributes for the caller instance.
:param str base_dn: The base DN to search within
:param str samaccountname: The computer's sAMAccountName
:param list attributes: Object attributes to populat... | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_computer.py#L30-L48 | [
"def computers(self, base_dn, samaccountnames=(), attributes=()):\n \"\"\"Gathers a list of ADComputer objects\n\n :param str base_dn: The base DN to search within\n :param list samaccountnames: A list of computer names for which objects will be\n created, defaults to all computers if unspecified\n ... | class ADComputer(ADObject):
"""A class to represent AD computer objects. Includes a number of
helper methods, particularly object-factory related.
ADComputer objects have minimal depth, with attributes set to
strings or lists. Available attributes are dependent
on the results returned by the LDAP... |
zulily/pudl | pudl/ad_computer.py | ADComputer.computers | python | def computers(self, base_dn, samaccountnames=(), attributes=()):
ad_computers = []
search_filter = '(&(objectClass=computer){0})'
# If no samaccountnames specified, filter will pull all computer objects under
# base_dn
if not samaccountnames:
search_filter = search_f... | Gathers a list of ADComputer objects
:param str base_dn: The base DN to search within
:param list samaccountnames: A list of computer names for which objects will be
created, defaults to all computers if unspecified
:param list attributes: Object attributes to populate, defaults to ... | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_computer.py#L51-L88 | [
"def _object_factory(self, search_result):\n \"\"\"Given a single search result, create and return an object\n\n :param tuple search_result: a single search result returned by an LDAP query,\n position 0 is the DN and position 1 is a dictionary of key/value pairs\n\n :return: A single AD object inst... | class ADComputer(ADObject):
"""A class to represent AD computer objects. Includes a number of
helper methods, particularly object-factory related.
ADComputer objects have minimal depth, with attributes set to
strings or lists. Available attributes are dependent
on the results returned by the LDAP... |
zulily/pudl | pudl/ad_object.py | ADObject.to_dict | python | def to_dict(self):
o_copy = copy.copy(self)
# Remove some stuff that is not likely related to AD attributes
for attribute in dir(self):
if attribute == 'logger' or attribute == 'adq':
try:
delattr(o_copy, attribute)
except Attribute... | Prepare a minimal dictionary with keys mapping to attributes for
the current instance. | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_object.py#L32-L46 | null | class ADObject(object):
"""A base class for AD objects."""
def __init__(self, adq):
"""ADObject constructor"""
# Setup logging, assumes a root logger already exists with handlers
self.logger = logging.getLogger(__name__)
self.adq = adq
def samaccountname(self, base_dn, d... |
zulily/pudl | pudl/ad_object.py | ADObject.samaccountname | python | def samaccountname(self, base_dn, distinguished_name):
mappings = self.samaccountnames(base_dn, [distinguished_name])
try:
# Usually we will find a match, but perhaps not always
return mappings[distinguished_name]
except KeyError:
logging.info("%s - unable to... | Retrieve the sAMAccountName for a specific DistinguishedName
:param str base_dn: The base DN to search within
:param list distinguished_name: The base DN to search within
:param list attributes: Object attributes to populate, defaults to all
:return: A populated ADUser object
:... | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_object.py#L49-L66 | [
"def samaccountnames(self, base_dn, distinguished_names):\n \"\"\"Retrieve the sAMAccountNames for the specified DNs\n\n :param str base_dn: The base DN to search within\n :param list distinguished_name: A list of distinguished names for which to\n retrieve sAMAccountNames\n\n :return: Key/value ... | class ADObject(object):
"""A base class for AD objects."""
def __init__(self, adq):
"""ADObject constructor"""
# Setup logging, assumes a root logger already exists with handlers
self.logger = logging.getLogger(__name__)
self.adq = adq
def to_dict(self):
"""Prepar... |
zulily/pudl | pudl/ad_object.py | ADObject.samaccountnames | python | def samaccountnames(self, base_dn, distinguished_names):
attributes = ['sAMAccountName']
search_filter = '(|{0})'.format(''.join(['(DistinguishedName={0})'.format(dn)
for dn in distinguished_names]))
logging.debug('%s Search filter: %s', self.__cl... | Retrieve the sAMAccountNames for the specified DNs
:param str base_dn: The base DN to search within
:param list distinguished_name: A list of distinguished names for which to
retrieve sAMAccountNames
:return: Key/value pairs mapping DistinguishedName to sAMAccountName
:rtyp... | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_object.py#L69-L88 | null | class ADObject(object):
"""A base class for AD objects."""
def __init__(self, adq):
"""ADObject constructor"""
# Setup logging, assumes a root logger already exists with handlers
self.logger = logging.getLogger(__name__)
self.adq = adq
def to_dict(self):
"""Prepar... |
zulily/pudl | pudl/ad_object.py | ADObject._object_factory | python | def _object_factory(self, search_result):
class_name = self.__class__.__name__
module = self.__module__
logging.debug('Creating object of type %s for DN: %s', class_name, search_result[0])
module = importlib.import_module('{0}'.format(module))
class_ = getattr(module, class_name)... | Given a single search result, create and return an object
:param tuple search_result: a single search result returned by an LDAP query,
position 0 is the DN and position 1 is a dictionary of key/value pairs
:return: A single AD object instance
:rtype: Object (ADUser, ADGroup, etc.) | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_object.py#L91-L136 | null | class ADObject(object):
"""A base class for AD objects."""
def __init__(self, adq):
"""ADObject constructor"""
# Setup logging, assumes a root logger already exists with handlers
self.logger = logging.getLogger(__name__)
self.adq = adq
def to_dict(self):
"""Prepar... |
zulily/pudl | pudl/ad_user.py | ADUser.user | python | def user(self, base_dn, samaccountname, attributes=(), explicit_membership_only=False):
users = self.users(base_dn, samaccountnames=[samaccountname],
attributes=attributes, explicit_membership_only=explicit_membership_only)
try:
# Usually we will find a match, bu... | Produces a single, populated ADUser object through the object factory.
Does not populate attributes for the caller instance.
:param str base_dn: The base DN to search within
:param str samaccountname: The user's sAMAccountName
:param list attributes: Object attributes to populate, defau... | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_user.py#L38-L59 | [
"def users(self, base_dn, samaccountnames=(), attributes=(), explicit_membership_only=False):\n \"\"\"Gathers a list of ADUser objects\n\n :param str base_dn: The base DN to search within\n :param list attributes: Object attributes to populate, defaults to all\n :param list samaccountnames: A list of us... | class ADUser(ADObject):
"""A class to represent AD user objects. Includes a number of
helper methods, particularly object-factory related.
ADUser objects have minimal depth, with attributes set to
strings or lists. Available attributes are dependent
on the results returned by the LDAP query.
... |
zulily/pudl | pudl/ad_user.py | ADUser.users | python | def users(self, base_dn, samaccountnames=(), attributes=(), explicit_membership_only=False):
ad_users = []
search_filter = '(&(objectClass=user)(!(objectClass=group))(!(objectClass=computer)){0})'
# If no samaccountnames specified, filter will pull all user objects under
# base_dn
... | Gathers a list of ADUser objects
:param str base_dn: The base DN to search within
:param list attributes: Object attributes to populate, defaults to all
:param list samaccountnames: A list of usernames for which objects will be
created, defaults to all users if unspecified
:... | train | https://github.com/zulily/pudl/blob/761eec76841964780e759e6bf6d5f06a54844a80/pudl/ad_user.py#L63-L110 | [
"def _object_factory(self, search_result):\n \"\"\"Given a single search result, create and return an object\n\n :param tuple search_result: a single search result returned by an LDAP query,\n position 0 is the DN and position 1 is a dictionary of key/value pairs\n\n :return: A single AD object inst... | class ADUser(ADObject):
"""A class to represent AD user objects. Includes a number of
helper methods, particularly object-factory related.
ADUser objects have minimal depth, with attributes set to
strings or lists. Available attributes are dependent
on the results returned by the LDAP query.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.