Esempio n. 1
0
def main():
    yt_resource = build('youtube', 'v3', developerKey=config['api_key'])
    print_info(
        f"If you want to ignore some files, add name of those files in {config['exceptions_file']}"
        f" in the same folder in which files to be renamed are present.")
    files = ls()
    exceptions = get_exceptions()

    cache = CacheManager(config)
    if cache.is_local_playlist_cache_available():
        playlist_id = get_playlist_id_from_cache(cache)
        if playlist_id is None:
            playlist_id = get_playlist_id_from_youtube(cache, yt_resource)
    else:
        playlist_id = get_playlist_id_from_youtube(cache, yt_resource)

    playlist = YTPlaylist(yt_resource, playlist_id)
    playlist.fetch_videos()
    playlist.print_videos()
    remote_serial_dict = playlist.get_videos_serial()

    print()

    renaming_helper = RenamingHelper(
        remote_serial_dict,
        files,
        exceptions,
        character_after_serial=config['character_after_serial'])
    rename(renaming_helper, cache)
    def test_get_missing_key(self):
        "Expected to throw"

        cache = CacheManager()

        with raises(ReferenceError):
            cache.get(key=None)
    def test_set_missing_key(self):
        "Expected to throw"

        cache = CacheManager()

        with raises(ReferenceError):
            cache.set(key=None, value='value', expiration=1)
    def test_set_has_value(self):
        "Expected to find the required value"

        cache = CacheManager()

        cache.set(key='key', value='value', expiration=1)

        assert cache.get('key') == 'value'
    def test_set_missing_value(self):
        "Expected to set an empty key"

        cache = CacheManager()

        cache.set(key='key', value=None, expiration=1)

        assert not cache.get('key')
    def test_get_existent_key(self):
        "Expected to return None"

        cache = CacheManager()
        key = 'key'
        value = 'value'

        cache.set(key, value)

        assert cache.get(key) == value
Esempio n. 7
0
async def main():
    cache_manager = CacheManager()
    truly_awesome_bank_API_client = TrulyAwesomeBankAPIClient()
    resource_manager = ResourceManager(cache_manager,
                                       truly_awesome_bank_API_client)

    transaction = {'type': 'PAYMENT', 'amount': 100, 'currency': 'EUR'}

    print('=======================')
    print('|    WRITE THROUGH    |')
    print('=======================')

    print('>>> Save transaction')
    entry = await resource_manager.save_with_write_through(transaction)
    print('>>> Get transaction')
    await resource_manager.fetch_transaction_by_id(entry['id'])

    print('=======================')
    print('|    WRITE BEHIND     |')
    print('=======================')

    print('>>> Save transaction')
    entry = await resource_manager.save_with_write_behind(transaction)
    print('>>> Get transaction')
    await resource_manager.fetch_transaction_by_id(entry['id'])

    print('')
    print('--------------------------------------------')
    print('|    AWESOME BANK DATABASE (before sync)   |')
    print('--------------------------------------------')
    print(truly_awesome_bank_API_client._TrulyAwesomeBankAPIClient__database)
    print('')

    # wait for synchronization
    await asyncio.sleep(10)

    print('')
    print('--------------------------------------------')
    print('|    AWESOME BANK DATABASE (after sync)    |')
    print('--------------------------------------------')
    print(truly_awesome_bank_API_client._TrulyAwesomeBankAPIClient__database)
    print('')
Esempio n. 8
0
    def __init__(self):
        """
        Init method.
        """

        # class variables
        self._as = None  # SimpleActionServer variable
        self._goal = ""  # Goal a recibir
        self._goal_exec = False  # Indicates if goal is being handled
        self._pause = False  # Indicates if pause
        self._step = 'init'  # Init, rss_reader, show_info
        self._out = False  # Varable to exit the while

        # Goal varaibles
        self._max_time = 0
        self._number_plays = 0
        self._t0 = 0
        self._t1 = 0
        self._time_run = 0
        self._i_plays = 0

        # Local paths
        rospack = rospkg.RosPack()
        self._root_path = rospack.get_path(pkg_name)  # Package path
        self._data_path = self._root_path + '/data/'  # Data path
        self._news_cache = self._data_path + 'news_cache.txt'  # Cache file
        # Tablet paths
        self._default_path = '/default.png'  # Default image

        # Rss objects
        self._feed_name = 'tu_tiempo'
        self._category_name = 'cover_page'
        #self._rss_feed = self.feeds[self._feed_name][self._category_name] # Feed url

        # Cache object
        self._cache_manager = CacheManager(self._data_path)

        # init the skill
        Skill.__init__(self, skill_name, CONDITIONAL)
