From d3ca5f342e720564313c6aa101058711b692be98 Mon Sep 17 00:00:00 2001 From: Davide Alberani Date: Fri, 1 May 2015 16:27:22 +0200 Subject: [PATCH] incremental sequences to print short unique IDs --- backend.py | 5 +++-- eventman_server.py | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/backend.py b/backend.py index bc593e9..f6b4351 100644 --- a/backend.py +++ b/backend.py @@ -32,7 +32,8 @@ class EventManDB(object): 'update': '$set', 'append': '$push', 'appendUnique': '$addToSet', - 'delete': '$pull' + 'delete': '$pull', + 'increment': '$inc' } def __init__(self, url=None, dbName='eventman'): @@ -189,7 +190,7 @@ class EventManDB(object): :type _id_or_query: str or :class:`~bson.objectid.ObjectId` or iterable :param data: the updated information to store :type data: dict - :param operation: operation used to update the document or a portion of it, like a list (update, append, appendUnique, delete) + :param operation: operation used to update the document or a portion of it, like a list (update, append, appendUnique, delete, increment) :type operation: str :param updateList: if set, it's considered the name of a list (the first matching element will be updated) :type updateList: str diff --git a/eventman_server.py b/eventman_server.py index 28627b2..fa9f335 100755 --- a/eventman_server.py +++ b/eventman_server.py @@ -100,6 +100,26 @@ class CollectionHandler(BaseHandler): # set of documents we're managing (a collection in MongoDB or a table in a SQL database) collection = None + # set of documents used to store incremental sequences + counters_collection = 'counters' + + def get_next_seq(self, seq): + """Increment and return the new value of a ever-incrementing counter. + + :param seq: unique name of the sequence + :type seq: str + + :return: the next value of the sequence + :rtype: int + """ + if not self.db.query(self.counters_collection, {'seq_name': seq}): + self.db.add(self.counters_collection, {'seq_name': seq, 'seq': 0}) + merged, doc = self.db.update(self.counters_collection, + {'seq_name': seq}, + {'seq': 1}, + operation='increment') + return doc.get('seq', 0) + def _filter_results(self, results, params): """Filter a list using keys and values from a dictionary. @@ -329,6 +349,8 @@ class EventsHandler(CollectionHandler): def handle_post_persons(self, id_, person_id, data): # Add a person to the list of persons registered at this event. + data['seq'] = self.get_next_seq('event_%s_persons' % id_) + data['seq_hex'] = '%06X' % data['seq'] doc = self.db.query('events', {'_id': id_, 'persons.person_id': person_id}) if '_id' in data: