class BaseVedisTestCase(unittest.TestCase): def setUp(self): super(BaseVedisTestCase, self).setUp() self.db = Vedis(':memory:') def tearDown(self): self.db.close() super(BaseVedisTestCase, self).tearDown() def set_k1_k2(self): # Short-hand for setting two keys. self.db['k1'] = 'v1' self.db['k2'] = 'v2'
class TestTransaction(BaseVedisTestCase): def setUp(self): self.db = Vedis('test.db') def tearDown(self): try: self.db.close() finally: if os.path.exists('test.db'): os.unlink('test.db') def test_transaction(self): self.db['k1'] = 'v1' @self.db.commit_on_success def succeed(): self.db['k2'] = 'v2' @self.db.commit_on_success def fail(): self.db['k3'] = 'v3' raise Exception('uh-oh') succeed() self.assertEqual(self.db['k2'], b'v2') self.assertRaises(Exception, fail) self.assertFalse(self.db.exists('k3')) def test_base_transaction_methods(self): self.db.begin() self.db['k1'] = 'v1' self.db.rollback() self.assertFalse(self.db.exists('k1'))
def set_state(user_id, value): with Vedis(config.db_file) as db: try: db[user_id] = value return True except: print('takogo usera net') return False
def set_state(user_id, state): with Vedis(config.db_users_state_file) as db: try: db[user_id] = state return True except: print('set_state_Error') return False
def save_request(user_id, message_id, films): with Vedis(States.db_search) as db: try: key = str(user_id) + str(message_id) db[key] = films return True except KeyError: print("KeyError. There is no user_id-message_id combination")
def set_state(user_id, value): with Vedis(config.db_file) as db: try: db[user_id] = value return True except Exception: # Обработка ситуации return False
def set_state(user_id, value): with Vedis(States.db_state) as db: try: db[user_id] = value return True except KeyError: print("KeyError. There is no user ", user_id, ", doing nothing") return False
def set_state(user_id, value): with Vedis(bot_conf.db_file) as db: try: db[user_id] = value return True except: print("Error1") return False
def get_current_state(user_id): with Vedis(config.db_file) as db: try: state = db[user_id] return state except KeyError: # Если такого ключа почему-то не оказалось return config.States.S_START.value # значение по умолчанию - начало диалога
def set_state(user_id, value): with Vedis(config.db_file) as db: try: db[user_id] = value return True except: # тут желательно как-то обработать ситуацию return False
def get(self, key, default_value=None): with Vedis(self.file_name) as database: try: return database[key].decode('utf-8') except KeyError: if default_value is not None: return default_value else: raise
def save_page(user_id, message_id, page): with Vedis(States.db_page) as db: try: key = str(user_id) + str(message_id) db[key] = str(page) print("Saved page with key: " + key) return True except KeyError: print("KeyError in save_page. There is no user_id-message_id combination: " + key)
def set_more_info(telegram_id, more_info): with Vedis( os.path.join(base_dir, os.path.join(base_dir, 'accounts_info.vdb'))) as db: try: account = db.Hash(telegram_id) account['more_info'] = more_info except Exception as err: print(err)
def get_current_state(user_id): """ get current condition of the bot """ with Vedis(config.db_file) as db: try: return db[user_id].decode() except KeyError: return config.States.START.value
def get_param(uid, param): with Vedis(config.db_file) as db: usr_dict = eval(db[uid].decode()) value = usr_dict.get(param) try: value = int(value) except ValueError: pass return value
def set_hash_timezone(user_id, value): with Vedis(config.db_status) as db: h = db.Hash(str(user_id)) try: h['timezone'] = value return True except: # тут желательно как-то обработать ситуацию return False
def get_current_state(user_id): """ Получаем "состояние" пользователя """ with Vedis(config.db_file) as db: try: return db[user_id].decode( ) # если используется Vedis версии ниже, чем 0.7.1, то .decode() НЕ НУЖЕН except KeyError: # если такого ключа почему-то не оказалось return config.States.S_BEFORE_START.value
class bulb: def __init__(self): self.path_base = '/usr/local/bin/' self.base = self.path_base + 'bulb' self.dimm_base = self.path_base + 'dimm_bulb' self.ved = Vedis('store.ved') def __del__(self): self.ved.close() def run(self, arg): call(['sudo', self.base, arg]) def dimm(self, level, inc): Popen(['sudo', self.dimm_base, '-l ' + str(level), '-i ' + str(inc)]) def undimm(self, level, inc): Popen(['sudo', self.dimm_base, '-l ' + str(level), '-i ' + str(inc), '-r'])
def get_current_state(user_id): with Vedis(db_file) as db: try: db_userId = db[user_id] db_userId = str(db_userId, 'utf-8') print(type(db_userId)) return db_userId except KeyError: return States.S_START.value
def set_state(user_id, value, social_network = 'inst'): with Vedis(sconfig.last_posts) as db: try: key = f'{social_network}_{user_id}' db[key] = value return True except: print('Проснись, ты обосрался!') # Помянем Санька return False
def set_state(user_id, value): """ Сохраняем текущее "состояние" пользователя в базу """ with Vedis(config.db_file) as db: try: db[user_id] = value return True except: return False
def set_state(user_id, value): """ Save the current condition """ with Vedis(config.db_file) as db: try: db[user_id] = value return True except: return False
def return_all_translations(name): with Vedis(os.path.join(base_dir, 'localization.vdb')) as db: try: answer = [] position = db.Hash(name) for each in position.values(): answer.append(each.decode('UTF-8')) return answer except Exception as err: print(err)
def set_hash_city(user_id, value): with Vedis(config.db_status) as db: h = db.Hash(str(user_id)) try: city = value.title() h['city'] = city return True except: # тут желательно как-то обработать ситуацию return False
class StorageBackendVedis(StorageBackend): __backend_name__ = 'vedis' def __init__(self, **kwargs): if kwargs is None or kwargs.get('database_path') is None: raise Exception("Vedis backend requires path argument") self.database_path = kwargs.get('database_path') self.db = Vedis(self.database_path) def store(self, key, field, value): if not all(map(lambda x: isinstance(x, str), [key, field, value])): raise Exception('key, field, value must be string') _hash = self.db.Hash(key) _hash[field] = value return True def load(self, key, field): if not all(map(lambda x: isinstance(x, str), [key, field])): raise Exception('key, field must be string') _hash = self.db.Hash(key) return _hash[field] def delete(self, key, field): if not all(map(lambda x: isinstance(x, str), [key, field])): raise Exception('key, field must be string') _hash = self.db.Hash(key) del _hash[field] return True def cleanup(self, key): if not isinstance(key, str): raise Exception('key must be string') _hash = self.db.Hash(key) try: for _hkey in _hash: del _hash[_hkey] except: pass
def set_data(key, value): """ Запис нових даних в базу. """ with Vedis(config.db_file) as db: try: db[key] = value return True except: # тут бажано обробити ситуацію return False
def set_state(user_id, value, social_network='inst'): with Vedis(sconfig.last_posts) as db: try: key = f'{social_network}_{user_id}' db[key] = str(value) print(f"add: key = {key}, value = {str(value)}") return True except: print('Проснись, ты обосрался!') # Помянем Санька print(key, str(value)) return False
def get_current_state(user_id, social_network='inst'): with Vedis(sconfig.last_posts) as db: try: key = f'{social_network}_{user_id}' value = int(db[key].decode()) print(f"get: key = {key}, value = {str(value)}") return value except KeyError: value = 1368674341 print(f"get: key = {key}, value = {value}") return value
def get_current_state(user_id): """ Пытаемся узнать из базы состояний "состояние" пользователя """ with Vedis(config.db_states) as db: try: state = db[user_id].decode() except KeyError: # если такого ключа не оказалось # берём значение по умолчанию state = config.States.START_ENTER.value return state
def reset_user(uid): with Vedis(config.db_file) as db: db[uid] = str({}) for mf in [ '%s-df_filtered_week.csv' % str(uid), '%s-df_filtered_tmpr.csv' % str(uid), '%s-df_filtered_final.csv' % str(uid), '%s-map.png' % str(uid) ]: if os.path.exists(mf): os.remove(mf)
def set_state(user_id, value): """ Записываем в базу состояний для пользователя user_id состояние value #TODO Написать обработку исключений """ with Vedis(config.DATABASE_STATE) as db: try: db[user_id] = value return True except Exception: return False
def get_data(key): """ Отримання даних з бази. """ with Vedis(config.db_file) as db: try: return db[key].decode( ) # Якщо використовуєтьcя Vedis версії нижче, ніж 0.7.1, то .decode() НЕ ПОТРІБЕН except KeyError: # Якщо такого ключа не виявилось # return config.States.S_START.value # значення по замовчуванню - початок діалогу return False
def get_users(): with Vedis(private_constants.db_users) as db: try: users = ast.literal_eval(db['USERS'].decode('utf-8')) return users except (KeyError, OSError) as e: func_name = _getframe().f_code.co_name print( f'{e.__class__.__name__} while running "{func_name}" with args: {e.args}' ) return None
def __init__(self, filename=':mem:'): self._filename = filename Vedis.__init__(self, filename)
def setUp(self): self.db = Vedis('test.db')
def setUp(self): super(BaseVedisTestCase, self).setUp() self.db = Vedis(':memory:')
def __init__(self): self.path_base = '/usr/local/bin/' self.base = self.path_base + 'bulb' self.dimm_base = self.path_base + 'dimm_bulb' self.ved = Vedis('store.ved')
def __init__(self, filename=":mem:"): self._filename = filename Vedis.__init__(self, filename)