Esempio n. 9
0
def main():
    setting = SettingManager()
    args = parser.parse_args()
    if args.dry:
        environ['DRY'] = 'True'
    if args.once:
        __once(setting.users[0], setting.common, args.once)
        return
    cache = CacheManager()
    user_count = len(setting.users)
    if user_count > 1:
        with ThreadPoolExecutor(user_count) as executor:
            futures = []
            try:
                for user in setting.users:
                    futures.append(
                        executor.submit(__parallel_process, user,
                                        setting.common, args.start, cache))
                executor.shutdown()
            except KeyboardInterrupt:
                LOGGER.warning('shutdown')
    else:
        __parallel_process(setting.users[0], setting.common, args.start, cache)
Esempio n. 10
0
		time_milliseconds = time + "{0:03.0f}".format(now.microsecond / 1000)
		return u"{}: {}".format(time_milliseconds, msg)

	def info(self, msg, *args, **kwargs):
		self.logger.info(self.prefix(msg), *args, **kwargs)

	def warn(self, msg, *args, **kwargs):
		self.logger.warn(self.prefix(msg), *args, **kwargs)

	def error(self, msg, *args, **kwargs):
		self.logger.error(self.prefix(msg), *args, **kwargs)
	def debug(self, msg, *args, **kwargs):
		self.logger.debug(self.prefix(msg), *args, **kwargs)

eventLogger = eventLogger('event_consumer_log.log')
cache_client = CacheManager()

def add_item_mylist(item_id, item_value):
		"""Add item to mylist
		"""
		shopping_list = "mylist"
		print("Add item to the list:", item_value)
		eventLogger.info("Adding item: {} to the:{}".format(item_value, shopping_list))
		key = "{}:{}:{}".format(device_id, shopping_list, item_id)
		cache_client.set_value(key, str(item_value))

def remove_item(item_id):
		"""Remove item to mylist
		"""
		shopping_list = "mylist"
		print("Remove item to the list:", item_id)
Esempio n. 11
0
# settings
input_file_name = 'read.html'
cache_dir_name = 'cache'
out_file_name = 'out.csv'
min_delay = 90
max_delay = 120

print('Load books from file: "%s"' % input_file_name)
read_parser = ReadParser()
if read_parser.load_from_file(input_file_name) is False:
    exit(1)
print('Books loaded.')

print('Parse books from summary.')
books = read_parser.parse_books()
print('Books parsed: %s.' % len(books))

print('Start download detailed book pages.')
cache = CacheManager(cache_dir_name)
loader = PageLoader(cache, min_delay, max_delay)
loader.download(books)
print('Detailed book pages downloaded.')

print('Prepare books for export.')
details_parser = DetailsParser(cache)
ready_books = details_parser.parse(books)
print('Books ready to export: %s.' % len(ready_books))

writer = CsvWriter()
writer.save(ready_books, out_file_name)
print('Books saved to "%s"' % out_file_name)
    def test_get_non_existent_key(self):
        "Expected to return None"

        cache = CacheManager()

        assert not cache.get('idonotexist')
Esempio n. 13
0
 def run(self):
     self.cacheManager = CacheManager(self.cfg.cache_manager)
     self.main()
Esempio n. 14
0
 def setUp(self):
     self.cache_manager = CacheManager()
Esempio n. 15
0
sys.path.append(os.path.abspath(os.path.join('..', '')))

from db_manager import master_list
from cache_manager import CacheManager
from config import device_id

formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.basicConfig(level=logging.INFO)
handler = logging.FileHandler('webapp_log.log')
handler.setFormatter(formatter)
logger = logging.getLogger(__name__)
logger.addHandler(handler)

app = Flask(__name__, static_folder="./static", template_folder="./static")
ch = CacheManager()


@app.route("/list")
def get_list():
    return "Master List:{}".format(master_list)
    #return render_template("index.html")


@app.route("/ping")
def hello():
    return "PONG"


@app.route("/mylist", methods=["GET"])
def get_my_list():
Esempio n. 16
0
import random
import string
from random import randint

from event_producer import EventProducer
from cache_manager import CacheManager

if __name__ == "__main__":
	publisher = EventProducer()
	publisher.connect()
	#Pushing random items
	item_name = "item" + str(randint(0, 9999999999))
	publisher.publish_event("list/mylist", item_name)

	print("Data in cache")
	cache = CacheManager()
	cache.print_data("mylist")