Bottle() w/ Beaker 中间件?

Bottle() w/ Beaker Middleware?

如何将 bottle 子应用与 beaker Sessions 一起使用?

bottlepy.org 显示了两者的示例:

子应用 http://bottlepy.org/docs/dev/tutorial.html#plugins-and-sub-applications

会话数 http://bottlepy.org/docs/dev/recipes.html#keeping-track-of-sessions

合并

from bottle import Bottle
from beaker.middleware import SessionMiddleware

session_opts = {
    'session.type': 'file',
    'session.cookie_expires': 300,
    'session.data_dir': './data',
    'session.auto': True
}

app = Bottle()
app = SessionMiddleware(app, session_opts)

@app.route('/')
def hello():
    return 'Hello World'

app.run()

这会引发以下错误:

Traceback (most recent call last):
 File "example.py", line 14, in <module>
 @app.route('/')
 AttributeError: 'SessionMiddleware' object has no attribute 'route'

您是否尝试过执行与教程中完全相同的代码?

import bottle
from beaker.middleware import SessionMiddleware

session_opts = {
    'session.type': 'file',
    'session.cookie_expires': 300,
    'session.data_dir': './data',
    'session.auto': True
}
app = SessionMiddleware(bottle.app(), session_opts)

@bottle.route('/test')
def test():
  s = bottle.request.environ.get('beaker.session')
  s['test'] = s.get('test',0) + 1
  s.save()
  return 'Test counter: %d' % s['test']

bottle.run(app=app)

这里提供了答案:https://github.com/bbangert/beaker/issues/79#issuecomment-89769806

import bottle
from beaker.middleware import SessionMiddleware

session = {
    'session.type': 'file',
    'session.cookie_expires': 300,
    'session.data_dir': './data',
    'session.auto': True
}
main_app = bottle.Bottle()
sub_app = bottle.Bottle()

app = SessionMiddleware(main_app, session)

@main_app.route('/')
def index():
     return 'This is app'

@sub_app.route('/')
def sub_app_index():
    return 'This is subapp'

main_app.mount('/sub', sub_app)

bottle.run(app=app)

您也可以从单独的模块导入您的子应用程序

如果你的脚本中只有一个bottle app,你可以使用@route代替@app.route

所以关于使用 beaker.SessionMiddleware 的轻微警告。它会根据读取它的每个请求写入整个会话。我们在使用多线程服务器时发现了这一点,因为写入它会丢失(由于明显的竞争条件)。因此,我们为它写了一个替代品(相同 API)。可在此处获取:https://github.com/keredson/drsession