Python Flask:跟踪用户会话?如何获取会话 Cookie ID?

Posted

技术标签:

【中文标题】Python Flask:跟踪用户会话?如何获取会话 Cookie ID?【英文标题】:Python Flask: keeping track of user sessions? How to get Session Cookie ID? 【发布时间】:2015-12-14 21:34:27 【问题描述】:

我想构建一个简单的 web 应用程序作为我学习活动的一部分。如果 Webapp 遇到第一次访问者,它应该要求用户输入他们的 email_id,否则它会通过 cookie 记住用户并自动登录以执行这些功能。

这是我第一次创建基于用户的网络应用程序。我心中有一个蓝图,但我无法弄清楚如何实现它。主要是我对收集用户 cookie 的方式感到困惑。我查看了各种教程和 flask_login,但我认为与 flask_login 实现的相比,我想要实现的要简单得多。

我也尝试使用flask.session,但它有点难以理解,最终我得到了一个有缺陷的实现。

这是我目前所拥有的(它是基本的,旨在传达我的用例):

from flask import render_template, request, redirect, url_for


@app.route("/", methods= ["GET"])
def first_page():
  cookie = response.headers['cookie']
  if database.lookup(cookie):
   user = database.get(cookie) # it returns user_email related to that cookie id 
  else:
    return redirect_url(url_for('login'))
  data = generateSomeData() # some function
  return redirect(url_for('do_that'), user_id, data, stats)

@app.route('/do_that', methods =['GET'])
def do_that(user_id):
  return render_template('interface.html', user_id, stats,data) # it uses Jinja template

@app.route('/submit', methods =["GET"])
def submit():
  # i want to get all the information here
  user_id = request.form['user_id']# some data
  answer = request.form['answer'] # some response to be recorded
  data = request.form['data'] # same data that I passed in do_that to keep 
  database.update(data,answer,user_id)
  return redirect(url_for('/do_that'))

@app.route('/login', methods=['GET'])
def login():
  return render_template('login.html')

@app.route('/loggedIn', methods =['GET'])
def loggedIn():
  cookie = response.headers['cookie']
  user_email = response.form['user_email']
  database.insert(cookie, user_email)
  return redirect(url_for('first_page'))

【问题讨论】:

database 对象来自哪里? 【参考方案1】:

您可以通过request.cookies dictionary 访问请求cookie,并通过使用make_response 或将调用render_template 的结果存储在变量中然后调用set_cookie on the response object 来设置cookie:

@app.route("/")
def home():
    user_id = request.cookies.get('YourSessionCookie')
    if user_id:
        user = database.get(user_id)
        if user:
            # Success!
            return render_template('welcome.html', user=user)
        else:
            return redirect(url_for('login'))
    else:
        return redirect(url_for('login'))

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        # You should really validate that these fields
        # are provided, rather than displaying an ugly
        # error message, but for the sake of a simple
        # example we'll just assume they are provided

        user_name = request.form["name"]
        password = request.form["password"]
        user = db.find_by_name_and_password(user_name, password)

        if not user:
            # Again, throwing an error is not a user-friendly
            # way of handling this, but this is just an example
            raise ValueError("Invalid username or password supplied")

        # Note we don't *return* the response immediately
        response = redirect(url_for("do_that"))
        response.set_cookie('YourSessionCookie', user.id)
        return response

@app.route("/do-that")
def do_that():
    user_id = request.cookies.get('YourSessionCookie')
    if user_id:
        user = database.get(user_id)
        if user:
            # Success!
            return render_template('do_that.html', user=user)
        else:
            return redirect(url_for('login'))
    else:
        return redirect(url_for('login'))

干掉代码

现在,您会注意到在homedo_that 方法中有很多样板文件,都与登录有关。您可以通过编写自己的装饰器来避免这种情况(如果您想了解更多信息,请参阅 What is a decorator):

from functools import wraps
from flask import flash

def login_required(function_to_protect):
    @wraps(function_to_protect)
    def wrapper(*args, **kwargs):
        user_id = request.cookies.get('YourSessionCookie')
        if user_id:
            user = database.get(user_id)
            if user:
                # Success!
                return function_to_protect(*args, **kwargs)
            else:
                flash("Session exists, but user does not exist (anymore)")
                return redirect(url_for('login'))
        else:
            flash("Please log in")
            return redirect(url_for('login'))
    return wrapper

那么你的 homedo_that 方法会变得大大更短:

# Note that login_required needs to come before app.route
# Because decorators are applied from closest to furthest
# and we don't want to route and then check login status

@app.route("/")
@login_required
def home():
    # For bonus points we *could* store the user
    # in a thread-local so we don't have to hit
    # the database again (and we get rid of *this* boilerplate too).
    user = database.get(request.cookies['YourSessionCookie'])
    return render_template('welcome.html', user=user)

@app.route("/do-that")
@login_required
def do_that():
    user = database.get(request.cookies['YourSessionCookie'])
    return render_template('welcome.html', user=user)

使用提供的内容

如果您需要您的 cookie 有一个特定的名称,我建议您使用 flask.session,因为它已经内置了很多细节(它已签名,所以它不能被篡改,可以设置为仅 HTTP 等)。这让我们的 login_required 装饰器更加干燥:

# You have to set the secret key for sessions to work
# Make sure you keep this secret
app.secret_key = 'something simple for now' 

from flask import flash, session

def login_required(function_to_protect):
    @wraps(function_to_protect)
    def wrapper(*args, **kwargs):
        user_id = session.get('user_id')
        if user_id:
            user = database.get(user_id)
            if user:
                # Success!
                return function_to_protect(*args, **kwargs)
            else:
                flash("Session exists, but user does not exist (anymore)")
                return redirect(url_for('login'))
        else:
            flash("Please log in")
            return redirect(url_for('login'))

然后您的个人方法可以通过以下方式获取用户:

user = database.get(session['user_id'])

【讨论】:

嗨,肖恩,感谢您的帮助。这是我能得到的最好答案。它为我清除了很多概念。只是一个问题:login_required 应该在 app.route 之后还是之前? 它应该总是出现在前面 - 请参阅最后一个代码 sn-p 中的注释(如果您想了解更多关于一般装饰器的信息,请参阅 this answer)。

以上是关于Python Flask:跟踪用户会话?如何获取会话 Cookie ID?的主要内容,如果未能解决你的问题,请参考以下文章

获取和会话和 CORS

我的第三十四篇博客---flask-cookie-sessionsqlchemary

python(十八):cookie和session

Flask:cookie 和 session (0.1)

python 框架Flask学习笔记之session

可以在 Python Flask 中为不同的用户创建不同的会话超时长度吗?