Beispiel #1
0
async def main_with():
    async with CouchDB("http://localhost:5984", user="******",
                       password="******") as couchdb:

        print((await couchdb.info())["version"])

        database = await couchdb["config"]

        async for doc in database.docs(["db-hta"]):
            print(doc)

    async with CouchDB("http://localhost:5984",
                       cookie="ZGVtb0B0b2x0ZWNrLmNvbT...") as couchdb:
        await couchdb["_users"]
Beispiel #2
0
async def main_with() -> None:

    # connect using username and password as credentials
    async with CouchDB("http://localhost:5984", user="******",
                       password="******") as couchdb:
        database = await couchdb["config"]

        async for doc in database.docs(["db-hta"]):
            print(doc)
    # connection is closed

    # connect using cookie
    async with CouchDB("http://localhost:5984",
                       cookie="ZGVtb0B0b2x0ZWNrLmNvbT...") as couchdb:
        await couchdb["_users"]
Beispiel #3
0
async def main_persistent() -> None:
    couchdb = CouchDB("http://localhost:5984", user="******", password="******")

    # optional credentials check
    await couchdb.check_credentials()

    # do something
    database = await couchdb["config"]
    async for doc in database.docs(["db-hta"]):
        print(doc)

    # close the connection without waiting
    asyncio.ensure_future(couchdb.close())

    return
    def __init__(
        self,
        token,
        management_url,
        couchdb_url,
        couchdb_user,
        couchdb_password,
        event_loop,
    ):
        super().__init__(
            token,
            management_url,
            event_loop=event_loop,
        )
        self.couchdb_client: CouchDB = CouchDB(
            couchdb_url,
            user=couchdb_user,
            password=couchdb_password,
            loop=self.event_loop,
        )

        self.couchdb_db_config: database.Database = None
        self.couchdb_db_metadata: database.Database = None

        self.user_session_manager = UserSessionManager()

        self._config_locks = {}
Beispiel #5
0
async def main_with():
    async with CouchDB(
        "http://localhost:5984", user="******", password="******"
    ) as couchdb:

        database = await couchdb["unfun"]

        # selector = {
        #     "_id": {
        #      "$regex": "^taurus\\.taurusi5172.*$"
        #     }
        # }
        #
        # async for doc in database.find(selector=selector):
        #     print(doc)

        # async for doc in database.docs():
        #     if doc.id.startswith("taurus.taurusi5172."):
        #         print(doc)

        # async for doc in database.docs(prefix="taurus.taurusi5172."):
        #     print(doc)

        async for key in database.all_docs().akeys(prefix="x"):
            print(key)

        print("------")

        async for key in database.view("view", "new-view").akeys(prefix="x"):
            print(key)
Beispiel #6
0
async def test_cookie_authentication(
        couchdb_with_user_access: CouchDB) -> None:
    import os

    import aiohttp

    from aiocouch import CouchDB

    try:
        hostname = os.environ["COUCHDB_HOST"]
    except KeyError:
        hostname = "http://localhost:5984"

    user = "******"

    # create a session cookie, which can be used later
    async with aiohttp.ClientSession() as session:
        async with session.post(
                f"{hostname}/_session",
                data={
                    "name": user,
                    "password": user
                },
        ) as resp:
            assert resp.status == 200
            await resp.json()
            cookie = resp.cookies["AuthSession"].value

    async with CouchDB(hostname, cookie=cookie) as couchdb:
        await couchdb.check_credentials()

        headers, response = await couchdb._server._get("/_session")
        assert not isinstance(response, bytes)
        assert user == response["userCtx"]["name"]
Beispiel #7
0
async def couchdb(event_loop: Any) -> AsyncGenerator[CouchDB, None]:
    import asyncio
    import os

    from aiocouch import CouchDB

    try:
        hostname = os.environ["COUCHDB_HOST"]
    except KeyError:
        hostname = "http://localhost:5984"

    user: Optional[str] = None

    with suppress(KeyError):
        user = os.environ["COUCHDB_USER"]

    try:
        password = os.environ["COUCHDB_PASS"]
    except KeyError:
        password = ""

    async with CouchDB(
        hostname, user=user, password=password, loop=event_loop
    ) as couchdb:
        yield couchdb

    # Give the couchdb server some time, so the assumptions of an empty database isn't
    # broken for subsequent tests. This delay used to be part of the disconnect
    # procedure, but #6 removed that. Therefore, we do sleep for the previous amount
    # here. This should give the server some time to delete the old fixtures.
    await asyncio.sleep(0.250)
