【问题标题】:Flask: Set session variable from URL ParamFlask:从 URL 参数设置会话变量
【发布时间】:2014-03-13 00:31:25
【问题描述】:

我有一个需要根据访问者进入的 URL 重新命名的网站。在大多数情况下,内容是相同的,但 CSS 是不同的。我是全新的烧瓶和相对较新的会话 cookie,但我认为最好的方法是创建一个包含“客户端”会话变量的会话 cookie。然后,根据客户(品牌),我可以将特定的 css 包装器附加到模板。

如何访问 URL 参数并将其中一个参数值设置为会话变量?例如,如果访问者从 www.example.com/index?client=brand1 进来,那么我想设置 session['client'] = brand1。

我的 app.py 文件:

import os
import json
from flask import Flask, session, request, render_template


app = Flask(__name__)

# Generate a secret random key for the session
app.secret_key = os.urandom(24)

@app.route('/')
def index():
    session['client'] = 
    return render_template('index.html')

@app.route('/edc')
def edc():
    return render_template('pages/edc.html')

@app.route('/success')
def success():
    return render_template('success.html')

@app.route('/contact')
def contact():
    return render_template('pages/contact.html')

@app.route('/privacy')
def privacy():
    return render_template('pages/privacy.html')

@app.route('/license')
def license():
    return render_template('pages/license.html')

@app.route('/install')
def install():
    return render_template('pages/install.html')

@app.route('/uninstall')
def uninstall():
    return render_template('pages/uninstall.html')

if __name__ == '__main__':
    app.run(debug=True)

【问题讨论】:

    标签: python session cookies flask


    【解决方案1】:

    您可以在 @flask.before_request 装饰函数中这样做:

    @app.before_request
    def set_client_session():
        if 'client' in request.args:
            session['client'] = request.args['client']
    

    set_client_session 将在每个传入请求时调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2012-02-05
      • 1970-01-01
      相关资源
      最近更新 更多