金字塔烧杯访问已创建的会话

时间:2012-01-17 11:16:02

标签: python session pyramid beaker

我正在尝试在金字塔框架中使用金字塔烧杯,它只是不工作它创建会话对象但我无法用线访问它们

@view_config(route_name='load_qli', renderer='json')
def load_qli(request):
    request.environ['beaker.session']

它出现以下错误

KeyError

KeyError: 'beaker.session'

我的development.ini文件看起来像这样

# pyramid_beaker settings
session.type = file
session.data_dir = %(here)s/data/sessions/data
session.lock_dir = %(here)s/data/sessions/lock
session.key = customerskey
session.secret = customerssecret
session.cookie_on_exception = true

和init.py这样

from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from qlipe.models import DBSession
from pyramid_mailer import mailer_factory_from_settings
from pyramid_beaker import session_factory_from_settings


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)


    # pyramid_beaker add-on
    session_factory = session_factory_from_settings(settings)   

    config = Configurator(
        settings=settings, 
        session_factory=session_factory
    )

我像这样创建会话

def my_view(request):
    session = request.session
    session['name'] = 'Fred Smith'
    session.save()

我哪里错了?

1 个答案:

答案 0 :(得分:5)

您应该只能使用include方式,而pyramid_beaker包可以从ini值初始化自己。

你的ini文件中的

pyramid_includes = pyramid_beaker

或在主函数的__init__.py文件中:

config.include('pyramid_beaker')

您可以在此处阅读更多内容http://docs.pylonsproject.org/projects/pyramid_beaker/en/latest/#setup

访问会话的常用方法是通过请求,就像在my_view中一样:

session = request.session

pyramid_beaker包使用金字塔会话工厂,它管理会话的方式不是通过request.environement ['beaker.session']对象,如beaker的例子。有关详情,请阅读http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/narr/sessions.html