Beispiel #8
0
async def main_with():
    async with CouchDB("http://localhost:5984", user="******",
                       password="******") as couchdb:

        database = await couchdb["config"]

        async for doc in database.docs(["db-hta"]):
            print(doc)
Beispiel #9
0
async def test_create_for_existing_ok_with_race(couchdb: CouchDB,
                                                database_id: str) -> None:
    try:
        # try to trigger a race-condition during the creation of the database
        await asyncio.gather(
            *[couchdb.create(database_id, exists_ok=True) for _ in range(5)])
    finally:
        # for this specific test, we need to do a manual cleanup
        db = await couchdb.create(database_id, exists_ok=True)
        await db.delete()
Beispiel #10
0
async def main_with() -> None:

    async with CouchDB(
        "http://localhost:5984", user="******", password="******"
    ) as couchdb:
        database = await couchdb["test"]

        async for event in database.changes(include_docs=True):
            if isinstance(event, DeletedEvent):
                print(f"The document {event.id} was deleted.")
            elif isinstance(event, ChangedEvent):
                print(f"The document {event.id} was saved as {event.rev}")
Beispiel #11
0
async def main_with():
    async with CouchDB("http://localhost:5984", user="******",
                       password="******") as couchdb:
        db = await couchdb["recipes"]
        doc = await db["apple_pie"]
        print(doc["incredients"])

        new_doc = await db.create("cookies",
                                  data={
                                      "title": "Grandma's cookies",
                                      "rating": "★★★★★"
                                  })
        await new_doc.save()
Beispiel #12
0
async def main():
    async with CouchDB("http://localhost:5984", user="******",
                       password="******") as couchdb:

        elapsed_time = 0

        while True:
            result = await couchdb._server._get("/_session")
            user = result["userCtx"]["name"]
            print(f"After {elapsed_time} sec: {user}")

            await asyncio.sleep(10)
            elapsed_time += 10
Beispiel #13
0
async def couchdb_with_user_access(couchdb_user_account):
    from aiocouch import CouchDB
    import os

    try:
        hostname = os.environ["COUCHDB_HOST"]
    except KeyError:
        hostname = "http://localhost:5984"

    async with CouchDB(hostname,
                       user="******",
                       password="******") as couchdb:
        yield couchdb
Beispiel #14
0
async def test_with_wrong_credentials() -> None:
    import os

    from aiocouch import CouchDB, UnauthorizedError

    try:
        hostname = os.environ["COUCHDB_HOST"]
    except KeyError:
        hostname = "http://localhost:5984"

    with pytest.raises(UnauthorizedError):
        async with CouchDB(
                hostname,
                user="******",
                password=
                "******",
        ) as couchdb:
            await couchdb["does_not_exist"]
Beispiel #15
0
async def test_basic_authentication() -> None:
    import os

    from aiocouch import CouchDB

    try:
        hostname = os.environ["COUCHDB_HOST"]
    except KeyError:
        hostname = "http://localhost:5984"

    user: Optional[str] = None
    with suppress(KeyError):
        user = os.environ["COUCHDB_USER"]

    try:
        password = os.environ["COUCHDB_PASS"]
    except KeyError:
        password = ""

    async with CouchDB(hostname, user=user, password=password) as couchdb:
        await couchdb.check_credentials()
Beispiel #16
0
async def test_basic_authentication(event_loop):
    from aiocouch import CouchDB
    import os

    try:
        hostname = os.environ["COUCHDB_HOST"]
    except KeyError:
        hostname = "http://localhost:5984"

    try:
        user = os.environ["COUCHDB_USER"]
    except KeyError:
        user = None

    try:
        password = os.environ["COUCHDB_PASS"]
    except KeyError:
        password = ""

    async with CouchDB(hostname, user=user, password=password) as couchdb:
        await couchdb.check_credentials()
Beispiel #17
0
async def couchdb():
    from aiocouch import CouchDB
    import os

    try:
        hostname = os.environ["COUCHDB_HOST"]
    except KeyError:
        hostname = "http://localhost:5984"

    try:
        user = os.environ["COUCHDB_USER"]
    except KeyError:
        user = None

    try:
        password = os.environ["COUCHDB_PASS"]
    except KeyError:
        password = ""

    async with CouchDB(hostname, user=user, password=password) as couchdb:
        yield couchdb
Beispiel #18
0
 async def setup(self):
     self.couch = CouchDB(self.app.config.couch_url,
                          user=self.app.config.couch_username,
                          password=self.app.config.couch_password)
     await self.couch.check_credentials()
     await self.prepare_databases()