简体   繁体   English

与烧杯的Bottle.py会话

[英]Bottle.py session with Beaker

first time questioner here. 这是第一次提问者。

I'm currently struggling on how to use Beaker properly using the Bottle micro-framework. 我目前正在努力如何使用Bottle微框架正确使用Beaker。 Here's the problematic program: 这是有问题的程序:

#!/usr/bin/python
# -*- coding: utf-8 -*-
# filename: server.py

import bottle as app
from beaker.middleware import SessionMiddleware

session_options = {
    'session.type': 'file',
    'session.data_dir': './session/',
    'session.auto': True,
}
app_middlware = SessionMiddleware(app.app(), session_options)
app_session = app.request.environ.get('beaker.session')

@app.route('/login')
def login():
    app_session = app.request.environ.get('beaker.session')
    app_session['logged_in'] = True

@app.route('/logout')
def logout():
    app_session = app.request.environ.get('beaker.session')
    if app_session.get('logged_in'):
        app_session['logged_in'] = False
        return 'You are logged out'
    app.redirect('/login')

@app.route('/dashboard')
def dashboard():
    app_session = app.request.environ.get('beaker.session')
    if app_session.get('logged_in'):
        return 'You are logged in'
    app.redirect('/login')

app.debug(True)
app.run(app=app_middlware, reloader=True)

If you noticed, I keep on calling app_session = app.request.environ.get('beaker.session') on every def block so just it will not return an error like: TypeError: 'NoneType' object does not support item assignment --- it seems that Python doesn't recognize variables that is outside its function (correct me if I'm wrong). 如果您注意到,我会继续在每个def块上调用app_session = app.request.environ.get('beaker.session') ,这样就不会返回如下错误: TypeError: 'NoneType' object does not support item assignment - - 似乎Python无法识别其功能之外的变量(如果我错了,请纠正我)。

And here are the questions: 以下是问题:

  1. What should I do to only have one instance of app_session = app.request.environ.get('beaker.session') so it can be available to every def blocks (I really need one instance since it's the same session to be checked and used). 我应该怎么做只有一个app_session = app.request.environ.get('beaker.session')实例,所以它可以用于每个def块(我真的需要一个实例,因为它是相同的会话要检查和用过的)。
  2. If this is the only way (it's ugly though), then should I just combine all routes that requires a session just so I can achieve the single instance of app_session ? 如果这是唯一的方法(虽然它很丑陋),那么我应该只需要组合所有需要会话的路由,这样我就可以实现app_session的单个实例吗?

Something like: 就像是:

@app.route('/<path:re:(login|dashboard|logout)\/?>')
def url(path):
    app_session = app.request.environ.get('beaker.session')
    if 'login' in path:
        app_session['logged_in'] = True
    elif 'logout' in path:
        if app_session.get('logged_in'):
            # app_session.delete() it doesn't seem to work?
            app_session['logged_in'] = False
            return 'You are logged out'
        app.redirect('/login')
    elif 'dashboard' in path:
        if app_session.get('logged_in'):
            return 'You are logged in'
        app.redirect('/login')

Using beaker in your bottle application is easy. bottle使用beaker很容易。 First, set up your Bottle app: 首先,设置您的Bottle应用:

import bottle
from bottle import request, route, hook
import beaker.middleware

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

app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)

And later on: 后来:

bottle.run(app=app)

With this in place, every time you receive a request, your Beaker session will be available as request.environ['beaker_session'] . 有了这个,每次收到请求时,您的Beaker会话都将作为request.environ['beaker_session'] I usually do something like this for convenience: 为方便起见,我通常会这样做:

@hook('before_request')
def setup_request():
    request.session = request.environ['beaker.session']

This arranges to run setup_request before handling any request; 这安排在处理任何请求之前运行setup_request ; we're using the bottle.request variable (see the earlier import statement), which is a thread-local variable with information about the current request. 我们正在使用bottle.request变量(参见前面的import语句),它是一个线程局部变量,包含有关当前请求的信息。 From this point on, I can just refer to request.session whenever I need it, eg: 从这一点开始,我可以随时在需要时引用request.session ,例如:

@route('/')
def index():
    if 'something' in request.session:
       return 'It worked!'

    request.session['something'] = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM