INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Add plugin arguments to argument parser. | def add_plugin_arguments(self, parser):
"""Add plugin arguments to argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The main haas ArgumentParser.
"""
for manager in self.hook_managers.values():
if len(list(manager)) == 0:
... |
Get enabled plugins for specified hook name. | def get_enabled_hook_plugins(self, hook, args, **kwargs):
"""Get enabled plugins for specified hook name.
"""
manager = self.hook_managers[hook]
if len(list(manager)) == 0:
return []
return [
plugin for plugin in manager.map(
self._create_... |
Get mutually - exlusive plugin for plugin namespace. | def get_driver(self, namespace, parsed_args, **kwargs):
"""Get mutually-exlusive plugin for plugin namespace.
"""
option, dest = self._namespace_to_option(namespace)
dest_prefix = '{0}_'.format(dest)
driver_name = getattr(parsed_args, dest, 'default')
driver_extension = ... |
Get transaction description ( for logging purposes ) | def get_description(self):
"""
Get transaction description (for logging purposes)
"""
if self.card:
card_description = self.card.get_description()
else:
card_description = 'Cardless'
if card_description:
card_description += ' | '
... |
Set transaction amount | def set_amount(self, amount):
"""
Set transaction amount
"""
if amount:
try:
self.IsoMessage.FieldData(4, int(amount))
except ValueError:
self.IsoMessage.FieldData(4, 0)
self.rebuild() |
Expected outcome of the transaction ( APPROVED or DECLINED ) | def set_expected_action(self, expected_response_action):
"""
Expected outcome of the transaction ('APPROVED' or 'DECLINED')
"""
if expected_response_action.upper() not in ['APPROVED', 'APPROVE', 'DECLINED', 'DECLINE']:
return False
self.expected_response_action = exp... |
TODO: 95 TVR 82 app_int_prof | def build_emv_data(self):
"""
TODO:
95 TVR
82 app_int_prof
"""
emv_data = ''
emv_data += self.TLV.build({'82': self._get_app_interchange_profile()})
emv_data += self.TLV.build({'9A': get_date()})
emv_data += self.TLV.build({'95': self.term.g... |
Set transaction currency code from given currency id e. g. set 840 from USD | def set_currency(self, currency_id):
"""
Set transaction currency code from given currency id, e.g. set 840 from 'USD'
"""
try:
self.currency = currency_codes[currency_id]
self.IsoMessage.FieldData(49, self.currency)
self.rebuild()
except KeyEr... |
Output the aggregate block count results. | def finalize(self):
"""Output the aggregate block count results."""
for name, count in sorted(self.blocks.items(), key=lambda x: x[1]):
print('{:3} {}'.format(count, name))
print('{:3} total'.format(sum(self.blocks.values()))) |
Run and return the results from the BlockCounts plugin. | def analyze(self, scratch, **kwargs):
"""Run and return the results from the BlockCounts plugin."""
file_blocks = Counter()
for script in self.iter_scripts(scratch):
for name, _, _ in self.iter_blocks(script.blocks):
file_blocks[name] += 1
self.blocks.update(f... |
Run and return the results form the DeadCode plugin. | def analyze(self, scratch, **kwargs):
"""Run and return the results form the DeadCode plugin.
The variable_event indicates that the Scratch file contains at least
one instance of a broadcast event based on a variable. When
variable_event is True, dead code scripts reported by this plugi... |
Output the number of instances that contained dead code. | def finalize(self):
"""Output the number of instances that contained dead code."""
if self.total_instances > 1:
print('{} of {} instances contained dead code.'
.format(self.dead_code_instances, self.total_instances)) |
Show help and basic usage | def show_help(name):
"""
Show help and basic usage
"""
print('Usage: python3 {} [OPTIONS]... '.format(name))
print('ISO8583 message client')
print(' -v, --verbose\t\tRun transactions verbosely')
print(' -p, --port=[PORT]\t\tTCP port to connect to, 1337 by default')
print(' -s, --serve... |
Run transactions interactively ( by asking user which transaction to run ) | def _run_interactive(self):
"""
Run transactions interactively (by asking user which transaction to run)
"""
self.term.connect()
self._show_available_transactions()
while True:
trxn_type = self._user_input('\nEnter transaction to send: ')
... |
Finds the top - level directory of a project given a start directory inside the project. | def find_top_level_directory(start_directory):
"""Finds the top-level directory of a project given a start directory
inside the project.
Parameters
----------
start_directory : str
The directory in which test discovery will start.
"""
top_level = start_directory
while os.path.i... |
Do test case discovery. | def discover(self, start, top_level_directory=None, pattern='test*.py'):
"""Do test case discovery.
This is the top-level entry-point for test discovery.
If the ``start`` argument is a drectory, then ``haas`` will
discover all tests in the package contained in that directory.
... |
Find all tests in a package or module or load a single test case if a class or test inside a module was specified. | def discover_by_module(self, module_name, top_level_directory=None,
pattern='test*.py'):
"""Find all tests in a package or module, or load a single test case if
a class or test inside a module was specified.
Parameters
----------
module_name : str
... |
Find and load a single TestCase or TestCase method from a module. | def discover_single_case(self, module, case_attributes):
"""Find and load a single TestCase or TestCase method from a module.
Parameters
----------
module : module
The imported Python module containing the TestCase to be
loaded.
case_attributes : list
... |
Run test discovery in a directory. | def discover_by_directory(self, start_directory, top_level_directory=None,
pattern='test*.py'):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
top... |
Run test discovery on a single file. | def discover_by_file(self, start_filepath, top_level_directory=None):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
top_level_directory : str
The path to the top-level ... |
Set proper headers. | def _set_options_headers(self, methods):
""" Set proper headers.
Sets following headers:
Allow
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Arguments:
:methods: Sequence of HTTP method names that are value for
request... |
Get names of HTTP methods that can be used at requested URI. | def _get_handled_methods(self, actions_map):
""" Get names of HTTP methods that can be used at requested URI.
Arguments:
:actions_map: Map of actions. Must have the same structure as
self._item_actions and self._collection_actions
"""
methods = ('OPTIONS',)
... |
Handle collection OPTIONS request. | def item_options(self, **kwargs):
""" Handle collection OPTIONS request.
Singular route requests are handled a bit differently because
singular views may handle POST requests despite being registered
as item routes.
"""
actions = self._item_actions.copy()
if self... |
Handle collection item OPTIONS request. | def collection_options(self, **kwargs):
""" Handle collection item OPTIONS request. """
methods = self._get_handled_methods(self._collection_actions)
return self._set_options_headers(methods) |
Wrap: func: to perform aggregation on: func: call. | def wrap(self, func):
""" Wrap :func: to perform aggregation on :func: call.
Should be called with view instance methods.
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
try:
return self.aggregate()
except KeyError:
retu... |
Pop and return aggregation params from query string params. | def pop_aggregations_params(self):
""" Pop and return aggregation params from query string params.
Aggregation params are expected to be prefixed(nested under) by
any of `self._aggregations_keys`.
"""
from nefertari.view import BaseView
self._query_params = BaseView.conv... |
Recursively get values under the field key. | def get_aggregations_fields(cls, params):
""" Recursively get values under the 'field' key.
Is used to get names of fields on which aggregations should be
performed.
"""
fields = []
for key, val in params.items():
if isinstance(val, dict):
fie... |
Check per - field privacy rules in aggregations. | def check_aggregations_privacy(self, aggregations_params):
""" Check per-field privacy rules in aggregations.
Privacy is checked by making sure user has access to the fields
used in aggregations.
"""
fields = self.get_aggregations_fields(aggregations_params)
fields_dict ... |
Perform aggregation and return response. | def aggregate(self):
""" Perform aggregation and return response. """
from nefertari.elasticsearch import ES
aggregations_params = self.pop_aggregations_params()
if self.view._auth_enabled:
self.check_aggregations_privacy(aggregations_params)
self.stub_wrappers()
... |
Turn this a: 2 b: blabla c: True a: d to { a: [ 2 d ] b: blabla c: True } | def asdict(self, name, _type=None, _set=False):
"""
Turn this 'a:2,b:blabla,c:True,a:'d' to
{a:[2, 'd'], b:'blabla', c:True}
"""
if _type is None:
_type = lambda t: t
dict_str = self.pop(name, None)
if not dict_str:
return {}
_d... |
Return random hex string of a given length | def get_random_hex(length):
"""
Return random hex string of a given length
"""
if length <= 0:
return ''
return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length] |
Return xx1x response for xx0x codes ( e. g. 0810 for 0800 ) | def get_response(_code):
"""
Return xx1x response for xx0x codes (e.g. 0810 for 0800)
"""
if _code:
code = str(_code)
return code[:-2] + str(int(code[-2:-1]) + 1) + code[-1]
else:
return None |
Load a TestSuite containing all TestCase instances for all tests in a TestCase subclass. | def load_case(self, testcase):
"""Load a TestSuite containing all TestCase instances for all tests in
a TestCase subclass.
Parameters
----------
testcase : type
A subclass of :class:`unittest.TestCase`
"""
tests = [self.load_test(testcase, name)
... |
Create and return a test suite containing all cases loaded from the provided module. | def load_module(self, module):
"""Create and return a test suite containing all cases loaded from the
provided module.
Parameters
----------
module : module
A module object containing ``TestCases``
"""
cases = self.get_test_cases_from_module(module)
... |
Add field to bitmap | def Field(self, field, Value = None):
'''
Add field to bitmap
'''
if Value == None:
try:
return self.__Bitmap[field]
except KeyError:
return None
elif Value == 1 or Value == 0:
self.__Bitmap[field] = Value
... |
Add field data | def FieldData(self, field, Value = None):
'''
Add field data
'''
if Value == None:
try:
return self.__FieldData[field]
except KeyError:
return None
else:
if len(str(Value)) > self.__IsoSpec.MaxLength(field):
... |
Helper function that can be used in db_key to support self as a collection key. | def authenticated_userid(request):
"""Helper function that can be used in ``db_key`` to support `self`
as a collection key.
"""
user = getattr(request, 'user', None)
key = user.pk_field()
return getattr(user, key) |
A generator for blocks contained in a block list. | def iter_blocks(block_list):
"""A generator for blocks contained in a block list.
Yields tuples containing the block name, the depth that the block was
found at, and finally a handle to the block itself.
"""
# queue the block and the depth of the block
queue = [(block, ... |
A generator for all scripts contained in a scratch file. | def iter_scripts(scratch):
"""A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
"""
for script in scratch.stage.scripts:
if not isinstance(script, kurt.Comment):
yield script
for sprite ... |
A generator for all scripts contained in a scratch file. | def iter_sprite_scripts(scratch):
"""A generator for all scripts contained in a scratch file.
yields stage scripts first, then scripts for each sprite
"""
for script in scratch.stage.scripts:
if not isinstance(script, kurt.Comment):
yield ('Stage', script)
... |
Return the type of block the script begins with. | def script_start_type(script):
"""Return the type of block the script begins with."""
if script[0].type.text == 'when @greenFlag clicked':
return HairballPlugin.HAT_GREEN_FLAG
elif script[0].type.text == 'when I receive %s':
return HairballPlugin.HAT_WHEN_I_RECEIVE
... |
Return a Counter of event - names that were broadcast. | def get_broadcast_events(cls, script):
"""Return a Counter of event-names that were broadcast.
The Count will contain the key True if any of the broadcast blocks
contain a parameter that is a variable.
"""
events = Counter()
for name, _, block in cls.iter_blocks(script)... |
Tag each script with attribute reachable. | def tag_reachable_scripts(cls, scratch):
"""Tag each script with attribute reachable.
The reachable attribute will be set false for any script that does not
begin with a hat block. Additionally, any script that begins with a
'when I receive' block whose event-name doesn't appear in a
... |
Attribute that returns the plugin description from its docstring. | def description(self):
"""Attribute that returns the plugin description from its docstring."""
lines = []
for line in self.__doc__.split('\n')[2:]:
line = line.strip()
if line:
lines.append(line)
return ' '.join(lines) |
Internal hook that marks reachable scripts before calling analyze. | def _process(self, scratch, filename, **kwargs):
"""Internal hook that marks reachable scripts before calling analyze.
Returns data exactly as returned by the analyze method.
"""
self.tag_reachable_scripts(scratch)
return self.analyze(scratch, filename=filename, **kwargs) |
Finalises the compressed version of the spreadsheet. If you aren t using the context manager ( with statement you must call this manually it is not triggered automatically like on a file object.: return: Nothing. | def close(self):
"""
Finalises the compressed version of the spreadsheet. If you aren't using the context manager ('with' statement,
you must call this manually, it is not triggered automatically like on a file object.
:return: Nothing.
"""
self.zipf.writestr("content.xml... |
Write a row of cells into the default sheet of the spreadsheet.: param cells: A list of cells ( most basic Python types supported ).: return: Nothing. | def writerow(self, cells):
"""
Write a row of cells into the default sheet of the spreadsheet.
:param cells: A list of cells (most basic Python types supported).
:return: Nothing.
"""
if self.default_sheet is None:
self.default_sheet = self.new_sheet()
... |
Create a new sheet in the spreadsheet and return it so content can be added.: param name: Optional name for the sheet.: param cols: Specify the number of columns needed for compatibility in some cases: return: Sheet object | def new_sheet(self, name=None, cols=None):
"""
Create a new sheet in the spreadsheet and return it so content can be added.
:param name: Optional name for the sheet.
:param cols: Specify the number of columns, needed for compatibility in some cases
:return: Sheet object
"... |
Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string. | def _format_kwargs(func):
"""Decorator to handle formatting kwargs to the proper names expected by
the associated function. The formats dictionary string keys will be used as
expected function kwargs and the value list of strings will be renamed to
the associated key string."""
formats = {}
form... |
Shows a menu but limits the number of entries shown at a time. Functionally equivalent to show_menu () with the limit parameter set. | def show_limit(entries, **kwargs):
"""Shows a menu but limits the number of entries shown at a time.
Functionally equivalent to `show_menu()` with the `limit` parameter set."""
limit = kwargs.pop('limit', 5)
if limit <= 0:
return show_menu(entries, **kwargs)
istart = 0 # Index of group start... |
Shows a menu with the given list of MenuEntry items. | def show_menu(entries, **kwargs):
"""Shows a menu with the given list of `MenuEntry` items.
**Params**:
- header (str) - String to show above menu.
- note (str) - String to show as a note below menu.
- msg (str) - String to show below menu.
- dft (str) - Default value if input is left b... |
Runs the function associated with the given MenuEntry. | def run_func(entry):
"""Runs the function associated with the given MenuEntry."""
if entry.func:
if entry.args and entry.krgs:
return entry.func(*entry.args, **entry.krgs)
if entry.args:
return entry.func(*entry.args)
if entry.krgs:
return entry.func(*... |
Enumerates the given list of strings into returned menu. | def enum_menu(strs, menu=None, *args, **kwargs):
"""Enumerates the given list of strings into returned menu.
**Params**:
- menu (Menu) - Existing menu to append. If not provided, a new menu will
be created.
"""
if not menu:
menu = Menu(*args, **kwargs)
for s in strs:
m... |
Prompts the user for input and returns the given answer. Optionally checks if answer is valid. | def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True):
"""Prompts the user for input and returns the given answer. Optionally
checks if answer is valid.
**Params**:
- msg (str) - Message to prompt the user with.
- fmt (func) - Function used to format... |
Prompts the user for a yes or no answer. Returns True for yes False for no. | def ask_yesno(msg="Proceed?", dft=None):
"""Prompts the user for a yes or no answer. Returns True for yes, False
for no."""
yes = ["y", "yes", "Y", "YES"]
no = ["n", "no", "N", "NO"]
if dft != None:
dft = yes[0] if (dft in yes or dft == True) else no[0]
return ask(msg, dft=dft, vld=yes+n... |
Prompts the user for an integer. | def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None):
"""Prompts the user for an integer."""
vld = vld or [int]
return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp) |
Prompts the user for a float. | def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None):
"""Prompts the user for a float."""
vld = vld or [float]
return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp) |
Prompts the user for a string. | def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None):
"""Prompts the user for a string."""
vld = vld or [str]
return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) |
Prompts the user for a random string. | def ask_captcha(length=4):
"""Prompts the user for a random string."""
captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length))
ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) |
Clears the console. | def clear():
"""Clears the console."""
if sys.platform.startswith("win"):
call("cls", shell=True)
else:
call("clear", shell=True) |
Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. | def status(*args, **kwargs):
"""Prints a status message at the start and finish of an associated
function. Can be used as a function decorator or as a function that accepts
another function as the first parameter.
**Params**:
The following parameters are available when used as a decorator:
... |
Prints a message then exits the program. Optionally pause before exit with pause = True kwarg. | def fatal(msg, exitcode=1, **kwargs):
"""Prints a message then exits the program. Optionally pause before exit
with `pause=True` kwarg."""
# NOTE: Can't use normal arg named `pause` since function has same name.
pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False
echo("[FA... |
Outputs or returns a horizontal line of the given character and width. Returns printed string. | def hrule(width=None, char=None):
"""Outputs or returns a horizontal line of the given character and width.
Returns printed string."""
width = width or HRWIDTH
char = char or HRCHAR
return echo(getline(char, width)) |
Sets the title of the console window. | def title(msg):
"""Sets the title of the console window."""
if sys.platform.startswith("win"):
ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg)) |
Wraps the given item content between horizontal lines. Item can be a string or a function. | def wrap(item, args=None, krgs=None, **kwargs):
"""Wraps the given item content between horizontal lines. Item can be a
string or a function.
**Examples**:
::
qprompt.wrap("Hi, this will be wrapped.") # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item.
"... |
Attempts to guess the menu entry name from the function name. | def _guess_name(desc, taken=None):
"""Attempts to guess the menu entry name from the function name."""
taken = taken or []
name = ""
# Try to find the shortest name based on the given description.
for word in desc.split():
c = word[0].lower()
if not c.isalnum():
continue
... |
Add a menu entry. | def add(self, name, desc, func=None, args=None, krgs=None):
"""Add a menu entry."""
self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) |
Add a menu entry whose name will be an auto indexed number. | def enum(self, desc, func=None, args=None, krgs=None):
"""Add a menu entry whose name will be an auto indexed number."""
name = str(len(self.entries)+1)
self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) |
Shows the menu. Any kwargs supplied will be passed to show_menu (). | def show(self, **kwargs):
"""Shows the menu. Any `kwargs` supplied will be passed to
`show_menu()`."""
show_kwargs = copy.deepcopy(self._show_kwargs)
show_kwargs.update(kwargs)
return show_menu(self.entries, **show_kwargs) |
Runs the function associated with the given entry name. | def run(self, name):
"""Runs the function associated with the given entry `name`."""
for entry in self.entries:
if entry.name == name:
run_func(entry)
break |
Runs the standard menu main logic. Any kwargs supplied will be pass to Menu. show (). If argv is provided to the script it will be used as the auto parameter. | def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs):
"""Runs the standard menu main logic. Any `kwargs` supplied will be
pass to `Menu.show()`. If `argv` is provided to the script, it will be
used as the `auto` parameter.
**Params**:
- auto ([str]) - If provide... |
Return two lists of scripts out of the original scripts list. | def partition_scripts(scripts, start_type1, start_type2):
"""Return two lists of scripts out of the original `scripts` list.
Scripts that begin with a `start_type1` or `start_type2` blocks
are returned first. All other scripts are returned second.
"""
match, other = [], []
for script in scrip... |
Return mapping of attributes to if they were initialized or not. | def attribute_result(cls, sprites):
"""Return mapping of attributes to if they were initialized or not."""
retval = dict((x, True) for x in cls.ATTRIBUTES)
for properties in sprites.values():
for attribute, state in properties.items():
retval[attribute] &= state != cl... |
Return the state of the scripts for the given attribute. | def attribute_state(cls, scripts, attribute):
"""Return the state of the scripts for the given attribute.
If there is more than one 'when green flag clicked' script and they
both modify the attribute, then the attribute is considered to not be
initialized.
"""
green_fla... |
Output whether or not each attribute was correctly initialized. | def output_results(cls, sprites):
"""Output whether or not each attribute was correctly initialized.
Attributes that were not modified at all are considered to be properly
initialized.
"""
print(' '.join(cls.ATTRIBUTES))
format_strs = ['{{{}!s:^{}}}'.format(x, len(x)) f... |
Return a mapping of attributes to their initilization state. | def sprite_changes(cls, sprite):
"""Return a mapping of attributes to their initilization state."""
retval = dict((x, cls.attribute_state(sprite.scripts, x)) for x in
(x for x in cls.ATTRIBUTES if x != 'background'))
return retval |
Run and return the results of the AttributeInitialization plugin. | def analyze(self, scratch, **kwargs):
"""Run and return the results of the AttributeInitialization plugin."""
changes = dict((x.name, self.sprite_changes(x)) for x in
scratch.sprites)
changes['stage'] = {
'background': self.attribute_state(scratch.stage.scripts... |
Return the initialization state for each variable in variables. | def variable_state(cls, scripts, variables):
"""Return the initialization state for each variable in variables.
The state is determined based on the scripts passed in via the scripts
parameter.
If there is more than one 'when green flag clicked' script and they
both modify the ... |
Run and return the results of the VariableInitialization plugin. | def analyze(self, scratch, **kwargs):
"""Run and return the results of the VariableInitialization plugin."""
variables = dict((x, self.variable_state(x.scripts, x.variables))
for x in scratch.sprites)
variables['global'] = self.variable_state(self.iter_scripts(scratch),
... |
Output the default sprite names found in the project. | def finalize(self):
"""Output the default sprite names found in the project."""
print('{} default sprite names found:'.format(self.total_default))
for name in self.list_default:
print(name) |
Run and return the results from the SpriteNaming plugin. | def analyze(self, scratch, **kwargs):
"""Run and return the results from the SpriteNaming plugin."""
for sprite in self.iter_sprites(scratch):
for default in self.default_names:
if default in sprite.name:
self.total_default += 1
self.li... |
Allows all methods to be tunneled via GET for dev/ debuging purposes. | def get_tunneling(handler, registry):
""" Allows all methods to be tunneled via GET for dev/debuging
purposes.
"""
log.info('get_tunneling enabled')
def get_tunneling(request):
if request.method == 'GET':
method = request.GET.pop('_m', 'GET')
request.method = method
... |
This allows replacing id_name with self. e. g./ users/ joe/ account ==/ users/ self/ account if joe is in the session as an authorized user | def enable_selfalias(config, id_name):
"""
This allows replacing id_name with "self".
e.g. /users/joe/account == /users/self/account if joe is in the session
as an authorized user
"""
def context_found_subscriber(event):
request = event.request
user = getattr(request, 'user', No... |
Convert dotted keys in: params: dictset to a nested dictset. | def convert_dotted(params):
""" Convert dotted keys in :params: dictset to a nested dictset.
E.g. {'settings.foo': 'bar'} -> {'settings': {'foo': 'bar'}}
"""
if not isinstance(params, dictset):
params = dictset(params)
dotted_items = {k: v for k, v in params.items()... |
Prepare query and update params. | def prepare_request_params(self, _query_params, _json_params):
""" Prepare query and update params. """
self._query_params = dictset(
_query_params or self.request.params.mixed())
self._json_params = dictset(_json_params)
ctype = self.request.content_type
if self.req... |
Set self. request. override_renderer if needed. | def set_override_rendered(self):
""" Set self.request.override_renderer if needed. """
if '' in self.request.accept:
self.request.override_renderer = self._default_renderer
elif 'application/json' in self.request.accept:
self.request.override_renderer = 'nefertari_json'
... |
Wrap self. index method with ESAggregator. | def _setup_aggregation(self, aggregator=None):
""" Wrap `self.index` method with ESAggregator.
This makes `self.index` to first try to run aggregation and only
on fail original method is run. Method is wrapped only if it is
defined and `elasticsearch.enable_aggregations` setting is true... |
Query ES collection and return results. | def get_collection_es(self):
""" Query ES collection and return results.
This is default implementation of querying ES collection with
`self._query_params`. It must return found ES collection
results for default response renderers to work properly.
"""
from nefertari.ela... |
Fill missing model fields in JSON with { key: null value }. | def fill_null_values(self):
""" Fill missing model fields in JSON with {key: null value}.
Only run for PUT requests.
"""
if not self.Model:
log.info("%s has no model defined" % self.__class__.__name__)
return
empty_values = self.Model.get_null_values()
... |
Set public limits if auth is enabled and user is not authenticated. | def set_public_limits(self):
""" Set public limits if auth is enabled and user is not
authenticated.
Also sets default limit for GET, HEAD requests.
"""
if self.request.method.upper() in ['GET', 'HEAD']:
self._query_params.process_int_param('_limit', 20)
if s... |
Convert object IDs from self. _json_params to objects if needed. | def convert_ids2objects(self):
""" Convert object IDs from `self._json_params` to objects if needed.
Only IDs that belong to relationship field of `self.Model`
are converted.
"""
if not self.Model:
log.info("%s has no model defined" % self.__class__.__name__)
... |
Setup defaulf wrappers. | def setup_default_wrappers(self):
""" Setup defaulf wrappers.
Wrappers are applied when view method does not return instance
of Response. In this case nefertari renderers call wrappers and
handle response generation.
"""
# Index
self._after_calls['index'] = [
... |
Migrate data from mongodict < = 0. 2. 1 to 0. 3. 0 config_old and config_new should be dictionaries with the keys regarding to MongoDB server: - host - port - database - collection | def migrate_codec(config_old, config_new):
'''Migrate data from mongodict <= 0.2.1 to 0.3.0
`config_old` and `config_new` should be dictionaries with the keys
regarding to MongoDB server:
- `host`
- `port`
- `database`
- `collection`
'''
assert mongodict.__version__ i... |
Generate map of fieldName: clsInstance from dict. | def from_dict(cls, data, model):
""" Generate map of `fieldName: clsInstance` from dict.
:param data: Dict where keys are field names and values are
new values of field.
:param model: Model class to which fields from :data: belong.
"""
model_provided = model is not N... |
Register new user by POSTing all required data. | def register(self):
""" Register new user by POSTing all required data. """
user, created = self.Model.create_account(
self._json_params)
if not created:
raise JHTTPConflict('Looks like you already have an account.')
self.request._user = user
pk_field = ... |
Register a new user by POSTing all required data. | def register(self):
""" Register a new user by POSTing all required data.
User's `Authorization` header value is returned in `WWW-Authenticate`
header.
"""
user, created = self.Model.create_account(self._json_params)
if user.api_key is None:
raise JHTTPBadReq... |
Claim current token by POSTing login and password. | def claim_token(self, **params):
"""Claim current token by POSTing 'login' and 'password'.
User's `Authorization` header value is returned in `WWW-Authenticate`
header.
"""
self._json_params.update(params)
success, self.user = self.Model.authenticate_by_password(
... |
Reset current token by POSTing login and password. | def reset_token(self, **params):
""" Reset current token by POSTing 'login' and 'password'.
User's `Authorization` header value is returned in `WWW-Authenticate`
header.
"""
response = self.claim_token(**params)
if not self.user:
return response
self... |
Apply privacy to nested documents. | def _apply_nested_privacy(self, data):
""" Apply privacy to nested documents.
:param data: Dict of data to which privacy is already applied.
"""
kw = {
'is_admin': self.is_admin,
'drop_hidden': self.drop_hidden,
}
for key, val in data.items():
... |
Add _self key value to: obj: dict. | def _set_object_self(self, obj):
""" Add '_self' key value to :obj: dict. """
from nefertari.elasticsearch import ES
location = self.request.path_url
route_kwargs = {}
""" Check for parents """
if self.request.matchdict:
route_kwargs.update(self.request.match... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.