Пример #1
0
 async def coro():
     async with AIOTinyDB(self.file.name) as db:
         db.insert(dict(name='yay'))
         self.assertEqual(len(db), 1)
         db.purge()
         self.assertEqual(len(db), 0)
         tst = 'abc'
         db.insert_multiple({'int': 1, 'char': c} for c in tst)
         for c, v in zip(tst, db):
             self.assertEqual(c, v['char'])
         db.update({'int': 2}, where('int') == 1)
         self.assertEqual(len(db.search(where('int') == 2)), 3)
     async with AIOTinyDB(self.file.name,
                          storage=AIOImmutableJSONStorage) as db:
         self.assertEqual(len(db.search(where('int') == 2)), 3)
         self.assertEqual(db.tables(), {AIOTinyDB.DEFAULT_TABLE})
Пример #2
0
async def process_card(session, card, cards_data, q):
    try:
        event = q.get_nowait()
        print("EVENT IN THREAD", event)
        if type(event) == SystemExit:
            sys.exit(0)
    except Empty:
        pass

    res = await get_balance(session, card)  # type: dict
    if res and not res.get("type") == "error":
        old_balance = list(filter(lambda x: x.get("card") == card,
                                  cards_data))[0]
        logging.debug(old_balance)
        if res["balance"] != old_balance['balance']:
            q.put_nowait({
                "type": BALANCE_UPDATE,
                "new_balance": res,
                "old_balance": old_balance,
                "change": expense_change(old_balance, res),
                "card": card,
            })

        async with AIOTinyDB(CARDS_DB) as db:
            db.upsert(res, Query().card == card)
        return res
Пример #3
0
 async def coro():
     async with AIOTinyDB(self.file.name) as db:
         db.insert(dict(index='default'))
         db.table('alt').insert(dict(index='alt'))
         self.assertEqual(len(db.tables()), 2)
         self.assertEqual(len(db), 1)
         self.assertEqual(len(db.table()), 1)
         self.assertEqual(len(db.table('alt')), 1)
Пример #4
0
 async def test():
     middleware = AIOVanillaMiddleware(AIOJSONStorage)
     async with AIOTinyDB(self.file.name, storage=middleware):
         tst = 'abc'
         db.insert_multiple({'int': 1, 'char': c} for c in tst)
     self.assertGreaterEqual(read_from, 1)
     self.assertGreaterEqual(written_to, 1)
     self.assertTrue(closed)
Пример #5
0
async def ls_faq() -> str:
    """
    !lsfaq

    :return: A list of all available FAQ topics
    """
    async with AIOTinyDB(bot.tinydb_path) as db:
        return f"Available FAQ topics: {', '.join(x['topic'] for x in db.table('faq').all())}"
Пример #6
0
async def del_faq(topic: str) -> str:
    """
    !delfaq <topic>
    Deletes a FAQ topic from tinydb, if it exists.

    :param topic: the name of the topic to delete
    :return: a success message
    """
    async with AIOTinyDB(bot.tinydb_path) as db:
        db.table("faq").remove(where("topic") == topic)
    return f"FAQ topic '{topic}' deleted!"
Пример #7
0
async def faq(topic: str) -> str:
    """
    !faq <topic>

    :param topic: FAQ topic name. Will get it from FokaBot's tinydb
    :return: the topic content, if it exists, or an error message
    """
    async with AIOTinyDB(bot.tinydb_path) as db:
        results = db.table("faq").search(where("topic") == topic)
        if results:
            return results[0]["response"]
        else:
            return "No such FAQ topic."
Пример #8
0
async def mod_faq(topic: str, new_response: str) -> str:
    """
    !modfaq <topic> <new_response>
    Edits an existing topic in tinydb. Doesn't do anything if the specified topic does not exist.

    :param topic: the name of the FAQ topic to edit
    :param new_response: the new response
    :return: success message
    """
    async with AIOTinyDB(bot.tinydb_path) as db:
        db.table("faq").upsert({
            "topic": topic,
            "response": new_response
        },
                               where("topic") == topic)
    return f"FAQ topic '{topic}' updated!"
Пример #9
0
async def check_cards_balance(q):
    async with aiohttp.ClientSession() as session:
        while q.run:
            async with AIOTinyDB(CARDS_DB) as db:
                dat = db.all()

            tasks = [
                asyncio.ensure_future(
                    process_card(session, card['card'], dat, q))
                for card in dat
            ]
            res = await asyncio.gather(*tasks)
            logging.debug(res)

            if not q.run:
                break
            await asyncio.sleep(SLEEP_TIME)
Пример #10
0
 def test_uninitialized_state(self):
     db = AIOTinyDB(self.file.name)
     for meth, args in (('purge_table', ('yay', )), ('purge_tables',
                                                     tuple()),
                        ('table', tuple()), ('tables', tuple())):
         with self.assertRaises(DatabaseNotReady):
             getattr(db, meth)(*args)
     for meth in ('insert', 'update', 'search'):
         with self.assertRaises(AttributeError):
             getattr(db, meth)
     with self.assertRaises(NotOverridableError):
         with db:
             pass
     with self.assertRaises(NotOverridableError):
         db.__exit__(None, None, None)
     with self.assertRaises(NotOverridableError):
         db.close()
Пример #11
0
 def censored_words_db(self) -> AIOTinyDB:
     return AIOTinyDB(self.db_file,
                      storage=CachingMiddleware(AIOJSONStorage))
Пример #12
0
 async def coro():
     db = AIOTinyDB(self.file.name, storage=AIOImmutableJSONStorage)
     with self.assertRaises(ReadonlyStorageError):
         async with db:
             pass
Пример #13
0
 async def coro():
     db = AIOTinyDB(self.file.name)
     async with db:
         db.insert(dict(index='as'))
         self.assertEqual(len(db.tables()), 1)
         db.purge_table(AIOTinyDB.DEFAULT_TABLE)
         self.assertEqual(len(db.tables()), 0)
     async with db:
         db.insert(dict(index='as'))
         self.assertEqual(len(db.tables()), 1)
         db.purge_tables()
         self.assertEqual(len(db.tables()), 0)
Пример #14
0
 async def test():
     for middleware_cls in (AIOMiddleware, CachingMiddleware):
         async with AIOTinyDB(self.file.name, storage=middleware_cls(AIOJSONStorage)):
             pass
Пример #15
0
import asyncio
import aiohttp
import aioredis
from tinydb import where
from aiotinydb import AIOTinyDB

loop = asyncio.get_event_loop()

pool = aioredis.create_pool(
        'redis://localhost',
        minsize=1, maxsize=2,
        loop = loop
)

db = AIOTinyDB(DB_NAME)

activity = discord.Activity(type=discord.ActivityType.watching, name=ACTIVITY_NAME)
bot = commands.Bot(command_prefix='*')
bot.remove_command("help")

# Wrapper for aiohttp POST
async def post(js_data):
    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(NODE_RPC_URL, json=js_data) as response:
                return await response.json()
        except Exception as e:
            print(f"Error trying to POST {js_data}: {e}")
            return None
Пример #16
0
 def __init__(self, app: ASGIApp, database_url: DatabaseURL) -> None:
     self.app = app
     self.database = AIOTinyDB(database_url.hostname + database_url.path)