Exemplo n.º 1
0
@default_formatter.register("human")
def _human(value, upper=False):
    res = ""
    for char in value:
        if res:
            res += "-"
        res += INT_TO_STR_MAP.get(char)
    if upper:
        return res.upper()
    return res


# cache.setup("disk://?directory=/tmp/cache")
# cache.setup("mem://")
cache.setup("redis://?max_connections=5")


# @profile(precision=4)
@cache.failover(ttl=timedelta(minutes=20), key="mul:{a:human}:hit")
@cache.failover(ttl=timedelta(minutes=1), key="mul2:{a:hash}:hit")
# @cache(ttl=timedelta(minutes=20), key="mul:{a:human(true)}")
# @cache.hit(ttl=timedelta(minutes=20), key="mul:{a:human(true)}:hit", cache_hits=1000, update_after=900)
# @cache.hit(ttl=timedelta(minutes=20), key="mul:{a}:hit", cache_hits=1000, update_after=900)
# @cache.early(ttl=timedelta(minutes=20), key="mul:{a}:hit", early_ttl=timedelta(minutes=5))
# @cache.locked(ttl=timedelta(minutes=20), key="mul:{a:human(true)}:hit")
async def example(a):
    return {"1": "2"}


async def main():
Exemplo n.º 2
0
    async def test(key):
        return await cache.incr(key), Decimal(10), b"d"

    detect = CacheDetect()
    assert not detect.keys
    print(await cache.incr("key"), "== 1")
    print(await test("key", _from_cache=detect), "== 2")
    await asyncio.sleep(0)
    print(detect.keys)
    print(await test("key", _from_cache=detect), "== 2")
    print(detect.keys)
    # return
    async with cache.lock("lock", expire=10):
        await cache.clear()
        await cache.set("key", value={"any": True}, expire=timedelta(minutes=1))  # -> bool
        await cache.get("key")  # -> Any
        await cache.incr("inr_key")  # -> int
        await cache.expire("key", timeout=timedelta(hours=10))
        await cache.delete("key")
        print(await cache.ping())  # -> bytes

    await cache.set_lock("key", value="value", expire=60)  # -> bool
    print(await cache.is_locked("key", wait=10, step=1))  # -> bool
    await cache.unlock("key", "value")  # -> bool


if __name__ == "__main__":
    # cache.setup("mem://", hooks=[prefix])
    cache.setup("redis://0.0.0.0/0?hash_key=s3243fedg", middlewares=(add_prefix("test:"),))
    asyncio.run(main(cache))
Exemplo n.º 3
0
import asyncio
import uuid

from cashews import cache

capacity = 1000
expect_false_positive = 1
fill_elements = 1000
test_n = 100

call_count = 0

cache.setup("redis://")


@cache.dual_bloom(name="test:{key}", capacity=capacity, false=expect_false_positive, no_collisions=False)
# @cache.bloom(capacity=capacity, false_positives=expect_false_positive)
# @cache.bloom(name="lower:{key}", capacity=capacity, false_positives=expect_false_positive)
async def _simple_bloom(key):
    await asyncio.sleep(0)
    global call_count
    call_count += 1
    return str(key)[0] not in ("c", "a", "b", "d", "e", "f")


async def main():
    await cache.clear()
    global call_count
    all = {}
    # fill bloom
    for _ in range(fill_elements):
Exemplo n.º 4
0
    RateLimitException,
    cache_detect,
    utils,
    LockedException,
)

import databases
import orm
import sqlalchemy
import jwt

database = databases.Database("sqlite:///db.sqlite")
metadata = sqlalchemy.MetaData()
app = FastAPI()

cache.setup("redis://", client_side=True)
cache.setup("mem://1", prefix="fail")

SECRET_KEY = "test"
ALGORITHM = "HS256"


class Auth(BaseModel):
    username: str
    password: str


class User(orm.Model):
    __tablename__ = "user"
    __metadata__ = metadata
    __database__ = database
Exemplo n.º 5
0
from datetime import timedelta

from fastapi import FastAPI
from cashews import (
    cache,
    Cache,
    mem,
    RateLimitException,
    context_cache_detect,
    utils,
    LockedException,
)

app = FastAPI()
cache.setup("mem://")
# cache.setup("disk://")
# cache.setup("redis://?safe=True&maxsize=20&create_connection_timeout=0.01")
# cache.setup("redis://?safe=True&maxsize=20&create_connection_timeout=0.01", client_side=True)
# cache.setup("redis://?safe=True&maxsize=20&create_connection_timeout=0.01", client_side=True, local_cache=Cache("disk").setup("disk://"))


@app.get("/")
@cache(ttl=timedelta(minutes=1))
async def simple():
    await asyncio.sleep(1)
    return "".join([random.choice(string.ascii_letters) for _ in range(10)])


@app.get("/early")
@cache.early(ttl=timedelta(minutes=5), early_ttl=timedelta(minutes=1))
Exemplo n.º 6
0
        allow_origins=config.CORS_ALLOW_ORIGINS,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    app.include_router(api.router)

    app.add_exception_handler(api.exceptions.APIError,
                              api.exceptions.api_error_exception_handler)

    @app.on_event("startup")
    async def init_db_client():
        await db.init_client()

    @app.on_event("shutdown")
    async def close_db_client():
        await db.close_client()

    sentry_sdk.init(
        config.SENTRY_DSN,
        environment=config.SENTRY_ENV,
        release=f"shelf@{app.version}",
    )
    app.add_middleware(SentryAsgiMiddleware)

    return app


cache.setup(config.CACHE_BACKEND_DSN)
app = create_app()
Exemplo n.º 7
0
    context_cache_detect,
    utils,
    LockedException,
)

import databases
import orm
import sqlalchemy
import jwt

database = databases.Database("sqlite:///db.sqlite")
metadata = sqlalchemy.MetaData()
app = FastAPI()

cache.setup(
    "redis://?hash_key=test&safe=True&maxsize=20&create_connection_timeout=0.01",
    client_side=True)

SECRET_KEY = "test"
ALGORITHM = "HS256"


class Auth(BaseModel):
    username: str
    password: str


class User(orm.Model):
    __tablename__ = "user"
    __metadata__ = metadata
    __database__ = database