Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This Python file uses the following encoding: utf-8
- from PySide6.QtWidgets import QApplication, QWidget, QSpinBox, QLabel, QPushButton, QVBoxLayout
- import pickle
- import redis
- import sys
- class RedisMemoizator:
- def __init__(self, host: str, port, user: str, password: str):
- self.__connection = redis.StrictRedis(host=host, username=user, password=password, decode_responses=False)
- def __call__(self, function):
- def memoize(*args, **kwargs):
- print(f'Сalling {function.__name__}() with {args}, {kwargs}')
- try:
- print(f'\tTry get value: {self._create_key(function, *args, **kwargs)}')
- return self._get_memoized_value(function, *args, **kwargs)
- except Exception as error:
- print(f'\tCall function because: {error}')
- return self._set_memoized_value(function(*args, **kwargs), function, *args, **kwargs)
- return memoize
- def _create_key(self, function, *args, **kwargs):
- return f'{function.__name__}|{args}|{kwargs}'
- def _get_memoized_value(self, function, *args, **kwargs):
- print(f'Load value: [{self._create_key(function, *args, **kwargs)}]')
- if not self.__connection.exists(self._create_key(function, *args, **kwargs)):
- raise Exception('Has no key in redis')
- return pickle.loads(self.__connection.get(self._create_key(function, *args, **kwargs)))
- def _set_memoized_value(self, result, function, *args, **kwargs):
- print(f'Save value: [{self._create_key(function, *args, **kwargs)}|{result}]')
- self.__connection.set(self._create_key(function, *args, **kwargs), pickle.dumps(result))
- return result
- @RedisMemoizator(host='178.208.86.244', port=6379, user='', password='')
- def fibonacci(number: int) ->int:
- print(f'Calculate fibonacci for number [{number}]')
- if number <= 1:
- return 1
- return fibonacci(number - 1) + fibonacci(number - 2)
- if __name__ == '__main__':
- app = QApplication(sys.argv)
- input_value = QSpinBox()
- input_value.setRange(0, 200)
- result_value = QLabel('--')
- calculate_button = QPushButton('Calculate')
- calculate_button.clicked.connect(lambda: result_value.setText(str(fibonacci(input_value.value()))))
- window = QWidget()
- layout = QVBoxLayout()
- window.setLayout(layout)
- layout.addWidget(input_value)
- layout.addWidget(calculate_button)
- layout.addWidget(result_value)
- window.show()
- sys.exit(app.exec())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement