How to use the py4web.Session 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 time
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():
github web2py / py4web / tests / test_session.py View on Github external
session.on_request()
            session["key"] = "value"
            session.on_success()
            cookie_name = session.local.session_cookie_name

            a, b = (
                str(response._cookies)[len("Set-Cookie: ") :]
                .split(";")[0]
                .split("=", 1)
            )
            request.cookies[a] = b
            request.cookies = response._cookies
            session.local.data.clear()

            conn = memcache.Client(["127.0.0.1:11211"], debug=0)
            session = Session(expiration=10, storage=conn)
            session.on_request()
            self.assertEqual(session.get("key"), "value")

            request.cookies[a] = "wrong_cookie"
            conn = memcache.Client(["127.0.0.1:11211"], debug=0)
            session = Session(expiration=10, storage=conn)
            session.on_request()
            self.assertEqual(session.get("key"), None)
        finally:
            if memcache_process:
                memcache_process.kill()
github web2py / py4web / tests / test_session.py View on Github external
def test_session_in_db(self):
        request.app_name = "myapp"
        db = DAL("sqlite:memory")
        session = Session(secret="a", expiration=10, storage=DBStore(db))
        request.cookies.clear()
        session.on_request()
        session["key"] = "value"
        session.on_success()
        cookie_name = session.local.session_cookie_name

        a, b = str(response._cookies)[len("Set-Cookie: ") :].split(";")[0].split("=", 1)
        request.cookies[a] = b
        request.cookies = response._cookies
        session.local.data.clear()

        session = Session(expiration=10, storage=DBStore(db))
        session.on_request()
        self.assertEqual(session.get("key"), "value")

        request.cookies[a] = "wrong_cookie"
github web2py / py4web / tests / test_session.py View on Github external
def test_session_in_memcache(self):
        try:
            memcache_process = subprocess.Popen(["memcached", "-p", "11211"])
            time.sleep(1)
            request.app_name = "myapp"
            conn = memcache.Client(["127.0.0.1:11211"], debug=0)
            session = Session(secret="a", expiration=10, storage=conn)
            request.cookies.clear()
            session.on_request()
            session["key"] = "value"
            session.on_success()
            cookie_name = session.local.session_cookie_name

            a, b = (
                str(response._cookies)[len("Set-Cookie: ") :]
                .split(";")[0]
                .split("=", 1)
            )
            request.cookies[a] = b
            request.cookies = response._cookies
            session.local.data.clear()

            conn = memcache.Client(["127.0.0.1:11211"], debug=0)
github web2py / py4web / tests / test_session.py View on Github external
def test_session(self):
        request.app_name = "myapp"
        session = Session(secret="a", expiration=10)
        session.on_request()
        session["key"] = "value"
        session.on_success()
        cookie_name = session.local.session_cookie_name

        a, b = str(response._cookies)[len("Set-Cookie: ") :].split(";")[0].split("=", 1)
        request.cookies[a] = b
        request.cookies = response._cookies
        session.local.data.clear()

        session = Session(secret="b", expiration=10)
        session.on_request()
        self.assertEqual(session.get("key"), None)

        session = Session(secret="a", expiration=10)
        session.on_request()
github web2py / py4web / tests / test_session.py View on Github external
session = Session(secret="a", expiration=10)
        session.on_request()
        session["key"] = "value"
        session.on_success()
        cookie_name = session.local.session_cookie_name

        a, b = str(response._cookies)[len("Set-Cookie: ") :].split(";")[0].split("=", 1)
        request.cookies[a] = b
        request.cookies = response._cookies
        session.local.data.clear()

        session = Session(secret="b", expiration=10)
        session.on_request()
        self.assertEqual(session.get("key"), None)

        session = Session(secret="a", expiration=10)
        session.on_request()
        self.assertEqual(session.get("key"), "value")
github web2py / py4web / tests / test_session.py View on Github external
def test_session_in_db(self):
        request.app_name = "myapp"
        db = DAL("sqlite:memory")
        session = Session(secret="a", expiration=10, storage=DBStore(db))
        request.cookies.clear()
        session.on_request()
        session["key"] = "value"
        session.on_success()
        cookie_name = session.local.session_cookie_name

        a, b = str(response._cookies)[len("Set-Cookie: ") :].split(";")[0].split("=", 1)
        request.cookies[a] = b
        request.cookies = response._cookies
        session.local.data.clear()

        session = Session(expiration=10, storage=DBStore(db))
        session.on_request()
        self.assertEqual(session.get("key"), "value")

        request.cookies[a] = "wrong_cookie"
        session = Session(expiration=10, storage=DBStore(db))
        session.on_request()
        self.assertEqual(session.get("key"), None)
github web2py / py4web / apps / _scaffold / common.py View on Github external
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

    conn = memcache.Client(settings.MEMCACHE_CLIENTS, debug=0)
    session = Session(secret=settings.SESSION_SECRET_KEY, storage=conn)
elif settings.SESSION_TYPE == "database":
    from py4web.utils.dbstore import DBStore
github web2py / py4web / apps / _scaffold / common.py View on Github external
# 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

    conn = memcache.Client(settings.MEMCACHE_CLIENTS, debug=0)
    session = Session(secret=settings.SESSION_SECRET_KEY, storage=conn)
elif settings.SESSION_TYPE == "database":
    from py4web.utils.dbstore import DBStore

    session = Session(secret=settings.SESSION_SECRET_KEY, storage=DBStore(db))

auth = Auth(session, db)

if settings.SMTP_SERVER:
    auth.mailer = Mailer(
        server=settings.SMTP_SERVER,
        sender=settings.SMTP_SENDER,
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