首页 > 解决方案 > 烧瓶设置饼干

问题描述

我尝试在 Flask 中设置 cookie,但我没有得到我想要的。我没有得到用户名,而是在我的 URL 上附加了一个响应。我的路线.py

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)

        userCookie = request.form['username']
        resp = make_response(render_template('index.html'))
        resp.set_cookie('user', userCookie)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index', resp=resp)
        return redirect(next_page)
    return render_template('login.html', title='Sign In', form=form)

我想在index.html中显示 cookie 的内容

{% for r in resp %}
  {{ r }}
{% endfor %}  

相反,我得到:

index?resp<Response+1250+bytes+[200+OK]>

我究竟做错了什么?

[编辑-注销方法]

这是我添加cookie之前的方法

@app.route('/logout')
def logout():
  logout_user()
  return redirect(url_for('index'))

因此,如果我添加了 cookie:

@app.route('/logout')
def logout():
    resp = make_response(redirect('/login'))
    resp.delete_cookie('user')

如果我重新启动服务器,登录,cookie 被创建,但在注销后我什至可以去端点 /login 返回 resp

标签: pythoncookiesflask

解决方案


Cookie 设置在一个请求中,可以在另一个请求中使用。

为了克服这个问题,使用redirectin make_response

我附上了一个使用 cookie 的登录/注销功能示例:

app.py

from flask import Flask, render_template, request, make_response, flash, redirect

app = Flask(__name__)
app.config['SECRET_KEY'] = 'SUPER SECRET'

@app.route('/', methods = ['GET'])
def home():
    username = request.cookies.get('username')
    if username:
        return render_template('home.html', username=username)
    return render_template('home.html')

@app.route('/login', methods = ['GET','POST'])
def login():
    username = request.cookies.get('username')
    if username:
        return render_template('login.html', username=username)
    if request.method=='POST':
        username = request.form.get('username')
        password = request.form.get('password')
        if username=='admin' and password=='admin':
            flash("Successful login", "success")
            resp = make_response(redirect('/'))
            resp.set_cookie('username', username)
            return resp
        else:
            flash("Wrong username or password", "danger")
    return render_template('login.html')

@app.route('/logout', methods = ['GET'])
def logout():
    resp = make_response(redirect('/'))
    resp.delete_cookie('username')
    return resp
app.run(debug=True)

home.html

<html>
    <head>
        <title>Home</title>
    </head>
    <body>
        {% with messages = get_flashed_messages() %}
          {% if messages %}
            <ul class=flashes>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
            </ul>
          {% endif %}
        {% endwith %}
        {% if username %}
            Welcome {{ username }}. 
            <a href="{{ url_for('logout') }}">Click here</a> to logout.
        {% else %}
            You are not logged in.          
            <a href="{{ url_for('login') }}">Click here</a> to login.
        {% endif %}
    </body>
</html>

login.html

<html>
    <head>
        <title>Login</title>
    </head>
    <body>
        {% with messages = get_flashed_messages() %}
          {% if messages %}
            <ul class=flashes>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
            </ul>
          {% endif %}
        {% endwith %}

        {% if username %}
            You are already logged in as{{ username }}.
            <a href="{{ url_for('home') }}">Click here</a> to go to home.
            <a href="{{ url_for('logout') }}">Click here</a> to logout.
        {% else %}
            <form method="post" action="">
                <label for="username">Username</label>
                <input type="text" name="username" id="username"/> 
                <br/>

                <label for="password">Password</label>
                <input type="password" name="password" id="password"/> 
                <br/>

                <input type="submit" name="submit" id="submit" value="Login"/> 
            </form>
        {% endif %}
    </body>
</html>

截图:

1.登录前(无cookie):

登录前

2.登录(无cookie):

登录

3.登录后(收到cookie):

登录后

4.注销后(无cookie):

注销后


推荐阅读