INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
This is an object list where thre is no first field name to give a hint of what the first field name should be
def missingkeys_nonstandard(block, commdct, dtls, objectlist, afield='afiled %s'): """This is an object list where thre is no first field name to give a hint of what the first field name should be""" afield = 'afield %s' for key_txt in objectlist: key_i = dtls.index(key_txt.upper()) comm...
Return a EventLoop instance.
def get_event_loop(): """Return a EventLoop instance. A new instance is created for each new HTTP request. We determine that we're in a new request by inspecting os.environ, which is reset at the start of each request. Also, each thread gets its own loop. """ ev = _state.event_loop if not os.getenv(_EV...
Remove all pending events without running any.
def clear(self): """Remove all pending events without running any.""" while self.current or self.idlers or self.queue or self.rpcs: current = self.current idlers = self.idlers queue = self.queue rpcs = self.rpcs _logging_debug('Clearing stale EventLoop instance...') if curren...
Insert event in queue and keep it sorted assuming queue is sorted.
def insort_event_right(self, event, lo=0, hi=None): """Insert event in queue, and keep it sorted assuming queue is sorted. If event is already in queue, insert it to the right of the rightmost event (to keep FIFO order). Optional args lo (default 0) and hi (default len(a)) bound the slice of a to ...
Schedule a function call at a specific time in the future.
def queue_call(self, delay, callback, *args, **kwds): """Schedule a function call at a specific time in the future.""" if delay is None: self.current.append((callback, args, kwds)) return if delay < 1e9: when = delay + self.clock.now() else: # Times over a billion seconds are ass...
Schedule an RPC with an optional callback.
def queue_rpc(self, rpc, callback=None, *args, **kwds): """Schedule an RPC with an optional callback. The caller must have previously sent the call to the service. The optional callback is called with the remaining arguments. NOTE: If the rpc is a MultiRpc, the callback will be called once for eac...
Add an idle callback.
def add_idle(self, callback, *args, **kwds): """Add an idle callback. An idle callback can return True, False or None. These mean: - None: remove the callback (don't reschedule) - False: the callback did no work; reschedule later - True: the callback did some work; reschedule soon If the cal...
Run one of the idle callbacks.
def run_idle(self): """Run one of the idle callbacks. Returns: True if one was called, False if no idle callback was called. """ if not self.idlers or self.inactive >= len(self.idlers): return False idler = self.idlers.popleft() callback, args, kwds = idler _logging_debug('idler...
Run one item ( a callback or an RPC wait_any ).
def run0(self): """Run one item (a callback or an RPC wait_any). Returns: A time to sleep if something happened (may be 0); None if all queues are empty. """ if self.current: self.inactive = 0 callback, args, kwds = self.current.popleft() _logging_debug('nowevent: %s', cal...
Run one item ( a callback or an RPC wait_any ) or sleep.
def run1(self): """Run one item (a callback or an RPC wait_any) or sleep. Returns: True if something happened; False if all queues are empty. """ delay = self.run0() if delay is None: return False if delay > 0: self.clock.sleep(delay) return True
Helper for GQL parsing to extract values from GQL expressions.
def _args_to_val(func, args): """Helper for GQL parsing to extract values from GQL expressions. This can extract the value from a GQL literal, return a Parameter for a GQL bound parameter (:1 or :foo), and interprets casts like KEY(...) and plain lists of values like (1, 2, 3). Args: func: A string indi...
Helper for FQL parsing to turn a property name into a property object.
def _get_prop_from_modelclass(modelclass, name): """Helper for FQL parsing to turn a property name into a property object. Args: modelclass: The model class specified in the query. name: The property name. This may contain dots which indicate sub-properties of structured properties. Returns: ...
Parse a GQL query string.
def gql(query_string, *args, **kwds): """Parse a GQL query string. Args: query_string: Full GQL query, e.g. 'SELECT * FROM Kind WHERE prop = 1'. *args, **kwds: If present, used to call bind(). Returns: An instance of query_class. """ qry = _gql(query_string) if args or kwds: qry = qry._bin...
Parse a GQL query string ( internal version ).
def _gql(query_string, query_class=Query): """Parse a GQL query string (internal version). Args: query_string: Full GQL query, e.g. 'SELECT * FROM Kind WHERE prop = 1'. query_class: Optional class to use, default Query. Returns: An instance of query_class. """ from .google_imports import gql # ...
Apply the filter to values extracted from an entity.
def _apply(self, key_value_map): """Apply the filter to values extracted from an entity. Think of self.match_keys and self.match_values as representing a table with one row. For example: match_keys = ('name', 'age', 'rank') match_values = ('Joe', 24, 5) (Except that in reality, the value...
Internal helper to fix the namespace.
def _fix_namespace(self): """Internal helper to fix the namespace. This is called to ensure that for queries without an explicit namespace, the namespace used by async calls is the one in effect at the time the async call is made, not the one in effect when the the request is actually generated. ...
Run this query putting entities into the given queue.
def run_to_queue(self, queue, conn, options=None, dsquery=None): """Run this query, putting entities into the given queue.""" try: multiquery = self._maybe_multi_query() if multiquery is not None: yield multiquery.run_to_queue(queue, conn, options=options) return if dsquery is...
True if results are guaranteed to contain a unique set of property values.
def is_distinct(self): """True if results are guaranteed to contain a unique set of property values. This happens when every property in the group_by is also in the projection. """ return bool(self.__group_by and set(self._to_property_names(self.__group_by)) <= set(s...
Return a new Query with additional filter ( s ) applied.
def filter(self, *args): """Return a new Query with additional filter(s) applied.""" if not args: return self preds = [] f = self.filters if f: preds.append(f) for arg in args: if not isinstance(arg, Node): raise TypeError('Cannot filter a non-Node argument; received %r...
Return a new Query with additional sort order ( s ) applied.
def order(self, *args): """Return a new Query with additional sort order(s) applied.""" # q.order(Employee.name, -Employee.age) if not args: return self orders = [] o = self.orders if o: orders.append(o) for arg in args: if isinstance(arg, model.Property): orders.ap...
Map a callback function or tasklet over the query results.
def map(self, callback, pass_batch_into_callback=None, merge_future=None, **q_options): """Map a callback function or tasklet over the query results. Args: callback: A function or tasklet to be applied to each result; see below. merge_future: Optional Future subclass; see below. **q...
Map a callback function or tasklet over the query results.
def map_async(self, callback, pass_batch_into_callback=None, merge_future=None, **q_options): """Map a callback function or tasklet over the query results. This is the asynchronous version of Query.map(). """ qry = self._fix_namespace() return tasklets.get_context().map_query( ...
Fetch a list of query results up to a limit.
def fetch_async(self, limit=None, **q_options): """Fetch a list of query results, up to a limit. This is the asynchronous version of Query.fetch(). """ if limit is None: default_options = self._make_options(q_options) if default_options is not None and default_options.limit is not None: ...
Internal version of get_async ().
def _get_async(self, **q_options): """Internal version of get_async().""" res = yield self.fetch_async(1, **q_options) if not res: raise tasklets.Return(None) raise tasklets.Return(res[0])
Count the number of query results up to a limit.
def count_async(self, limit=None, **q_options): """Count the number of query results, up to a limit. This is the asynchronous version of Query.count(). """ qry = self._fix_namespace() return qry._count_async(limit=limit, **q_options)
Internal version of count_async ().
def _count_async(self, limit=None, **q_options): """Internal version of count_async().""" # TODO: Support offset by incorporating it to the limit. if 'offset' in q_options: raise NotImplementedError('.count() and .count_async() do not support ' 'offsets at present.') ...
Fetch a page of results.
def fetch_page_async(self, page_size, **q_options): """Fetch a page of results. This is the asynchronous version of Query.fetch_page(). """ qry = self._fix_namespace() return qry._fetch_page_async(page_size, **q_options)
Internal version of fetch_page_async ().
def _fetch_page_async(self, page_size, **q_options): """Internal version of fetch_page_async().""" q_options.setdefault('batch_size', page_size) q_options.setdefault('produce_cursors', True) it = self.iter(limit=page_size + 1, **q_options) results = [] while (yield it.has_next_async()): re...
Helper to construct a QueryOptions object from keyword arguments.
def _make_options(self, q_options): """Helper to construct a QueryOptions object from keyword arguments. Args: q_options: a dict of keyword arguments. Note that either 'options' or 'config' can be used to pass another QueryOptions object, but not both. If another QueryOptions object is give...
Return a list giving the parameters required by a query.
def analyze(self): """Return a list giving the parameters required by a query.""" class MockBindings(dict): def __contains__(self, key): self[key] = None return True bindings = MockBindings() used = {} ancestor = self.ancestor if isinstance(ancestor, ParameterizedThing): ...
Bind parameter values. Returns a new Query object.
def _bind(self, args, kwds): """Bind parameter values. Returns a new Query object.""" bindings = dict(kwds) for i, arg in enumerate(args): bindings[i + 1] = arg used = {} ancestor = self.ancestor if isinstance(ancestor, ParameterizedThing): ancestor = ancestor.resolve(bindings, used...
Return the cursor before the current item.
def cursor_before(self): """Return the cursor before the current item. You must pass a QueryOptions object with produce_cursors=True for this to work. If there is no cursor or no current item, raise BadArgumentError. Before next() has returned there is no cursor. Once the loop is exhausted, t...
Return the cursor after the current item.
def cursor_after(self): """Return the cursor after the current item. You must pass a QueryOptions object with produce_cursors=True for this to work. If there is no cursor or no current item, raise BadArgumentError. Before next() has returned there is no cursor. Once the loop is exhausted, t...
Return a Future whose result will say whether a next item is available.
def has_next_async(self): """Return a Future whose result will say whether a next item is available. See the module docstring for the usage pattern. """ if self._fut is None: self._fut = self._iter.getq() flag = True try: yield self._fut except EOFError: flag = False r...
Iterator protocol: get next item or raise StopIteration.
def next(self): """Iterator protocol: get next item or raise StopIteration.""" if self._fut is None: self._fut = self._iter.getq() try: try: # The future result is set by this class's _extended_callback # method. # pylint: disable=unpacking-non-sequence (ent, ...
Run this query putting entities into the given queue.
def run_to_queue(self, queue, conn, options=None): """Run this query, putting entities into the given queue.""" if options is None: # Default options. offset = None limit = None keys_only = None else: # Capture options we need to simulate. offset = options.offset li...
An auto - batching wrapper for memcache. get () or. get_multi ().
def memcache_get(self, key, for_cas=False, namespace=None, use_cache=False, deadline=None): """An auto-batching wrapper for memcache.get() or .get_multi(). Args: key: Key to set. This must be a string; no prefix is applied. for_cas: If True, request and store CAS ids on the Cont...
A decorator to declare that only the first N arguments may be positional.
def positional(max_pos_args): """A decorator to declare that only the first N arguments may be positional. Note that for methods, n includes 'self'. """ __ndb_debug__ = 'SKIP' def positional_decorator(wrapped): if not DEBUG: return wrapped __ndb_debug__ = 'SKIP' @wrapping(wrapped) def...
Converts a function into a decorator that optionally accepts keyword arguments in its declaration.
def decorator(wrapped_decorator): """Converts a function into a decorator that optionally accepts keyword arguments in its declaration. Example usage: @utils.decorator def decorator(func, args, kwds, op1=None): ... apply op1 ... return func(*args, **kwds) # Form (1), vanilla @decorat...
A recursive Fibonacci to exercise task switching.
def fibonacci(n): """A recursive Fibonacci to exercise task switching.""" if n <= 1: raise ndb.Return(n) a, b = yield fibonacci(n - 1), fibonacci(n - 2) raise ndb.Return(a + b)
A memoizing recursive Fibonacci to exercise RPCs.
def memoizing_fibonacci(n): """A memoizing recursive Fibonacci to exercise RPCs.""" if n <= 1: raise ndb.Return(n) key = ndb.Key(FibonacciMemo, str(n)) memo = yield key.get_async(ndb_should_cache=False) if memo is not None: assert memo.arg == n logging.info('memo hit: %d -> %d', n, memo.value) ...
Actually run the _todo_tasklet.
def run_queue(self, options, todo): """Actually run the _todo_tasklet.""" utils.logging_debug('AutoBatcher(%s): %d items', self._todo_tasklet.__name__, len(todo)) batch_fut = self._todo_tasklet(todo, options) self._running.append(batch_fut) # Add a callback when we're done. ...
Adds an arg and gets back a future.
def add(self, arg, options=None): """Adds an arg and gets back a future. Args: arg: one argument for _todo_tasklet. options: rpc options. Return: An instance of future, representing the result of running _todo_tasklet without batching. """ fut = tasklets.Future('%s.add(%s...
Passes exception along.
def _finished_callback(self, batch_fut, todo): """Passes exception along. Args: batch_fut: the batch future returned by running todo_tasklet. todo: (fut, option) pair. fut is the future return by each add() call. If the batch fut was successful, it has already called fut.set_result() on ot...
Return all namespaces in the specified range.
def get_namespaces(start=None, end=None): """Return all namespaces in the specified range. Args: start: only return namespaces >= start if start is not None. end: only return namespaces < end if end is not None. Returns: A list of namespace names between the (optional) start and end values. """ ...
Return all kinds in the specified range for the current namespace.
def get_kinds(start=None, end=None): """Return all kinds in the specified range, for the current namespace. Args: start: only return kinds >= start if start is not None. end: only return kinds < end if end is not None. Returns: A list of kind names between the (optional) start and end values. """ ...
Return all properties of kind in the specified range.
def get_properties_of_kind(kind, start=None, end=None): """Return all properties of kind in the specified range. NOTE: This function does not return unindexed properties. Args: kind: name of kind whose properties you want. start: only return properties >= start if start is not None. end: only return...
Return all representations of properties of kind in the specified range.
def get_representations_of_kind(kind, start=None, end=None): """Return all representations of properties of kind in the specified range. NOTE: This function does not return unindexed properties. Args: kind: name of kind whose properties you want. start: only return properties >= start if start is not No...
Return the version of the entity group containing key.
def get_entity_group_version(key): """Return the version of the entity group containing key. Args: key: a key for an entity group whose __entity_group__ key you want. Returns: The version of the entity group containing key. This version is guaranteed to increase on every change to the entity group. ...
Return the Key for a namespace.
def key_for_namespace(cls, namespace): """Return the Key for a namespace. Args: namespace: A string giving the namespace whose key is requested. Returns: The Key for the namespace. """ if namespace: return model.Key(cls.KIND_NAME, namespace) else: return model.Key(cls.K...
Return the __property__ key for property of kind.
def key_for_property(cls, kind, property): """Return the __property__ key for property of kind. Args: kind: kind whose key is requested. property: property whose key is requested. Returns: The key for property of kind. """ return model.Key(Kind.KIND_NAME, kind, Property.KIND_NAME...
Return the kind specified by a given __property__ key.
def key_to_kind(cls, key): """Return the kind specified by a given __property__ key. Args: key: key whose kind name is requested. Returns: The kind specified by key. """ if key.kind() == Kind.KIND_NAME: return key.id() else: return key.parent().id()
Return the key for the entity group containing key.
def key_for_entity_group(cls, key): """Return the key for the entity group containing key. Args: key: a key for an entity group whose __entity_group__ key you want. Returns: The __entity_group__ key for the entity group containing key. """ return model.Key(cls.KIND_NAME, cls.ID, parent...
Called by Django before deciding which view to execute.
def process_request(self, unused_request): """Called by Django before deciding which view to execute.""" # Compare to the first half of toplevel() in context.py. tasklets._state.clear_all_pending() # Create and install a new context. ctx = tasklets.make_default_context() tasklets.set_context(ctx...
Helper to construct a ContextOptions object from keyword arguments.
def _make_ctx_options(ctx_options, config_cls=ContextOptions): """Helper to construct a ContextOptions object from keyword arguments. Args: ctx_options: A dict of keyword arguments. config_cls: Optional Configuration class to use, default ContextOptions. Note that either 'options' or 'config' can be use...
Set the context cache policy function.
def set_cache_policy(self, func): """Set the context cache policy function. Args: func: A function that accepts a Key instance as argument and returns a bool indicating if it should be cached. May be None. """ if func is None: func = self.default_cache_policy elif isinstance(fu...
Return whether to use the context cache for this key.
def _use_cache(self, key, options=None): """Return whether to use the context cache for this key. Args: key: Key instance. options: ContextOptions instance, or None. Returns: True if the key should be cached, False otherwise. """ flag = ContextOptions.use_cache(options) if fl...
Set the memcache policy function.
def set_memcache_policy(self, func): """Set the memcache policy function. Args: func: A function that accepts a Key instance as argument and returns a bool indicating if it should be cached. May be None. """ if func is None: func = self.default_memcache_policy elif isinstance(f...
Return whether to use memcache for this key.
def _use_memcache(self, key, options=None): """Return whether to use memcache for this key. Args: key: Key instance. options: ContextOptions instance, or None. Returns: True if the key should be cached in memcache, False otherwise. """ flag = ContextOptions.use_memcache(options) ...
Default datastore policy.
def default_datastore_policy(key): """Default datastore policy. This defers to _use_datastore on the Model class. Args: key: Key instance. Returns: A bool or None. """ flag = None if key is not None: modelclass = model.Model._kind_map.get(key.kind()) if modelclass ...
Set the context datastore policy function.
def set_datastore_policy(self, func): """Set the context datastore policy function. Args: func: A function that accepts a Key instance as argument and returns a bool indicating if it should use the datastore. May be None. """ if func is None: func = self.default_datastore_policy ...
Return whether to use the datastore for this key.
def _use_datastore(self, key, options=None): """Return whether to use the datastore for this key. Args: key: Key instance. options: ContextOptions instance, or None. Returns: True if the datastore should be used, False otherwise. """ flag = ContextOptions.use_datastore(options) ...
Default memcache timeout policy.
def default_memcache_timeout_policy(key): """Default memcache timeout policy. This defers to _memcache_timeout on the Model class. Args: key: Key instance. Returns: Memcache timeout to use (integer), or None. """ timeout = None if key is not None and isinstance(key, model.Key)...
Set the policy function for memcache timeout ( expiration ).
def set_memcache_timeout_policy(self, func): """Set the policy function for memcache timeout (expiration). Args: func: A function that accepts a key instance as argument and returns an integer indicating the desired memcache timeout. May be None. If the function returns 0 it implies the def...
Return the memcache timeout ( expiration ) for this key.
def _get_memcache_timeout(self, key, options=None): """Return the memcache timeout (expiration) for this key.""" timeout = ContextOptions.memcache_timeout(options) if timeout is None: timeout = self._memcache_timeout_policy(key) if timeout is None: timeout = ContextOptions.memcache_timeout(s...
Returns a cached Model instance given the entity key if available.
def _load_from_cache_if_available(self, key): """Returns a cached Model instance given the entity key if available. Args: key: Key instance. Returns: A Model instance if the key exists in the cache. """ if key in self._cache: entity = self._cache[key] # May be None, meaning "doe...
Return a Model instance given the entity key.
def get(self, key, **ctx_options): """Return a Model instance given the entity key. It will use the context cache if the cache policy for the given key is enabled. Args: key: Key instance. **ctx_options: Context options. Returns: A Model instance if the key exists in the datasto...
Call a callback upon successful commit of a transaction.
def call_on_commit(self, callback): """Call a callback upon successful commit of a transaction. If not in a transaction, the callback is called immediately. In a transaction, multiple callbacks may be registered and will be called once the transaction commits, in the order in which they were regis...
Return a Future for a nickname from an account.
def get_nickname(userid): """Return a Future for a nickname from an account.""" account = yield get_account(userid) if not account: nickname = 'Unregistered' else: nickname = account.nickname or account.email raise ndb.Return(nickname)
Marks a task as done.
def mark_done(task_id): """Marks a task as done. Args: task_id: The integer id of the task to update. Raises: ValueError: if the requested task doesn't exist. """ task = Task.get_by_id(task_id) if task is None: raise ValueError('Task with id %d does not exist' % task_id) task.done = True t...
Converts a list of tasks to a list of string representations.
def format_tasks(tasks): """Converts a list of tasks to a list of string representations. Args: tasks: A list of the tasks to convert. Returns: A list of string formatted tasks. """ return ['%d : %s (%s)' % (task.key.id(), task.description, ('do...
Accepts a string command and performs an action.
def handle_command(command): """Accepts a string command and performs an action. Args: command: the command to run as a string. """ try: cmds = command.split(None, 1) cmd = cmds[0] if cmd == 'new': add_task(get_arg(cmds)) elif cmd == 'done': mark_done(int(get_arg(cmds))) eli...
Async version of delete ().
def delete_async(blob_key, **options): """Async version of delete().""" if not isinstance(blob_key, (basestring, BlobKey)): raise TypeError('Expected blob key, got %r' % (blob_key,)) rpc = blobstore.create_rpc(**options) yield blobstore.delete_async(blob_key, rpc=rpc)
Async version of delete_multi ().
def delete_multi_async(blob_keys, **options): """Async version of delete_multi().""" if isinstance(blob_keys, (basestring, BlobKey)): raise TypeError('Expected a list, got %r' % (blob_key,)) rpc = blobstore.create_rpc(**options) yield blobstore.delete_async(blob_keys, rpc=rpc)
Create upload URL for POST form.
def create_upload_url(success_path, max_bytes_per_blob=None, max_bytes_total=None, **options): """Create upload URL for POST form. Args: success_path: Path within application to call when POST is successful and upload is complete. max_...
Async version of create_upload_url ().
def create_upload_url_async(success_path, max_bytes_per_blob=None, max_bytes_total=None, **options): """Async version of create_upload_url().""" rpc = blobstore.create_rpc(**options) rpc = blobstore.create_upload_url_async(success...
Parse a BlobInfo record from file upload field_storage.
def parse_blob_info(field_storage): """Parse a BlobInfo record from file upload field_storage. Args: field_storage: cgi.FieldStorage that represents uploaded blob. Returns: BlobInfo record as parsed from the field-storage instance. None if there was no field_storage. Raises: BlobInfoParseErro...
Fetch data for blob.
def fetch_data(blob, start_index, end_index, **options): """Fetch data for blob. Fetches a fragment of a blob up to MAX_BLOB_FETCH_SIZE in length. Attempting to fetch a fragment that extends beyond the boundaries of the blob will return the amount of data from start_index until the end of the blob, which will...
Async version of fetch_data ().
def fetch_data_async(blob, start_index, end_index, **options): """Async version of fetch_data().""" if isinstance(blob, BlobInfo): blob = blob.key() rpc = blobstore.create_rpc(**options) rpc = blobstore.fetch_data_async(blob, start_index, end_index, rpc=rpc) result = yield rpc raise tasklets.Return(resu...
Retrieve a BlobInfo by key.
def get(cls, blob_key, **ctx_options): """Retrieve a BlobInfo by key. Args: blob_key: A blob key. This may be a str, unicode or BlobKey instance. **ctx_options: Context options for Model().get_by_id(). Returns: A BlobInfo entity associated with the provided key, If there was no s...
Async version of get ().
def get_async(cls, blob_key, **ctx_options): """Async version of get().""" if not isinstance(blob_key, (BlobKey, basestring)): raise TypeError('Expected blob key, got %r' % (blob_key,)) if 'parent' in ctx_options: raise TypeError('Parent is not supported') return cls.get_by_id_async(str(blob...
Multi - key version of get ().
def get_multi(cls, blob_keys, **ctx_options): """Multi-key version of get(). Args: blob_keys: A list of blob keys. **ctx_options: Context options for Model().get_by_id(). Returns: A list whose items are each either a BlobInfo entity or None. """ futs = cls.get_multi_async(blob_ke...
Async version of get_multi ().
def get_multi_async(cls, blob_keys, **ctx_options): """Async version of get_multi().""" for blob_key in blob_keys: if not isinstance(blob_key, (BlobKey, basestring)): raise TypeError('Expected blob key, got %r' % (blob_key,)) if 'parent' in ctx_options: raise TypeError('Parent is not sup...
Permanently delete this blob from Blobstore.
def delete(self, **options): """Permanently delete this blob from Blobstore. Args: **options: Options for create_rpc(). """ fut = delete_async(self.key(), **options) fut.get_result()
Fills the internal buffer.
def __fill_buffer(self, size=0): """Fills the internal buffer. Args: size: Number of bytes to read. Will be clamped to [self.__buffer_size, MAX_BLOB_FETCH_SIZE]. """ read_size = min(max(size, self.__buffer_size), MAX_BLOB_FETCH_SIZE) self.__buffer = fetch_data(self.__blob_key, self._...
Returns the BlobInfo for this file.
def blob_info(self): """Returns the BlobInfo for this file.""" if not self.__blob_info: self.__blob_info = BlobInfo.get(self.__blob_key) return self.__blob_info
Create a new Connection object with the right adapter.
def make_connection(config=None, default_model=None, _api_version=datastore_rpc._DATASTORE_V3, _id_resolver=None): """Create a new Connection object with the right adapter. Optionally you can pass in a datastore_rpc.Configuration object. """ return datastore_rpc.Connecti...
Internal helper to unpack a User value from a protocol buffer.
def _unpack_user(v): """Internal helper to unpack a User value from a protocol buffer.""" uv = v.uservalue() email = unicode(uv.email().decode('utf-8')) auth_domain = unicode(uv.auth_domain().decode('utf-8')) obfuscated_gaiaid = uv.obfuscated_gaiaid().decode('utf-8') obfuscated_gaiaid = unicode(obfuscated_g...
Convert a date to a datetime for Cloud Datastore storage.
def _date_to_datetime(value): """Convert a date to a datetime for Cloud Datastore storage. Args: value: A datetime.date object. Returns: A datetime object with time set to 0:00. """ if not isinstance(value, datetime.date): raise TypeError('Cannot convert to datetime expected date value; ' ...
Convert a time to a datetime for Cloud Datastore storage.
def _time_to_datetime(value): """Convert a time to a datetime for Cloud Datastore storage. Args: value: A datetime.time object. Returns: A datetime object with date set to 1970-01-01. """ if not isinstance(value, datetime.time): raise TypeError('Cannot convert to datetime expected time value; ' ...
Decorator to make a function automatically run in a transaction.
def transactional(func, args, kwds, **options): """Decorator to make a function automatically run in a transaction. Args: **ctx_options: Transaction options (see transaction(), but propagation default to TransactionOptions.ALLOWED). This supports two forms: (1) Vanilla: @transactional d...
The async version of
def transactional_async(func, args, kwds, **options): """The async version of @ndb.transaction.""" options.setdefault('propagation', datastore_rpc.TransactionOptions.ALLOWED) if args or kwds: return transaction_async(lambda: func(*args, **kwds), **options) return transaction_async(func, **options)
The async version of @ndb. transaction.
def transactional_tasklet(func, args, kwds, **options): """The async version of @ndb.transaction. Will return the result of the wrapped function as a Future. """ from . import tasklets func = tasklets.tasklet(func) return transactional_async.wrapped_decorator(func, args, kwds, **options)
A decorator that ensures a function is run outside a transaction.
def non_transactional(func, args, kwds, allow_existing=True): """A decorator that ensures a function is run outside a transaction. If there is an existing transaction (and allow_existing=True), the existing transaction is paused while the function is executed. Args: allow_existing: If false, throw an exce...
Updates all descendants to a specified value.
def _set(self, value): """Updates all descendants to a specified value.""" if self.__is_parent_node(): for child in self.__sub_counters.itervalues(): child._set(value) else: self.__counter = value
Internal helper for comparison operators.
def _comparison(self, op, value): """Internal helper for comparison operators. Args: op: The operator ('=', '<' etc.). Returns: A FilterNode instance representing the requested comparison. """ # NOTE: This is also used by query.gql(). if not self._indexed: raise datastore_err...
Comparison operator for the in comparison operator.
def _IN(self, value): """Comparison operator for the 'in' comparison operator. The Python 'in' operator cannot be overloaded in the way we want to, so we define a method. For example:: Employee.query(Employee.rank.IN([4, 5, 6])) Note that the method is called ._IN() but may normally be invoked...
Call all validations on the value.
def _do_validate(self, value): """Call all validations on the value. This calls the most derived _validate() method(s), then the custom validator function, and then checks the choices. It returns the value, possibly modified in an idempotent way, or raises an exception. Note that this does no...
Internal helper called to tell the property its name.
def _fix_up(self, cls, code_name): """Internal helper called to tell the property its name. This is called by _fix_up_properties() which is called by MetaModel when finishing the construction of a Model subclass. The name passed in is the name of the class attribute to which the Property is assigne...
Internal helper to set a value in an entity for a Property.
def _set_value(self, entity, value): """Internal helper to set a value in an entity for a Property. This performs validation first. For a repeated Property the value should be a list. """ if entity._projection: raise ReadonlyPropertyError( 'You cannot set property values of a proje...