示例#1
0
文件: test_form.py 项目: pepej/py4web
 def test_form(self):
     session = Session()
     session.initialize()
     table = [Field("name")]
     form_name = 'testing_form'
     f = Form(table, form_name=form_name, csrf_session=session)
     value = f.formkey
     post_vars = dict(_formname=form_name, _formkey=value)
     self.assertTrue(f._verify_form(post_vars))
示例#2
0
    def test_session_in_memcache(self):
        memcache_process = None
        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"
            cookie_name = session.local.session_cookie_name
            session.on_success(200)

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

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

            conn = memcache.Client(["127.0.0.1:11211"], debug=0)
            session = Session(expiration=10, storage=conn)
            request.cookies[a] = "wrong_cookie"
            session.on_request()
            self.assertEqual(session.get("key"), None)
        finally:
            if memcache_process is None:
                print("memcached not availabl, test skipped")
            elif memcache_process:
                memcache_process.kill()
示例#3
0
    def test_session(self):
        request.app_name = "myapp"
        session = Session(secret="a", expiration=10)
        session.on_request()
        session["key"] = "value"
        cookie_name = session.local.session_cookie_name
        session.on_success(200)
        a, b = str(
            response._cookies)[len("Set-Cookie: "):].split(";")[0].split(
                "=", 1)
        request.cookies[a] = b
        session.finalize()
        self.assertEqual(session.local, None)

        session = Session(secret="b", expiration=10)
        request.cookies[a] = b
        session.on_request()
        self.assertEqual(session.get("key"), None)

        session = Session(secret="a", expiration=10)
        request.cookies[a] = b
        session.on_request()
        self.assertEqual(session.get("key"), "value")
示例#4
0
    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"
        cookie_name = session.local.session_cookie_name
        session.on_success(200)
        a, b = str(
            response._cookies)[len("Set-Cookie: "):].split(";")[0].split(
                "=", 1)
        request.cookies[a] = b
        session.finalize()
        self.assertIsNone(session.local)

        session = Session(expiration=10, storage=DBStore(db))
        request.cookies[a] = b
        session.on_request()
        self.assertEqual(session.get("key"), "value")

        session = Session(expiration=10, storage=DBStore(db))
        request.cookies[a] = "wrong_cookie"
        session.on_request()
        self.assertEqual(session.get("key"), None)
示例#5
0
    def test_session_in_memcache(self):
        memcache_process = None
        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()
            context = dict(status=200)
            session.on_request(context)
            session["key"] = "value"
            cookie_name = session.local.session_cookie_name
            session.on_success(context)

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

            _before_request()
            with pytest.raises(RuntimeError) as err:
                session.local
            self.assertTrue("py4web hint" in str(err.value))

            conn = memcache.Client(["127.0.0.1:11211"], debug=0)
            session = Session(expiration=10, storage=conn)
            request.cookies[a] = b
            context = dict(status=200)
            session.on_request(context)
            self.assertEqual(session.get("key"), "value")

            conn = memcache.Client(["127.0.0.1:11211"], debug=0)
            session = Session(expiration=10, storage=conn)
            request.cookies[a] = "wrong_cookie"
            context = dict(status=200)
            session.on_request(context)
            self.assertEqual(session.get("key"), None)
        finally:
            if memcache_process is None:
                print("memcached not availabl, test skipped")
            elif memcache_process:
                memcache_process.kill()
示例#6
0
    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)
            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()
示例#7
0
import os, re
from py4web import action, abort, request, Session, URL
from py4web.core import Fixture, Reloader
from pydal.validators import CRYPT
from . import fs2json

__static_version__ = '1.0.3'

session = Session()


class Logged(Fixture):
    def __init__(self, session):
        self.__prerequisites__ = [session]
        self.session = session

    def on_request(self):
        user = self.session.get('user')
        if not user or not user.get('id'):
            abort(403)

session_secured = action.uses(Logged(session))

@action('login', method='POST')
@action.uses(session)
def login():
    valid = False
    password = request.json.get('password')
    password_file = os.environ.get('PY4WEB_PASSWORD_FILE')
    if password and password_file and os.path.exists(password_file):
        with open(password_file, 'r') as fp:
示例#8
0
 def test_local(self):
     # for test coverage
     request.app_name = "example"
     Session.__init_request_ctx__()  # mimic before_request-hook
     index()
示例#9
0
    def test_session(self):
        request.app_name = "myapp"
        session = Session(secret="a", expiration=10)
        session.on_request()
        session["key"] = "value"
        cookie_name = session.local.session_cookie_name
        session.on_success(200)
        a, b = str(
            response._cookies)[len("Set-Cookie: "):].split(";")[0].split(
                "=", 1)
        request.cookies[a] = b

        _before_request()
        with pytest.raises(RuntimeError) as err:
            session.local
        self.assertTrue('py4web hint' in str(err.value))

        session = Session(secret="b", expiration=10)
        request.cookies[a] = b
        session.on_request()
        self.assertEqual(session.get("key"), None)

        session = Session(secret="a", expiration=10)
        request.cookies[a] = b
        session.on_request()
        self.assertEqual(session.get("key"), "value")
示例#10
0
    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"
        cookie_name = session.local.session_cookie_name
        session.on_success(200)
        a, b = str(
            response._cookies)[len("Set-Cookie: "):].split(";")[0].split(
                "=", 1)
        request.cookies[a] = b

        _before_request()
        with pytest.raises(RuntimeError) as err:
            session.local
        self.assertTrue('py4web hint' in str(err.value))

        session = Session(expiration=10, storage=DBStore(db))
        request.cookies[a] = b
        session.on_request()
        self.assertEqual(session.get("key"), "value")

        session = Session(expiration=10, storage=DBStore(db))
        request.cookies[a] = "wrong_cookie"
        session.on_request()
        self.assertEqual(session.get("key"), None)
示例#11
0
import os
from py4web import action, request, DAL, Field, Session, Cache, Condition

# 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()

# an example of a custom requirement
user_in_session = Condition(lambda: session.get('user', False))


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


# example of GET/POST/DELETE RESTful APIs


@action("api")  # a GET API function
示例#12
0
 def test_local(self):
     # for test coverage
     Session.__init_request_ctx__()  # mimic before_request-hook
     index()
示例#13
0
import os
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())

示例#14
0
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)


# example of GET/POST/DELETE RESTful APIs


@action("api")  # a GET API function
@action.uses(session)  # we load the session
@action.requires(user_in(session)
                 )  # then check we have a valid user in session
示例#15
0
    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()
        self.assertEqual(session.get('key'), 'value')
示例#16
0
import os
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

    # test copying Field ThreadSafe attr
    db.thing.name.default = "test_clone"
示例#17
0
    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)
示例#18
0
文件: common.py 项目: RekGRpth/py4web
db = DAL(
    settings.DB_URI,
    folder=settings.DB_FOLDER,
    pool_size=settings.DB_POOL_SIZE,
    migrate=settings.DB_MIGRATE,
    fake_migrate=settings.DB_FAKE_MIGRATE,
)

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

# 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, ct(k))
                if ct(k) >= 0 else cs(k, v, 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":
示例#19
0
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'))


# 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)


# example of GET/POST/DELETE RESTful APIs


@action('api')  # a GET API function
@action.uses(session)  # we load the session
@action.requires(user_in(session)
                 )  # then check we have a valid user in session
@action.uses(db)  # all before starting a db connection