desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return the next interval for CARD, in seconds.'
def nextIvl(self, card, ease):
if (card.queue in (0, 1, 3)): return self._nextLrnIvl(card, ease) elif (ease == 1): conf = self._lapseConf(card) if conf['delays']: return (conf['delays'][0] * 60) return (self._nextLapseIvl(card, conf) * 86400) else: return (self._nextRevIvl(card, ease) *...
'Suspend cards.'
def suspendCards(self, ids):
self.col.log(ids) self.remFromDyn(ids) self.removeLrn(ids) self.col.db.execute(('update cards set queue=-1,mod=?,usn=? where id in ' + ids2str(ids)), intTime(), self.col.usn())
'Unsuspend cards.'
def unsuspendCards(self, ids):
self.col.log(ids) self.col.db.execute(('update cards set queue=type,mod=?,usn=? where queue = -1 and id in ' + ids2str(ids)), intTime(), self.col.usn())
'Bury all cards for note until next session.'
def buryNote(self, nid):
cids = self.col.db.list('select id from cards where nid = ? and queue >= 0', nid) self.buryCards(cids)
'Put cards at the end of the new queue.'
def forgetCards(self, ids):
self.remFromDyn(ids) self.col.db.execute(('update cards set type=0,queue=0,ivl=0,due=0,odue=0,factor=? where id in ' + ids2str(ids)), STARTING_FACTOR) pmax = (self.col.db.scalar('select max(due) from cards where type=0') or 0) self.sortCards(ids, start=(pmax + 1)) ...
'Put cards in review queue with a new interval in days (min, max).'
def reschedCards(self, ids, imin, imax):
d = [] t = self.today mod = intTime() for id in ids: r = random.randint(imin, imax) d.append(dict(id=id, due=(r + t), ivl=max(1, r), mod=mod, usn=self.col.usn(), fact=STARTING_FACTOR)) self.remFromDyn(ids) self.col.db.executemany('\nupdate cards set type=2,queue=2,ivl=:i...
'Completely reset cards for export.'
def resetCards(self, ids):
sids = ids2str(ids) nonNew = self.col.db.list(('select id from cards where id in %s and (queue != 0 or type != 0)' % sids)) self.col.db.execute(('update cards set reps=0,lapses=0,odid=0,odue=0,queue=0 where id in %s' % sids)) self.forgetC...
'Grab passed options from Ansible complex and module args. :param complex_args: ``dict`` :param module_args: ``dict`` :returns: ``dict``'
@staticmethod def grab_options(complex_args, module_args):
options = dict() if complex_args: options.update(complex_args) options.update(utils.parse_kv(module_args)) return options
'Returns string value from a modified config file. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_ini(self, config_overrides, resultant, list_extend=True):
config = ConfigTemplateParser(dict_type=MultiKeyDict, allow_no_value=True) config.optionxform = str config_object = io.BytesIO(resultant.encode('utf-8')) config.readfp(config_object) for (section, items) in config_overrides.items(): if (not isinstance(items, dict)): if isinstance...
'Returns config json Its important to note that file ordering will not be preserved as the information within the json file will be sorted by keys. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_json(self, config_overrides, resultant, list_extend=True):
original_resultant = json.loads(resultant) merged_resultant = self._merge_dict(base_items=original_resultant, new_items=config_overrides, list_extend=list_extend) return json.dumps(merged_resultant, indent=4, sort_keys=True)
'Return config yaml. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_yaml(self, config_overrides, resultant, list_extend=True):
original_resultant = yaml.safe_load(resultant) merged_resultant = self._merge_dict(base_items=original_resultant, new_items=config_overrides, list_extend=list_extend) return yaml.safe_dump(merged_resultant, default_flow_style=False, width=1000)
'Recursively merge new_items into base_items. :param base_items: ``dict`` :param new_items: ``dict`` :returns: ``dict``'
def _merge_dict(self, base_items, new_items, list_extend=True):
for (key, value) in new_items.iteritems(): if isinstance(value, dict): base_items[key] = self._merge_dict(base_items.get(key, {}), value) elif ((',' in value) or ('\n' in value)): base_items[key] = re.split(', |,|\n', value) base_items[key] = [i.strip() for i i...
'Run the method'
def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
if (not self.runner.is_playbook): raise errors.AnsibleError('FAILED: `config_templates` are only available in playbooks') options = self.grab_options(complex_args, module_args) try: source = options['src'] dest = options['dest'] config_overrides = options.ge...
'Returns string value from a modified config file. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_ini(self, config_overrides, resultant, list_extend=True):
try: config = ConfigTemplateParser(allow_no_value=True, dict_type=MultiKeyDict) config.optionxform = str except Exception: config = ConfigTemplateParser(dict_type=MultiKeyDict) config_object = io.BytesIO(str(resultant)) config.readfp(config_object) for (section, items) in con...
'Returns config json Its important to note that file ordering will not be preserved as the information within the json file will be sorted by keys. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_json(self, config_overrides, resultant, list_extend=True):
original_resultant = json.loads(resultant) merged_resultant = self._merge_dict(base_items=original_resultant, new_items=config_overrides, list_extend=list_extend) return json.dumps(merged_resultant, indent=4, sort_keys=True)
'Return config yaml. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_yaml(self, config_overrides, resultant, list_extend=True):
original_resultant = yaml.safe_load(resultant) merged_resultant = self._merge_dict(base_items=original_resultant, new_items=config_overrides, list_extend=list_extend) return yaml.safe_dump(merged_resultant, default_flow_style=False, width=1000)
'Recursively merge new_items into base_items. :param base_items: ``dict`` :param new_items: ``dict`` :returns: ``dict``'
def _merge_dict(self, base_items, new_items, list_extend=True):
for (key, value) in new_items.iteritems(): if isinstance(value, dict): base_items[key] = self._merge_dict(base_items=base_items.get(key, {}), new_items=value, list_extend=list_extend) elif ((not isinstance(value, int)) and ((',' in value) or ('\n' in value))): base_items[key]...
'Return options and status from module load.'
def _load_options_and_status(self, task_vars):
config_type = self._task.args.get('config_type') if (config_type not in ['ini', 'yaml', 'json']): return (False, dict(failed=True, msg='No valid [ config_type ] was provided. Valid options are ini, yaml, or json.')) searchpath = [self._loader._basedir] if s...
'Run the method'
def run(self, tmp=None, task_vars=None):
try: remote_user = task_vars.get('ansible_user') if (not remote_user): remote_user = task_vars.get('ansible_ssh_user') if (not remote_user): remote_user = self._play_context.remote_user if (not tmp): tmp = self._make_tmp_path(remote_user) excep...
'Grab passed options from Ansible complex and module args. :param complex_args: ``dict`` :param module_args: ``dict`` :returns: ``dict``'
@staticmethod def grab_options(complex_args, module_args):
options = dict() if complex_args: options.update(complex_args) options.update(utils.parse_kv(module_args)) return options
'Returns string value from a modified config file. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_ini(self, config_overrides, resultant, list_extend=True):
config = ConfigTemplateParser(dict_type=MultiKeyDict, allow_no_value=True) config.optionxform = str config_object = io.BytesIO(resultant.encode('utf-8')) config.readfp(config_object) for (section, items) in config_overrides.items(): if (not isinstance(items, dict)): if isinstance...
'Returns config json Its important to note that file ordering will not be preserved as the information within the json file will be sorted by keys. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_json(self, config_overrides, resultant, list_extend=True):
original_resultant = json.loads(resultant) merged_resultant = self._merge_dict(base_items=original_resultant, new_items=config_overrides, list_extend=list_extend) return json.dumps(merged_resultant, indent=4, sort_keys=True)
'Return config yaml. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_yaml(self, config_overrides, resultant, list_extend=True):
original_resultant = yaml.safe_load(resultant) merged_resultant = self._merge_dict(base_items=original_resultant, new_items=config_overrides, list_extend=list_extend) return yaml.safe_dump(merged_resultant, default_flow_style=False, width=1000)
'Recursively merge new_items into base_items. :param base_items: ``dict`` :param new_items: ``dict`` :returns: ``dict``'
def _merge_dict(self, base_items, new_items, list_extend=True):
for (key, value) in new_items.iteritems(): if isinstance(value, dict): base_items[key] = self._merge_dict(base_items.get(key, {}), value) elif ((',' in value) or ('\n' in value)): base_items[key] = re.split(', |,|\n', value) base_items[key] = [i.strip() for i i...
'Run the method'
def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
if (not self.runner.is_playbook): raise errors.AnsibleError('FAILED: `config_templates` are only available in playbooks') options = self.grab_options(complex_args, module_args) try: source = options['src'] dest = options['dest'] config_overrides = options.ge...
'Returns string value from a modified config file. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_ini(self, config_overrides, resultant, list_extend=True):
try: config = ConfigTemplateParser(allow_no_value=True, dict_type=MultiKeyDict) config.optionxform = str except Exception: config = ConfigTemplateParser(dict_type=MultiKeyDict) config_object = io.BytesIO(str(resultant)) config.readfp(config_object) for (section, items) in con...
'Returns config json Its important to note that file ordering will not be preserved as the information within the json file will be sorted by keys. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_json(self, config_overrides, resultant, list_extend=True):
original_resultant = json.loads(resultant) merged_resultant = self._merge_dict(base_items=original_resultant, new_items=config_overrides, list_extend=list_extend) return json.dumps(merged_resultant, indent=4, sort_keys=True)
'Return config yaml. :param config_overrides: ``dict`` :param resultant: ``str`` || ``unicode`` :returns: ``str``'
def return_config_overrides_yaml(self, config_overrides, resultant, list_extend=True):
original_resultant = yaml.safe_load(resultant) merged_resultant = self._merge_dict(base_items=original_resultant, new_items=config_overrides, list_extend=list_extend) return yaml.safe_dump(merged_resultant, default_flow_style=False, width=1000)
'Recursively merge new_items into base_items. :param base_items: ``dict`` :param new_items: ``dict`` :returns: ``dict``'
def _merge_dict(self, base_items, new_items, list_extend=True):
for (key, value) in new_items.iteritems(): if isinstance(value, dict): base_items[key] = self._merge_dict(base_items=base_items.get(key, {}), new_items=value, list_extend=list_extend) elif ((not isinstance(value, int)) and ((',' in value) or ('\n' in value))): base_items[key]...
'Return options and status from module load.'
def _load_options_and_status(self, task_vars):
config_type = self._task.args.get('config_type') if (config_type not in ['ini', 'yaml', 'json']): return (False, dict(failed=True, msg='No valid [ config_type ] was provided. Valid options are ini, yaml, or json.')) searchpath = [self._loader._basedir] if s...
'Run the method'
def run(self, tmp=None, task_vars=None):
try: remote_user = task_vars.get('ansible_user') if (not remote_user): remote_user = task_vars.get('ansible_ssh_user') if (not remote_user): remote_user = self._play_context.remote_user if (not tmp): tmp = self._make_tmp_path(remote_user) excep...
'For the purpose of this example the implementation is as simple as possible. A \'real\' token should probably contain a hash of the username/password combo, which should be then validated against the account data stored on the DB.'
def check_auth(self, token, allowed_roles, resource, method):
accounts = app.data.driver.db['accounts'] return accounts.find_one({'token': token})
'Implements the Flask extension pattern. .. versionchanged:: 0.2 Explicit initialize self.driver to None.'
def __init__(self, app):
self.driver = None if (app is not None): self.app = app self.init_app(self.app) else: self.app = None
'This is where you want to initialize the db driver so it will be alive through the whole instance lifespan.'
def init_app(self, app):
raise NotImplementedError
'Retrieves a set of documents (rows), matching the current request. Consumed when a request hits a collection/document endpoint (`/people/`). :param resource: resource being accessed. You should then use the ``datasource`` helper function to retrieve both the db collection/table and base query (filter), if any. :param ...
def find(self, resource, req, sub_resource_lookup):
raise NotImplementedError
'Perform an aggregation on the resource datasource and returns the result. Only implent this if the underlying db engine supports aggregation operations. :param resource: resource being accessed. You should then use the ``datasource`` helper function to retrieve the db collection/table consumed by the resource. :param ...
def aggregate(self, resource, pipeline, options):
raise NotImplementedError
'Retrieves a single document/record. Consumed when a request hits an item endpoint (`/people/id/`). :param resource: resource being accessed. You should then use the ``datasource`` helper function to retrieve both the db collection/table and base query (filter), if any. :param req: an instance of ``eve.utils.ParsedRequ...
def find_one(self, resource, req, **lookup):
raise NotImplementedError
'Retrieves a single, raw document. No projections or datasource filters are being applied here. Just looking up the document using the same lookup. :param resource: resource name. :param ** lookup: lookup query. .. versionadded:: 0.4'
def find_one_raw(self, resource, **lookup):
raise NotImplementedError
'Retrieves a list of documents based on a list of primary keys The primary key is the field defined in `ID_FIELD`. This is a separate function to allow us to use per-database optimizations for this type of query. :param resource: resource name. :param ids: a list of ids corresponding to the documents to retrieve :param...
def find_list_of_ids(self, resource, ids, client_projection=None):
raise NotImplementedError
'Inserts a document into a resource collection/table. :param resource: resource being accessed. You should then use the ``datasource`` helper function to retrieve both the actual datasource name. :param doc_or_docs: json document or list of json documents to be added to the database. .. versionchanged:: 0.0.6 \'documen...
def insert(self, resource, doc_or_docs):
raise NotImplementedError
'Updates a collection/table document/row. :param resource: resource being accessed. You should then use the ``datasource`` helper function to retrieve the actual datasource name. :param id_: the unique id of the document. :param updates: json updates to be performed on the database document (or row). :param original: d...
def update(self, resource, id_, updates, original):
raise NotImplementedError
'Replaces a collection/table document/row. :param resource: resource being accessed. You should then use the ``datasource`` helper function to retrieve the actual datasource name. :param id_: the unique id of the document. :param document: the new json document :param original: definition of the json document that shou...
def replace(self, resource, id_, document, original):
raise NotImplementedError
'Removes a document/row or an entire set of documents/rows from a database collection/table. :param resource: resource being accessed. You should then use the ``datasource`` helper function to retrieve the actual datasource name. :param lookup: a dict with the query that documents must match in order to qualify for del...
def remove(self, resource, lookup):
raise NotImplementedError
'Takes two db queries and applies db-specific syntax to produce the intersection. .. versionadded: 0.1.0 Support for intelligent combination of db queries'
def combine_queries(self, query_a, query_b):
raise NotImplementedError
'Parses the given potentially-complex query and returns the value being assigned to the field given in `field_name`. This mainly exists to deal with more complicated compound queries .. versionadded: 0.1.0 Support for parsing values embedded in compound db queries'
def get_value_from_query(self, query, field_name):
raise NotImplementedError
'For the specified field name, does the query contain it? Used know whether we need to parse a compound query. .. versionadded: 0.1.0 Support for parsing values embedded in compound db queries'
def query_contains_field(self, query, field_name):
raise NotImplementedError
'Returns True if the collection is empty; False otherwise. While a user could rely on self.find() method to achieve the same result, this method can probably take advantage of specific datastore features to provide better performance. Don\'t forget, a \'resource\' could have a pre-defined filter. If that is the case, i...
def is_empty(self, resource):
raise NotImplementedError
'Returns a tuple with the actual name of the database collection/table, base query and projection for the resource being accessed. :param resource: resource being accessed. .. versionchanged:: 0.6 Name change: from _datasource to datasource. .. versionchanged:: 0.5 If allow_unknown is enabled for the resource, don\'t r...
def datasource(self, resource):
dsource = config.SOURCES[resource] source = copy(dsource['source']) filter_ = copy(dsource['filter']) sort = copy(dsource['default_sort']) projection = copy(dsource['projection']) return (source, filter_, projection, sort)
'Returns both db collection and exact query (base filter included) to which an API resource refers to. .. versionchanged:: 0.5.2 Make User Restricted Resource Access work with HMAC Auth too. .. versionchanged:: 0.5 Let client projection work when \'allow_unknown\' is active (#497). .. versionchanged:: 0.4 Always return...
def _datasource_ex(self, resource, query=None, client_projection=None, client_sort=None):
(datasource, filter_, projection_, sort_) = self.datasource(resource) if client_sort: sort = client_sort else: sort = (sort_ if (sort_ and config.DOMAIN[resource]['sorting']) else None) if filter_: if query: query = self.combine_queries(query, filter_) else: ...
'Returns a properly parsed client projection if available. :param req: a :class:`ParsedRequest` instance. .. versionchanged:: 0.6.1 Moved from the mongo layer up to the DataLayer base class (#724). .. versionadded:: 0.4'
def _client_projection(self, req):
client_projection = {} if (req and req.projection): try: client_projection = json.loads(req.projection) if (not isinstance(client_projection, dict)): raise Exception('The projection parameter has to be a dict') except: abor...
':param app: the flask application (eve itself). This can be used by the class to access, amongst other things, the app.config object to retrieve class-specific settings.'
def __init__(self, app=None):
self.app = app
'Opens the file given by name or unique id. Note that although the returned file is guaranteed to be a File object, it might actually be some subclass. Returns None if no file was found.'
def get(self, id_or_filename, resource=None):
raise NotImplementedError
'Saves a new file using the storage system, preferably with the name specified. If there already exists a file with this name name, the storage system may modify the filename as necessary to get a unique name. Depending on the storage system, a unique id or the actual name of the stored file will be returned. The conte...
def put(self, content, filename=None, content_type=None, resource=None):
raise NotImplementedError
'Deletes the file referenced by name or unique id. If deletion is not supported on the target storage system this will raise NotImplementedError instead'
def delete(self, id_or_filename, resource=None):
raise NotImplementedError
'Returns True if a file referenced by the given name or unique id already exists in the storage system, or False if the name is available for a new file.'
def exists(self, id_or_filename, resource=None):
raise NotImplementedError
':param app: the flask application (eve itself). This can be used by the class to access, amongst other things, the app.config object to retrieve class-specific settings. .. versionchanged:: 0.6 Support for multiple, cached, GridFS instances'
def __init__(self, app=None):
super(GridFSMediaStorage, self).__init__(app) self.validate() self._fs = {}
'Make sure that the application data layer is a eve.io.mongo.Mongo instance.'
def validate(self):
if (self.app is None): raise TypeError('Application object cannot be None') if (not isinstance(self.app, Flask)): raise TypeError('Application object must be a Eve application')
'Provides the instance-level GridFS instance, instantiating it if needed. .. versionchanged:: 0.6 Support for multiple, cached, GridFS instances'
def fs(self, resource=None):
driver = self.app.data if ((driver is None) or (not isinstance(driver, Mongo))): raise TypeError('Application data object must be of eve.io.Mongo type.') px = driver.current_mongo_prefix(resource) if (px not in self._fs): self._fs[px] = GridFS(driver.pymongo(prefix=p...
'Returns the file given by unique id. Returns None if no file was found. .. versionchanged: 0.6 Support for _id as string.'
def get(self, _id, resource=None):
if isinstance(_id, str_type): try: _id = ObjectId(unicode(_id)) except NameError: _id = ObjectId(_id) _file = None try: _file = self.fs(resource).get(_id) except: pass return _file
'Saves a new file in GridFS. Returns the unique id of the stored file. Also stores content type of the file.'
def put(self, content, filename=None, content_type=None, resource=None):
return self.fs(resource).put(content, filename=filename, content_type=content_type)
'Deletes the file referenced by unique id.'
def delete(self, _id, resource=None):
self.fs(resource).delete(_id)
'Returns True if a file referenced by the unique id or the query document already exists, False otherwise. Valid query: {\'filename\': \'file.txt\'}'
def exists(self, id_or_document, resource=None):
return self.fs(resource).exists(id_or_document)
'{\'type\': \'boolean\'}'
def _validate_versioned(self, unique, field, value):
pass
'{\'type\': \'boolean\'}'
def _validate_unique_to_user(self, unique, field, value):
(auth_field, auth_value) = auth_field_and_value(self.resource) query = ({auth_field: auth_value} if auth_field else {}) self._is_value_unique(unique, field, value, query)
'{\'type\': \'boolean\'}'
def _validate_unique(self, unique, field, value):
self._is_value_unique(unique, field, value, {})
'Validates that a field value is unique. .. versionchanged:: 0.6.2 Exclude soft deleted documents from uniqueness check. Closes #831. .. versionadded:: 0.6'
def _is_value_unique(self, unique, field, value, query):
if unique: query[field] = value resource_config = config.DOMAIN[self.resource] if resource_config['soft_delete']: query[config.DELETED] = {'$ne': True} if self.document_id: id_field = resource_config['id_field'] query[id_field] = {'$ne': self.docum...
'{\'type\': \'dict\', \'schema\': { \'resource\': {\'type\': \'string\', \'required\': True}, \'field\': {\'type\': \'string\', \'required\': True}, \'embeddable\': {\'type\': \'boolean\', \'default\': False}, \'version\': {\'type\': \'boolean\', \'default\': False}'
def _validate_data_relation(self, data_relation, field, value):
if (('version' in data_relation) and (data_relation['version'] is True)): value_field = data_relation['field'] version_field = app.config['VERSION'] if (isinstance(value, dict) and (value_field in value) and (version_field in value)): resource_def = config.DOMAIN[data_relation['r...
'Enables validation for `feature`data type :param value: field value'
def _validate_type_feature(self, value):
try: Feature(value) return True except TypeError: pass
'Enables validation for `featurecollection`data type :param value: field value'
def _validate_type_featurecollection(self, value):
try: FeatureCollection(value) return True except TypeError: pass
'Module handler, our entry point.'
def visit_Module(self, node):
self.mongo_query = {} self.ops = [] self.current_value = None self.generic_visit(node) if (self.mongo_query == {}): raise ParseError('Only conditional statements with boolean (and, or) and comparison operators are supported.')
'Make sure that we are parsing compare or boolean operators'
def visit_Expr(self, node):
if (not (isinstance(node.value, ast.Compare) or isinstance(node.value, ast.BoolOp))): raise ParseError('Will only parse conditional statements') self.generic_visit(node)
'Compare operator handler.'
def visit_Compare(self, node):
self.visit(node.left) left = self.current_value operator = (self.op_mapper[node.ops[0].__class__] if node.ops else None) if node.comparators: comparator = node.comparators[0] self.visit(comparator) if (operator != ''): value = {operator: self.current_value} else: ...
'Boolean operator handler.'
def visit_BoolOp(self, node):
op = self.op_mapper[node.op.__class__] self.ops.append([]) for value in node.values: self.visit(value) c = self.ops.pop() if self.ops: self.ops[(-1)].append({op: c}) else: self.mongo_query[op] = c
'A couple function calls are supported: bson\'s ObjectId() and datetime().'
def visit_Call(self, node):
if isinstance(node.func, ast.Name): expr = None if (node.func.id == 'ObjectId'): expr = (("('" + node.args[0].s) + "')") elif (node.func.id == 'datetime'): values = [] for arg in node.args: values.append(str(arg.n)) expr = (('('...
'Attribute handler (\'Contact.Id\').'
def visit_Attribute(self, node):
self.visit(node.value) self.current_value += ('.' + node.attr)
'Names handler.'
def visit_Name(self, node):
self.current_value = node.id
'Numbers handler.'
def visit_Num(self, node):
self.current_value = node.n
'Strings handler.'
def visit_Str(self, node):
self.current_value = node.s
'Initialize PyMongo. .. versionchanged:: 0.6 Use mongo_prefix for multidb support. .. versionchanged:: 0.0.9 Support for Python 3.3.'
def init_app(self, app):
self.driver = PyMongos(self) self.mongo_prefix = None
'Retrieves a set of documents matching a given request. Queries can be expressed in two different formats: the mongo query syntax, and the python syntax. The first kind of query would look like: :: ?where={"name": "john doe"} while the second would look like: :: ?where=name=="john doe" The resultset if paginated. :para...
def find(self, resource, req, sub_resource_lookup):
args = dict() if (req and req.max_results): args['limit'] = req.max_results if (req and (req.page > 1)): args['skip'] = ((req.page - 1) * req.max_results) client_sort = {} spec = {} if (req and req.sort): try: client_sort = ast.literal_eval(req.sort) e...
'Retrieves a single document. :param resource: resource name. :param req: a :class:`ParsedRequest` instance. :param **lookup: lookup query. .. versionchanged:: 0.6 Support for multiple databases. Filter soft deleted documents by default .. versionchanged:: 0.4 Honor client projection requests. .. versionchanged:: 0.3.0...
def find_one(self, resource, req, **lookup):
self._mongotize(lookup, resource) client_projection = self._client_projection(req) (datasource, filter_, projection, _) = self._datasource_ex(resource, lookup, client_projection) if (config.DOMAIN[resource]['soft_delete'] and ((not req) or (not req.show_deleted)) and (not self.query_contains_field(looku...
'Retrieves a single raw document. :param resource: resource name. :param **lookup: lookup query. .. versionchanged:: 0.6 Support for multiple databases. .. versionadded:: 0.4'
def find_one_raw(self, resource, **lookup):
id_field = config.DOMAIN[resource]['id_field'] _id = lookup.get(id_field) (datasource, filter_, _, _) = self._datasource_ex(resource, {id_field: _id}, None) lookup = self._mongotize(lookup, resource) return self.pymongo(resource).db[datasource].find_one(lookup)
'Retrieves a list of documents from the collection given by `resource`, matching the given list of ids. This query is generated to *preserve the order* of the elements in the `ids` list. An alternative would be to use the `$in` operator and accept non-dependable ordering for a slight performance boost see <https://jira...
def find_list_of_ids(self, resource, ids, client_projection=None):
id_field = config.DOMAIN[resource]['id_field'] query = {'$or': [{id_field: id_} for id_ in ids]} (datasource, spec, projection, _) = self._datasource_ex(resource, query=query, client_projection=client_projection) documents = self.pymongo(resource).db[datasource].find(filter=spec, projection=projection) ...
'.. versionadded:: 0.7'
def aggregate(self, resource, pipeline, options):
(datasource, _, _, _) = self.datasource(resource) challenge = self._mongotize({'key': pipeline}, resource)['key'] return self.pymongo(resource).db[datasource].aggregate(challenge, **options)
'Inserts a document into a resource collection. .. versionchanged:: 0.6.1 Support for PyMongo 3.0. .. versionchanged:: 0.6 Support for multiple databases. .. versionchanged:: 0.0.9 More informative error messages. .. versionchanged:: 0.0.8 \'write_concern\' support. .. versionchanged:: 0.0.6 projection queries (\'?proj...
def insert(self, resource, doc_or_docs):
(datasource, _, _, _) = self._datasource_ex(resource) coll = self.get_collection_with_write_concern(datasource, resource) if isinstance(doc_or_docs, dict): doc_or_docs = [doc_or_docs] try: return coll.insert_many(doc_or_docs, ordered=True).inserted_ids except pymongo.errors.BulkWrite...
'Performs a change, be it a replace or update. .. versionchanged:: 0.6.1 Support for PyMongo 3.0. .. versionchanged:: 0.6 Return 400 if an attempt is made to update/replace an immutable field.'
def _change_request(self, resource, id_, changes, original, replace=False):
id_field = config.DOMAIN[resource]['id_field'] query = {id_field: id_} if (config.ETAG in original): query[config.ETAG] = original[config.ETAG] (datasource, filter_, _, _) = self._datasource_ex(resource, query) coll = self.get_collection_with_write_concern(datasource, resource) try: ...
'Updates a collection document. .. versionchanged:: 0.6 Support for multiple databases. .. versionchanged:: 5.2 Raise OriginalChangedError if document is changed from the specified original. .. versionchanged:: 0.4 Return a 400 on pymongo DuplicateKeyError. .. versionchanged:: 0.3.0 Custom ID_FIELD lookups would fail. ...
def update(self, resource, id_, updates, original):
return self._change_request(resource, id_, {'$set': updates}, original)
'Replaces an existing document. .. versionchanged:: 0.6 Support for multiple databases. .. versionchanged:: 5.2 Raise OriginalChangedError if document is changed from the specified original. .. versionchanged:: 0.3.0 Custom ID_FIELD lookups would fail. See #203. .. versionchanged:: 0.2 Don\'t explicitly convert ID_FIEL...
def replace(self, resource, id_, document, original):
return self._change_request(resource, id_, document, original, replace=True)
'Removes a document or the entire set of documents from a collection. .. versionchanged:: 0.6.1 Support for PyMongo 3.0. .. versionchanged:: 0.6 Support for multiple databases. .. versionchanged:: 0.3 Support lookup arg, which allows to properly delete sub-resources (only delete documents that meet a certain constraint...
def remove(self, resource, lookup):
lookup = self._mongotize(lookup, resource) (datasource, filter_, _, _) = self._datasource_ex(resource, lookup) coll = self.get_collection_with_write_concern(datasource, resource) try: coll.delete_many(filter_) except pymongo.errors.OperationFailure as e: self.app.logger.exception(e) ...
'Takes two db queries and applies db-specific syntax to produce the intersection. This is used because we can\'t just dump one set of query operators into another. Consider for example if the dataset contains a custom datasource pattern like -- \'filter\': {\'username\': {\'$exists\': True}} If we simultaneously try to...
def combine_queries(self, query_a, query_b):
return {'$and': [{k: v} for (k, v) in itertools.chain(query_a.items(), query_b.items())]}
'For the specified field name, parses the query and returns the value being assigned in the query. For example, get_value_from_query({\'_id\': 123}, \'_id\') 123 This mainly exists to deal with more complicated compound queries get_value_from_query( {\'$and\': [{\'_id\': 123}, {\'firstname\': \'mike\'}], \'_id\' 123 .....
def get_value_from_query(self, query, field_name):
if (field_name in query): return query[field_name] elif ('$and' in query): for condition in query['$and']: if (field_name in condition): return condition[field_name] raise KeyError
'For the specified field name, does the query contain it? Used know whether we need to parse a compound query. .. versionadded: 0.1.0 Support for parsing values embedded in compound db queries'
def query_contains_field(self, query, field_name):
try: self.get_value_from_query(query, field_name) except KeyError: return False return True
'Returns True if resource is empty; False otherwise. If there is no predefined filter on the resource we\'re relying on the db.collection.count(). However, if we do have a predefined filter we have to fallback on the find() method, which can be much slower. .. versionchanged:: 0.6 Support for multiple databases. .. ver...
def is_empty(self, resource):
(datasource, filter_, _, _) = self.datasource(resource) coll = self.pymongo(resource).db[datasource] try: if (not filter_): return (coll.count() == 0) else: try: del filter_[config.LAST_UPDATED] except: pass retu...
'Recursively iterates a JSON dictionary, turning RFC-1123 strings into datetime values and ObjectId-link strings into ObjectIds. .. versionchanged:: 0.3 \'query_objectid_as_string\' allows to bypass casting string types to objectids. .. versionchanged:: 0.1.1 Renamed from _jsondatetime to _mongotize, as it now handles ...
def _mongotize(self, source, resource):
schema = config.DOMAIN[resource] skip_objectid = schema.get('query_objectid_as_string', False) def try_cast(v): try: return datetime.strptime(v, config.DATE_FORMAT) except: if (not skip_objectid): try: try: r...
'Makes sure that only allowed operators are included in the query, aborts with a 400 otherwise. .. versionchanged:: 0.5 Abort with 400 if unsupported query operators are used. #387. DRY. .. versionchanged:: 0.0.9 More informative error messages. Allow ``auth_username_field`` to be set to ``ID_FIELD``. .. versionadded::...
def _sanitize(self, spec):
def sanitize_keys(spec): ops = set([op for op in spec.keys() if (op[0] == '$')]) unknown = (ops - Mongo.operators) if unknown: abort(400, description=debug_error_message(('Query contains unknown or unsupported operators: %s' % ', '.join(unknown)))) if...
'Syntactic sugar for the current collection write_concern setting. .. versionadded:: 0.0.8'
def _wc(self, resource):
return config.DOMAIN[resource]['mongo_write_concern']
'Returns the active mongo_prefix that should be used to retrieve a valid PyMongo instance from the cache. If \'self.mongo_prefix\' is set it has precedence over both endpoint (resource) and default drivers. This allows Auth classes (for instance) to override default settings to use a user-reserved db instance. Even a s...
def current_mongo_prefix(self, resource=None):
auth = None try: if ((resource is None) and request and request.endpoint): resource = request.endpoint[:request.endpoint.index('|')] if (request and request.endpoint): auth = resource_auth(resource) except ValueError: pass px = (auth.get_mongo_prefix() if ...
'Returns an active PyMongo instance. If \'prefix\' is defined then it has precedence over the endpoint (\'resource\') and/or \'self.mongo_instance\'. :param resource: endpoint for which a PyMongo instance is requested. :param prefix: PyMongo instance key. This has precedence over both \'resource\' and eventual `self.mo...
def pymongo(self, resource=None, prefix=None):
px = (prefix if prefix else self.current_mongo_prefix(resource=resource)) if (px not in self.driver): self.driver[px] = PyMongo(self.app, px) self.mongo_prefix = None try: return self.driver[px] except Exception as e: raise ConnectionException(e)
'Returns a pymongo Collection with the desired write_concern setting. PyMongo 3.0+ collections are immutable, yet we still want to allow the maintainer to change the write concern setting on the fly, hence the clone. .. versionadded:: 0.6.1'
def get_collection_with_write_concern(self, datasource, resource):
wc = WriteConcern(config.DOMAIN[resource]['mongo_write_concern']['w']) return self.pymongo(resource).db[datasource].with_options(write_concern=wc)
'Returns the \'default\' PyMongo instance, which is either the \'Mongo.mongo_prefix\' value or \'MONGO\'. This property is useful for backward compatibility as many custom Auth classes use the now obsolete \'self.data.driver.db[collection]\' pattern.'
@property def db(self):
return self.mongo.pymongo().db