How to use the py4web.Cache function in py4web

To help you get started, we’ve selected a few py4web examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github web2py / py4web / tests / test_action.py View on Github external
import unittest
import uuid

import mechanize

from py4web import action, DAL, Field, Session, Cache
from py4web.core import bottle, request, error404

os.environ["PY4WEB_APPS_FOLDER"] = os.path.sep.join(
    os.path.normpath(__file__).split(os.path.sep)[:-2]
)

db = DAL("sqlite://storage_%s" % uuid.uuid4(), folder="/tmp/")
db.define_table("thing", Field("name"))
session = Session(secret="my secret")
cache = Cache()

action.app_name = "tests"


@action("index")
@cache.memoize(expiration=1)
@action.uses(db, session)
@action.requires(lambda: True)
def index():
    db.thing.insert(name="test")
    session["number"] = session.get("number", 0) + 1
    return "ok %s %s" % (session["number"], db(db.thing).count())


def run_server():
    bottle.run(host="localhost", port=8001)
github web2py / py4web / tests / test_cache.py View on Github external
def test_different_keys(self):
        cache = py4web.Cache()
        results = set()
        for k in range(100):
            results.add(cache.get("a", random.random))
            results.add(cache.get("b", random.random))
            results.add(cache.get("c", random.random))
        self.assertEqual(len(results), 3)
github web2py / py4web / tests / test_cache.py View on Github external
def test_memoize_and_expiration(self):
        memoize = py4web.Cache().memoize(expiration=0.1)

        @memoize
        def f(x):
            return x + random.random()

        results = set()
        for k in range(10):
            results.add(f(1))
            results.add(f(2))
        time.sleep(0.2)
        for k in range(10):
            results.add(f(1))
            results.add(f(2))
        self.assertEqual(len(results), 4)
github web2py / py4web / tests / test_cache.py View on Github external
def test_logic(self):
        cache = py4web.Cache()
        cache.get("x", lambda: "y")
        self.assertEqual(cache.head.next.next, cache.tail)
        self.assertEqual(cache.head.next, cache.tail.prev)
        self.assertEqual(cache.head, cache.tail.prev.prev)
        self.assertEqual(cache.head.next.key, "x")
        self.assertEqual(cache.head.next.value, "y")
github web2py / py4web / tests / test_cache.py View on Github external
def test_timing(self):
        M = N = 100000
        cache = py4web.Cache()
        for k in range(M):
            cache.get(k, random.random)
        t0 = time.time()
        for k in range(N):
            cache.get("new", random.random)
        self.assertTrue((time.time() - t0) / N, 1 - 5)
        self.assertTrue(cache.free == 0)
github web2py / py4web / tests / test_cache.py View on Github external
def test_change_detection(self):
        cache = py4web.Cache()
        results = set()
        for k in range(30):
            results.add(
                cache.get("a", random.random, expiration=0, monitor=lambda: int(k / 10))
            )
        self.assertEqual(len(results), 3)
        time.sleep(0.02)
        results.add(cache.get("a", random.random, expiration=0.01, monitor=lambda: 5))
        self.assertEqual(len(results), 4)
github web2py / py4web / apps / _scaffold / common.py View on Github external
)
for item in settings.LOGGERS:
    level, filename = item.split(":", 1)
    if filename in ("stdout", "stderr"):
        handler = logging.StreamHandler(getattr(sys, filename))
    else:
        handler = logging.FileHandler(filename)
    handler.setLevel(getattr(logging, level.upper(), "ERROR"))
    handler.setFormatter(formatter)
    logger.addHandler(handler)

# connect to db
db = DAL(settings.DB_URI, folder=settings.DB_FOLDER, pool_size=settings.DB_POOL_SIZE)

# define global objects that may or may not be used by th actions
cache = Cache(size=1000)
T = Translator(settings.T_FOLDER)

# pick the session type that suits you best
if settings.SESSION_TYPE == "cookies":
    session = Session(secret=settings.SESSION_SECRET_KEY)
elif settings.SESSION_TYPE == "redis":
    import redis

    host, port = settings.REDIS_SERVER.split(":")
    # for more options: https://github.com/andymccurdy/redis-py/blob/master/redis/client.py
    conn = redis.Redis(host=host, port=int(port))
    conn.set = lambda k, v, e, cs=conn.set, ct=conn.ttl: (cs(k, v), e and ct(e))
    session = Session(secret=settings.SESSION_SECRET_KEY, storage=conn)
elif settings.SESSION_TYPE == "memcache":
    import memcache, time
github web2py / py4web / apps / todo / __init__.py View on Github external
import os
from py4web import action, request, DAL, Field, Session, Cache, user_in

# define session and cache objects
session = Session(secret="some secret")
cache = Cache(size=1000)

# define database and tables
db = DAL(
    "sqlite://storage.db", folder=os.path.join(os.path.dirname(__file__), "databases")
)
db.define_table("todo", Field("info"))
db.commit()

# example index page using session, template and vue.js
@action("index")  # the function below is exposed as a GET action
@action.uses("index.html")  # we use the template index.html to render it
@action.uses(session)  # action needs a session object (read/write cookies)
def index():
    session["counter"] = session.get("counter", 0) + 1
    session["user"] = {"id": 1}  # store a user in session
    return dict(session=session)