def get_state_from_db(self): """ This function loads states of users from db. It"s triggered when the class is initialized. :return: nothing """ connection = db.get_connection() try: with connection.cursor() as cursor: cursor.execute('SELECT user_id, state FROM users;') states = cursor.fetchall() self.cache_state = {state[0]: state[1] for state in states} finally: connection.close()
def set_state_to_db(self): """ This function updates the states of users in the database :return: nothing """ connection = db.get_connection() try: with connection.cursor() as cursor: for user, state in self.cache_state.items(): cursor.execute( 'UPDATE users SET state = %s WHERE user_id = %s;', (state, user)) connection.commit() except Exception as error: db.logger.warning(error.with_traceback(None), 'Error from cache module - set_state_to_db!') finally: connection.close()
def get_state(self, user_id): """ This function gets a user state by user id. If a user state isn't in the cache that's checking in db :param user_id: unique id of a users :return: a state of user """ try: return self.cache_state[user_id] except KeyError: connection = db.get_connection() try: with connection.cursor() as cursor: cursor.execute( 'SELECT state FROM users WHERE user_id = %s;', (user_id, )) new_state = cursor.fetchone()[0] self.cache_state.update({user_id: new_state}) return new_state except TypeError as type_error: db.logger.warning(type_error.with_traceback(None), 'Error from cache module - get_state!') return False finally: connection.close()
""" Copyright 2005-2018 QuantumRocket. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. General purpose database utility functions. """ import lib.log as log import sql.db as db import ulid con = db.get_connection() def get_user_id_by_widget_id(widget_id): """ Return the user_id of a widget, retrieved by its widget ulid. """ try: widget = find_by_id(widget_id) if widget is None: return None return widget['user_id'] except Exception as e: