Flask:从URL参数设置会话变量
我有一个网站,想根据访问者进入的链接来改变网站的品牌形象。大部分内容是一样的,但样式(CSS)却不一样。我刚开始学习Flask,对会话cookie也还不太熟悉,但我觉得最好的办法是创建一个会话cookie,里面包含一个“client”(客户)会话变量。然后,根据不同的客户(品牌),我可以在模板中添加特定的CSS样式。
我该如何获取链接中的参数,并把其中一个参数的值设置为会话变量呢?比如,如果一个访问者通过 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)
1 个回答
4
你可以在一个用 @flask.before_request
装饰的函数里做到这一点:
@app.before_request
def set_client_session():
if 'client' in request.args:
session['client'] = request.args['client']
set_client_session
会在每次收到请求时被调用。