From 91602af71250c21ba3656c662af6f85e9c4cf667 Mon Sep 17 00:00:00 2001 From: Tom Hunger Date: Mon, 26 Jan 2015 17:39:10 +0000 Subject: [PATCH] Use dict-as-argument trick to store global data for next command id. --- sirius/protocol/protocol_loop.py | 16 ++++++++-------- sirius/web/printer_print.py | 4 +++- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/sirius/protocol/protocol_loop.py b/sirius/protocol/protocol_loop.py index 8c5fd62..8037a07 100644 --- a/sirius/protocol/protocol_loop.py +++ b/sirius/protocol/protocol_loop.py @@ -34,8 +34,6 @@ last_seen_by_address = dict() PrinterDevice = collections.namedtuple( 'PrinterDevice', 'address last_heartbeat_timestamp') -next_command_id = None - class BridgeState(object): "Ephemeral state of a bridge. Lives as long as the websocket." @@ -48,19 +46,21 @@ class BridgeState(object): self.connected_devices = set() -def _get_next_command_id(): - """ +def _get_next_command_id(local_data={}): + """Return the next usable command id. Initialized lazily from the + database. + :returns: An int that can be used as the next command id. """ # Lazy-initialize global next_command_id - global next_command_id - if next_command_id is None: + if 'next_command_id' not in local_data: # NB 0 is an invalid command id (AKA file-id) so we start at # whatever the latest message id is to avoid collisions. next_command_id = model_messages.Message.get_next_command_id() logger.info("Initialized next_command_id as %s", next_command_id) - next_command_id += 1 - return next_command_id + local_data['next_command_id'] = next_command_id + local_data['next_command_id'] += 1 + return local_data['next_command_id'] def send_message(device_address, message): diff --git a/sirius/web/printer_print.py b/sirius/web/printer_print.py index 56e4d21..942c2ad 100644 --- a/sirius/web/printer_print.py +++ b/sirius/web/printer_print.py @@ -78,13 +78,15 @@ def printer_print(user_id, username, printer_id): 'error') stats.inc('printer.print.offline') - # Store the same message in the model. + # Store the same message in the database. model_message = model_messages.Message( print_id=next_print_id, pixels=bytearray(pixels), sender_id=login.current_user.id, target_printer=printer, ) + + # We know immediately if the printer wasn't online. if not success: model_message.failure_message = 'Printer offline' model_message.response_timestamp = datetime.datetime.utcnow() -- 2.47.3