INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Hash mutable arguments containers with immutable keys and values.
def argshash(self, args, kwargs): "Hash mutable arguments' containers with immutable keys and values." a = repr(args) b = repr(sorted((repr(k), repr(v)) for k, v in kwargs.items())) return a + b
Adds next to the context.
def get_context_data(self, **kwargs): """ Adds `next` to the context. This makes sure that the `next` parameter doesn't get lost if the form was submitted invalid. """ ctx = super(UserMediaImageViewMixin, self).get_context_data(**kwargs) ctx.update({ ...
Returns the success URL.
def get_success_url(self): """ Returns the success URL. This is either the given `next` URL parameter or the content object's `get_absolute_url` method's return value. """ if self.next: return self.next if self.object and self.object.content_object: ...
Adds useful objects to the class and performs security checks.
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class and performs security checks.""" self._add_next_and_user(request) self.content_object = None self.content_type = None self.object_id = kwargs.get('object_id', None) if kwargs.get('content_t...
Adds useful objects to the class.
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class.""" self._add_next_and_user(request) return super(DeleteImageView, self).dispatch(request, *args, **kwargs)
Making sure that a user can only delete his own images.
def get_queryset(self): """ Making sure that a user can only delete his own images. Even when he forges the request URL. """ queryset = super(DeleteImageView, self).get_queryset() queryset = queryset.filter(user=self.user) return queryset
Adds useful objects to the class.
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class.""" self._add_next_and_user(request) return super(UpdateImageView, self).dispatch(request, *args, **kwargs)
Making sure that a user can only edit his own images.
def get_queryset(self): """ Making sure that a user can only edit his own images. Even when he forges the request URL. """ queryset = super(UpdateImageView, self).get_queryset() queryset = queryset.filter(user=self.user) return queryset
Deletes all user media images of the given instance.
def _delete_images(self, instance): """Deletes all user media images of the given instance.""" UserMediaImage.objects.filter( content_type=ContentType.objects.get_for_model(instance), object_id=instance.pk, user=instance.user, ).delete()
It seems like in Django 1. 5 something has changed.
def clean_image(self): """ It seems like in Django 1.5 something has changed. When Django tries to validate the form, it checks if the generated filename fit into the max_length. But at this point, self.instance.user is not yet set so our filename generation function cannot crea...
Returns a unique filename for images.
def get_image_file_path(instance, filename): """Returns a unique filename for images.""" ext = filename.split('.')[-1] filename = '%s.%s' % (uuid.uuid4(), ext) return os.path.join( 'user_media', str(instance.user.pk), 'images', filename)
Makes sure that a an image is also deleted from the media directory.
def image_post_delete_handler(sender, instance, **kwargs): """ Makes sure that a an image is also deleted from the media directory. This should prevent a load of "dead" image files on disc. """ for f in glob.glob('{}/{}*'.format(instance.image.storage.location, ...
Returns a thumbnail s coordinates.
def box_coordinates(self): """Returns a thumbnail's coordinates.""" if ( self.thumb_x is not None and self.thumb_y is not None and self.thumb_x2 is not None and self.thumb_y2 is not None ): return ( int(self.thumb_x), ...
Returns a thumbnail s large size.
def large_size(self, as_string=True): """Returns a thumbnail's large size.""" size = getattr(settings, 'USER_MEDIA_THUMB_SIZE_LARGE', (150, 150)) if as_string: return u'{}x{}'.format(size[0], size[1]) return size
Uses box coordinates to crop an image without resizing it first.
def crop_box(im, box=False, **kwargs): """Uses box coordinates to crop an image without resizing it first.""" if box: im = im.crop(box) return im
Loads a GermaNet instance connected to the given MongoDB instance.
def load_germanet(host = None, port = None, database_name = 'germanet'): ''' Loads a GermaNet instance connected to the given MongoDB instance. Arguments: - `host`: the hostname of the MongoDB instance - `port`: the port number of the MongoDB instance - `database_name`: the name of the GermaNet...
Set the cache size used to reduce the number of database access operations.
def cache_size(self, new_value): ''' Set the cache size used to reduce the number of database access operations. ''' if type(new_value) == int and 0 < new_value: if self._lemma_cache is not None: self._lemma_cache = repoze.lru.LRUCache(new_value) ...
A generator over all the lemmas in the GermaNet database.
def all_lemmas(self): ''' A generator over all the lemmas in the GermaNet database. ''' for lemma_dict in self._mongo_db.lexunits.find(): yield Lemma(self, lemma_dict)
Looks up lemmas in the GermaNet database.
def lemmas(self, lemma, pos = None): ''' Looks up lemmas in the GermaNet database. Arguments: - `lemma`: - `pos`: ''' if pos is not None: if pos not in SHORT_POS_TO_LONG: return None pos = SHORT_POS_TO_LONG[pos] ...
A generator over all the synsets in the GermaNet database.
def all_synsets(self): ''' A generator over all the synsets in the GermaNet database. ''' for synset_dict in self._mongo_db.synsets.find(): yield Synset(self, synset_dict)
Looks up synsets in the GermaNet database.
def synsets(self, lemma, pos = None): ''' Looks up synsets in the GermaNet database. Arguments: - `lemma`: - `pos`: ''' return sorted(set(lemma_obj.synset for lemma_obj in self.lemmas(lemma, pos)))
Looks up a synset in GermaNet using its string representation.
def synset(self, synset_repr): ''' Looks up a synset in GermaNet using its string representation. Arguments: - `synset_repr`: a unicode string containing the lemma, part of speech, and sense number of the first lemma of the synset >>> gn.synset(u'funktionieren.v.2') ...
Builds a Synset object from the database entry with the given ObjectId.
def get_synset_by_id(self, mongo_id): ''' Builds a Synset object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object ''' cache_hit = None if self._synset_cache is not None: cache_hit = self...
Builds a Lemma object from the database entry with the given ObjectId.
def get_lemma_by_id(self, mongo_id): ''' Builds a Lemma object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object ''' cache_hit = None if self._lemma_cache is not None: cache_hit = self._l...
Tries to find the base form ( lemma ) of the given word using the data provided by the Projekt deutscher Wortschatz. This method returns a list of potential lemmas.
def lemmatise(self, word): ''' Tries to find the base form (lemma) of the given word, using the data provided by the Projekt deutscher Wortschatz. This method returns a list of potential lemmas. >>> gn.lemmatise(u'Männer') [u'Mann'] >>> gn.lemmatise(u'XYZ123') ...
Globs the XML files contained in the given directory and sorts them into sections for import into the MongoDB database.
def find_germanet_xml_files(xml_path): ''' Globs the XML files contained in the given directory and sorts them into sections for import into the MongoDB database. Arguments: - `xml_path`: the path to the directory containing the GermaNet XML files ''' xml_files = sorted(glob.glob(os.p...
Error checking of XML input: check that the given node has certain required attributes and does not have any unrecognised attributes.
def warn_attribs(loc, node, recognised_attribs, reqd_attribs=None): ''' Error checking of XML input: check that the given node has certain required attributes, and does not have any unrecognised attributes. Arguments: - `loc`: a string with som...
Reads in a GermaNet lexical information file and returns its contents as a list of dictionary structures.
def read_lexical_file(filename): ''' Reads in a GermaNet lexical information file and returns its contents as a list of dictionary structures. Arguments: - `filename`: the name of the XML file to read ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) sy...
Reads the GermaNet relation file gn_relations. xml which lists all the relations holding between lexical units and synsets.
def read_relation_file(filename): ''' Reads the GermaNet relation file ``gn_relations.xml`` which lists all the relations holding between lexical units and synsets. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) lex_rels = []...
Reads in a GermaNet wiktionary paraphrase file and returns its contents as a list of dictionary structures.
def read_paraphrase_file(filename): ''' Reads in a GermaNet wiktionary paraphrase file and returns its contents as a list of dictionary structures. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) assert doc.getroot().tag == 'w...
Reads in the given lexical information files and inserts their contents into the given MongoDB database.
def insert_lexical_information(germanet_db, lex_files): ''' Reads in the given lexical information files and inserts their contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `lex_files`: a list of paths to XML files containing lexial ...
Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database.
def insert_relation_information(germanet_db, gn_rels_file): ''' Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `gn_rels_file`: ''' lex_rels, con_rels = read_relation_fil...
Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database.
def insert_paraphrase_information(germanet_db, wiktionary_files): ''' Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `wiktionary_files`: ''' num_paraphrases = 0 # ca...
Creates the lemmatiser collection in the given MongoDB instance using the data derived from the Projekt deutscher Wortschatz.
def insert_lemmatisation_data(germanet_db): ''' Creates the lemmatiser collection in the given MongoDB instance using the data derived from the Projekt deutscher Wortschatz. Arguments: - `germanet_db`: a pymongo.database.Database object ''' # drop the database collection if it already exist...
For every synset in GermaNet inserts count information derived from SDEWAC.
def insert_infocontent_data(germanet_db): ''' For every synset in GermaNet, inserts count information derived from SDEWAC. Arguments: - `germanet_db`: a pymongo.database.Database object ''' gnet = germanet.GermaNet(germanet_db) # use add one smoothing gn_counts = defa...
For every part of speech in GermaNet computes the maximum min_depth in that hierarchy.
def compute_max_min_depth(germanet_db): ''' For every part of speech in GermaNet, computes the maximum min_depth in that hierarchy. Arguments: - `germanet_db`: a pymongo.database.Database object ''' gnet = germanet.GermaNet(germanet_db) max_min_depths = defaultdict(lambda: -1)...
Main function.
def main(): '''Main function.''' usage = ('\n\n %prog [options] XML_PATH\n\nArguments:\n\n ' 'XML_PATH the directory containing the ' 'GermaNet .xml files') parser = optparse.OptionParser(usage=usage) parser.add_option('--host', default=None, ...
in
def handle_In(self, node): '''in''' try: elts = node.elts except AttributeError: raise ParseError('Invalid value type for `in` operator: {0}'.format(node.__class__.__name__), col_offset=node.col_offset) return {'$in': list(map(self.fie...
Assign a value to this Value.
def AssignVar(self, value): """Assign a value to this Value.""" self.value = value # Call OnAssignVar on options. [option.OnAssignVar() for option in self.options]
Parse a Value declaration.
def Parse(self, value): """Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error. """ value_line = value.split(' ') if len(value_line) < 3: raise TextFSMTemplat...
Passes the line through each rule until a match is made.
def _CheckLine(self, line): """Passes the line through each rule until a match is made. Args: line: A string, the current input line. """ for rule in self._cur_state: matched = self._CheckRule(rule, line) if matched: for value in matched.groupdict(): self._AssignVar(...
Make graphite - api data points dictionary from Influxdb ResultSet data
def _make_graphite_api_points_list(influxdb_data): """Make graphite-api data points dictionary from Influxdb ResultSet data""" _data = {} for key in influxdb_data.keys(): _data[key[0]] = [(datetime.datetime.fromtimestamp(float(d['time'])), d['value']) for d in influxdb_data...
Setup log level and log file if set
def _setup_logger(self, level, log_file): """Setup log level and log file if set""" if logger.handlers: return level = getattr(logging, level.upper()) logger.setLevel(level) formatter = logging.Formatter( '[%(levelname)s] %(asctime)s - %(module)s.%(funcNam...
Turn glob ( graphite ) queries into compiled regex * becomes. *. becomes \. fmt argument is so that caller can control anchoring ( must contain exactly 1 { 0 } !
def compile_regex(self, fmt, query): """Turn glob (graphite) queries into compiled regex * becomes .* . becomes \. fmt argument is so that caller can control anchoring (must contain exactly 1 {0} !""" return re.compile(fmt.format( query.pattern.replace('.', '\.').repl...
Gets an <expression > and optional <schema >. <expression > should be a string of python code. <schema > should be a dictionary mapping field names to types.
def find(expression, schema=None): ''' Gets an <expression> and optional <schema>. <expression> should be a string of python code. <schema> should be a dictionary mapping field names to types. ''' parser = SchemaFreeParser() if schema is None else SchemaAwareParser(schema) return parser.pars...
Gets a list of <fields > to sort by. Also supports getting a single string for sorting by one field. Reverse sort is supported by appending - to the field name. Example: sort ( [ age - height ] ) will sort by ascending age and descending height.
def sort(fields): ''' Gets a list of <fields> to sort by. Also supports getting a single string for sorting by one field. Reverse sort is supported by appending '-' to the field name. Example: sort(['age', '-height']) will sort by ascending age and descending height. ''' from pymongo import ...
Return sorted version of nested dicts/ lists for comparing.
def ordered(obj): """ Return sorted version of nested dicts/lists for comparing. Modified from: http://stackoverflow.com/a/25851972 """ if isinstance(obj, collections.abc.Mapping): return sorted((k, ordered(v)) for k, v in obj.items()) # Special case str since it's a collections.abc...
Does not yield the input class
def walk_subclasses(root): """Does not yield the input class""" classes = [root] visited = set() while classes: cls = classes.pop() if cls is type or cls in visited: continue classes.extend(cls.__subclasses__()) visited.add(cls) if cls is not root: ...
dump the hash ( and range if there is one ) key ( s ) of an object into a dynamo - friendly format.
def dump_key(engine, obj): """dump the hash (and range, if there is one) key(s) of an object into a dynamo-friendly format. returns {dynamo_name: {type: value} for dynamo_name in hash/range keys} """ key = {} for key_column in obj.Meta.keys: key_value = getattr(obj, key_column.name, mis...
Return an expiration days in the future
def new_expiry(days=DEFAULT_PASTE_LIFETIME_DAYS): """Return an expiration `days` in the future""" now = delorean.Delorean() return now + datetime.timedelta(days=days)
Mark the object as having been persisted at least once.
def sync(obj, engine): """Mark the object as having been persisted at least once. Store the latest snapshot of all marked values.""" snapshot = Condition() # Only expect values (or lack of a value) for columns that have been explicitly set for column in sorted(_obj_tracking[obj]["marked"], key=lamb...
Provided for debug output when rendering conditions.
def printable_name(column, path=None): """Provided for debug output when rendering conditions. User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar """ pieces = [column.name] path = path or path_of(column) for segment in path: if isinstance(segment, str): pieces.append(segmen...
Yield all conditions within the given condition.
def iter_conditions(condition): """Yield all conditions within the given condition. If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found).""" conditions = list() visited = set() # Has to be split out, since we don't want to visit the root (for cyclic cond...
Yield all columns in the condition or its inner conditions.
def iter_columns(condition): """ Yield all columns in the condition or its inner conditions. Unwraps proxies when the condition's column (or any of its values) include paths. """ # Like iter_conditions, this can't live in each condition without going possibly infinite on the # recursion, or pas...
inner = True uses column. typedef. inner_type instead of column. typedef
def _value_ref(self, column, value, *, dumped=False, inner=False): """inner=True uses column.typedef.inner_type instead of column.typedef""" ref = ":v{}".format(self.next_index) # Need to dump this value if not dumped: typedef = column.typedef for segment in path...
Returns a NamedTuple of ( name type value ) for any type of reference.
def any_ref(self, *, column, value=missing, dumped=False, inner=False): """Returns a NamedTuple of (name, type, value) for any type of reference. .. code-block:: python # Name ref >>> tracker.any_ref(column=User.email) Reference(name='email', type='name', value=None...
Decrement the usage of each ref by 1.
def pop_refs(self, *refs): """Decrement the usage of each ref by 1. If this was the last use of a ref, remove it from attr_names or attr_values. """ for ref in refs: name = ref.name count = self.counts[name] # Not tracking this ref if coun...
Main entry point for rendering multiple expressions. All parameters are optional except obj when atomic or update are True.
def render(self, obj=None, condition=None, atomic=False, update=False, filter=None, projection=None, key=None): """Main entry point for rendering multiple expressions. All parameters are optional, except obj when atomic or update are True. :param obj: *(Optional)* An object to render an atomic...
The rendered wire format for all conditions that have been rendered. Rendered conditions are never cleared. A new: class: ~bloop. conditions. ConditionRenderer should be used for each operation.
def rendered(self): """The rendered wire format for all conditions that have been rendered. Rendered conditions are never cleared. A new :class:`~bloop.conditions.ConditionRenderer` should be used for each operation.""" expressions = {k: v for (k, v) in self.expressions.items() if v is not Non...
Replaces the attr dict at the given key with an instance of a Model
def _unpack(self, record, key, expected): """Replaces the attr dict at the given key with an instance of a Model""" attrs = record.get(key) if attrs is None: return obj = unpack_from_dynamodb( attrs=attrs, expected=expected, model=self.mode...
Repack a record into a cleaner structure for consumption.
def reformat_record(record): """Repack a record into a cleaner structure for consumption.""" return { "key": record["dynamodb"].get("Keys", None), "new": record["dynamodb"].get("NewImage", None), "old": record["dynamodb"].get("OldImage", None), "meta": { "created_at"...
List [ Dict ] - > Dict [ shard_id Shard ].
def unpack_shards(shards, stream_arn, session): """List[Dict] -> Dict[shard_id, Shard]. Each Shards' parent/children are hooked up with the other Shards in the list. """ if not shards: return {} # When unpacking tokens, shard id key is "shard_id" # When unpacking DescribeStream respons...
JSON - serializable representation of the current Shard state.
def token(self): """JSON-serializable representation of the current Shard state. The token is enough to rebuild the Shard as part of rebuilding a Stream. :returns: Shard state as a json-friendly dict :rtype: dict """ if self.iterator_type in RELATIVE_ITERATORS: ...
Generator that yields each: class: ~bloop. stream. shard. Shard by walking the shard s children in order.
def walk_tree(self): """Generator that yields each :class:`~bloop.stream.shard.Shard` by walking the shard's children in order.""" shards = collections.deque([self]) while shards: shard = shards.popleft() yield shard shards.extend(shard.children)
Move to a new position in the shard using the standard parameters to GetShardIterator.
def jump_to(self, *, iterator_type, sequence_number=None): """Move to a new position in the shard using the standard parameters to GetShardIterator. :param str iterator_type: "trim_horizon", "at_sequence", "after_sequence", "latest" :param str sequence_number: *(Optional)* Sequence number to us...
Move the Shard s iterator to the earliest record after the: class: ~datetime. datetime time.
def seek_to(self, position): """Move the Shard's iterator to the earliest record after the :class:`~datetime.datetime` time. Returns the first records at or past ``position``. If the list is empty, the seek failed to find records, either because the Shard is exhausted or it reached the...
If the Shard doesn t have any children tries to find some from DescribeStream.
def load_children(self): """If the Shard doesn't have any children, tries to find some from DescribeStream. If the Shard is open this won't find any children, so an empty response doesn't mean the Shard will **never** have children. """ # Child count is fixed the first time any ...
Get the next set of records in this shard. An empty list doesn t guarantee the shard is exhausted.
def get_records(self): """Get the next set of records in this shard. An empty list doesn't guarantee the shard is exhausted. :returns: A list of reformatted records. May be empty. """ # Won't be able to find new records. if self.exhausted: return [] # Alre...
Create backing tables for a model and its non - abstract subclasses.
def bind(self, model, *, skip_table_setup=False): """Create backing tables for a model and its non-abstract subclasses. :param model: Base model to bind. Can be abstract. :param skip_table_setup: Don't create or verify the table in DynamoDB. Default is False. :raises bloop.exceptions....
Delete one or more objects.
def delete(self, *objs, condition=None, atomic=False): """Delete one or more objects. :param objs: objects to delete. :param condition: only perform each delete if this condition holds. :param bool atomic: only perform each delete if the local and DynamoDB versions of the object match. ...
Populate objects from DynamoDB.
def load(self, *objs, consistent=False): """Populate objects from DynamoDB. :param objs: objects to delete. :param bool consistent: Use `strongly consistent reads`__ if True. Default is False. :raises bloop.exceptions.MissingKey: if any object doesn't provide a value for a key column. ...
Create a reusable: class: ~bloop. search. QueryIterator.
def query(self, model_or_index, key, filter=None, projection="all", consistent=False, forward=True): """Create a reusable :class:`~bloop.search.QueryIterator`. :param model_or_index: A model or index to query. For example, ``User`` or ``User.by_email``. :param key: Key condition. ...
Save one or more objects.
def save(self, *objs, condition=None, atomic=False): """Save one or more objects. :param objs: objects to save. :param condition: only perform each save if this condition holds. :param bool atomic: only perform each save if the local and DynamoDB versions of the object match. :r...
Create a reusable: class: ~bloop. search. ScanIterator.
def scan(self, model_or_index, filter=None, projection="all", consistent=False, parallel=None): """Create a reusable :class:`~bloop.search.ScanIterator`. :param model_or_index: A model or index to scan. For example, ``User`` or ``User.by_email``. :param filter: Filter condition. Only matching...
Create a: class: ~bloop. stream. Stream that provides approximate chronological ordering.
def stream(self, model, position): """Create a :class:`~bloop.stream.Stream` that provides approximate chronological ordering. .. code-block:: pycon # Create a user so we have a record >>> engine = Engine() >>> user = User(id=3, email="user@domain.com") ...
Create a new: class: ~bloop. transactions. ReadTransaction or: class: ~bloop. transactions. WriteTransaction.
def transaction(self, mode="w"): """ Create a new :class:`~bloop.transactions.ReadTransaction` or :class:`~bloop.transactions.WriteTransaction`. As a context manager, calling commit when the block exits: .. code-block:: pycon >>> engine = Engine() >>> user = Us...
Entry point for serializing values. Most custom types should use: func: ~bloop. types. Type. dynamo_dump.
def _dump(self, value, **kwargs): """Entry point for serializing values. Most custom types should use :func:`~bloop.types.Type.dynamo_dump`. This wraps the return value of :func:`~bloop.types.Type.dynamo_dump` in DynamoDB's wire format. For example, serializing a string enum to an int: ...
Entry point for deserializing values. Most custom types should use: func: ~bloop. types. Type. dynamo_load.
def _load(self, value, **kwargs): """Entry point for deserializing values. Most custom types should use :func:`~bloop.types.Type.dynamo_load`. This unpacks DynamoDB's wire format and calls :func:`~bloop.types.Type.dynamo_load` on the inner value. For example, deserializing an int to a string e...
Returns the DynamoDB backing type for a given python value s type
def backing_type_for(value): """Returns the DynamoDB backing type for a given python value's type :: 4 -> 'N' ['x', 3] -> 'L' {2, 4} -> 'SS' """ if isinstance(value, str): vtype = "S" elif isinstance(value, bytes): vty...
Monitor changes in approximately real - time and replicate them
def stream_replicate(): """Monitor changes in approximately real-time and replicate them""" stream = primary.stream(SomeDataBlob, "trim_horizon") next_heartbeat = pendulum.now() while True: now = pendulum.now() if now >= next_heartbeat: stream.heartbeat() next_hea...
Move to the trim_horizon or latest of the entire stream.
def _move_stream_endpoint(coordinator, position): """Move to the "trim_horizon" or "latest" of the entire stream.""" # 0) Everything will be rebuilt from DescribeStream. stream_arn = coordinator.stream_arn coordinator.roots.clear() coordinator.active.clear() coordinator.buffer.clear() # 1) ...
Scan through the * entire * Stream for the first record after time.
def _move_stream_time(coordinator, time): """Scan through the *entire* Stream for the first record after ``time``. This is an extremely expensive, naive algorithm that starts at trim_horizon and simply dumps records into the void until the first hit. General improvements in performance are tough; we c...
Move to the Stream position described by the token.
def _move_stream_token(coordinator, token): """Move to the Stream position described by the token. The following rules are applied when interpolation is required: - If a shard does not exist (past the trim_horizon) it is ignored. If that shard had children, its children are also checked against the ...
Poll active shards for records and insert them into the buffer. Rotate exhausted shards.
def advance_shards(self): """Poll active shards for records and insert them into the buffer. Rotate exhausted shards. Returns immediately if the buffer isn't empty. """ # Don't poll shards when there are pending records. if self.buffer: return # 0) Collect ...
Keep active shards with trim_horizon latest iterators alive by advancing their iterators.
def heartbeat(self): """Keep active shards with "trim_horizon", "latest" iterators alive by advancing their iterators.""" for shard in self.active: if shard.sequence_number is None: records = next(shard) # Success! This shard now has an ``at_sequence`` iterat...
JSON - serializable representation of the current Stream state.
def token(self): """JSON-serializable representation of the current Stream state. Use :func:`Engine.stream(YourModel, token) <bloop.engine.Engine.stream>` to create an identical stream, or :func:`stream.move_to(token) <bloop.stream.Stream.move_to>` to move an existing stream to this position. ...
Remove a Shard from the Coordinator. Drops all buffered records from the Shard.
def remove_shard(self, shard, drop_buffered_records=False): """Remove a Shard from the Coordinator. Drops all buffered records from the Shard. If the Shard is active or a root, it is removed and any children promoted to those roles. :param shard: The shard to remove :type shard: :cla...
Set the Coordinator to a specific endpoint or time or load state from a token.
def move_to(self, position): """Set the Coordinator to a specific endpoint or time, or load state from a token. :param position: "trim_horizon", "latest", :class:`~datetime.datetime`, or a :attr:`Coordinator.token <bloop.stream.coordinator.Coordinator.token>` """ if isinstan...
Create a tuple of ( ordering ( record shard )) for use in a RecordBuffer.
def heap_item(clock, record, shard): """Create a tuple of (ordering, (record, shard)) for use in a RecordBuffer.""" # Primary ordering is by event creation time. # However, creation time is *approximate* and has whole-second resolution. # This means two events in the same shard within one second can't b...
Push a new record into the buffer
def push(self, record, shard): """Push a new record into the buffer :param dict record: new record :param shard: Shard the record came from :type shard: :class:`~bloop.stream.shard.Shard` """ heapq.heappush(self.heap, heap_item(self.clock, record, shard))
Push multiple ( record shard ) pairs at once with only one: meth: heapq. heapify call to maintain order.
def push_all(self, record_shard_pairs): """Push multiple (record, shard) pairs at once, with only one :meth:`heapq.heapify` call to maintain order. :param record_shard_pairs: list of ``(record, shard)`` tuples (see :func:`~bloop.stream.buffer.RecordBuffer.push`). """ # Faste...
Yields each ( name value ) tuple for all columns in an object that aren t missing
def loaded_columns(obj: BaseModel): """Yields each (name, value) tuple for all columns in an object that aren't missing""" for column in sorted(obj.Meta.columns, key=lambda c: c.name): value = getattr(obj, column.name, missing) if value is not missing: yield column.name, value
Push values by dynamo_name into an object
def unpack_from_dynamodb(*, attrs, expected, model=None, obj=None, engine=None, context=None, **kwargs): """Push values by dynamo_name into an object""" context = context or {"engine": engine} engine = engine or context.get("engine", None) if not engine: raise ValueError("You must provide engine...
Set an object s field to default if it doesn t have a value
def setdefault(obj, field, default): """Set an object's field to default if it doesn't have a value""" setattr(obj, field, getattr(obj, field, default))
Bind a column to the model with the given name.
def bind_column(model, name, column, force=False, recursive=False, copy=False) -> Column: """Bind a column to the model with the given name. This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily attach a new column to an existing model: .. code-block:: pyt...
Bind an index to the model with the given name.
def bind_index(model, name, index, force=False, recursive=True, copy=False) -> Index: """Bind an index to the model with the given name. This method is primarily used during BaseModel.__init_subclass__, although it can be used to easily attach a new index to an existing model: .. code-bloc...
Recalculate the projection hash_key and range_key for the given index.
def refresh_index(meta, index) -> None: """Recalculate the projection, hash_key, and range_key for the given index. :param meta: model.Meta to find columns by name :param index: The index to refresh """ # All projections include model + index keys projection_keys = set.union(meta.keys, index.ke...
Unconditionally remove any columns or indexes bound to the given name or dynamo_name.
def unbind(meta, name=None, dynamo_name=None) -> None: """Unconditionally remove any columns or indexes bound to the given name or dynamo_name. .. code-block:: python import bloop.models class User(BaseModel): id = Column(String, hash_key=True) email = Column(String, ...
dict ( dynamo name ) - > obj
def _load(cls, attrs, *, context, **kwargs): """ dict (dynamo name) -> obj """ return unpack_from_dynamodb( model=cls, attrs=attrs or {}, expected=cls.Meta.columns, context=context, **kwargs)
obj - > dict
def _dump(cls, obj, *, context, **kwargs): """ obj -> dict """ if obj is None: return None dump = context["engine"]._dump filtered = filter( lambda item: item[1] is not None, (( column.dynamo_name, dump(column.typedef, g...