【问题标题】:csrf session token missing flask [duplicate]csrf 会话令牌缺少烧瓶 [重复]
【发布时间】:2021-11-23 11:54:14
【问题描述】:

我正在尝试在我的表单上使用 csrf 保护,但我总是收到一条错误消息,提示我缺少 csrf 会话令牌。

我不知道我的代码有什么问题,也许这里有人可以帮助我理解我做错了什么。

我的代码:

app = Flask(__name__)
csrf = CSRFProtect(app)

@app.route("/reserve", methods=["GET", "POST"])
def reserve():
   if request.method == "GET" :
       return render_template("reserve.html", csrf_token=generate_csrf())


<form id="Reserve" action="/reserve" method="post">
   <!-- csrf protection -->
   <input type="hidden" name="csrf_token" value="{{ csrf_token }}"/>
   <input type="text" placeholder="Name">
   <button type="submit">
        Submit
   </button>
</form>

我尝试过使用:&lt;input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/&gt; 但是还是不行。

【问题讨论】:

    标签: html flask csrf flask-wtforms


    【解决方案1】:

    我想你忘了为应用程序设置secret key

    from flask import Flask
    from flask import render_template, request
    from flask_wtf.csrf import CSRFProtect
    
    app = Flask(__name__)
    app.secret_key = 'your secret here'
    csrf = CSRFProtect(app)
    
    @app.route('/reserve', methods=['GET', 'POST'])
    def reserve():
        if request.method == 'GET':
            return render_template('reserve.html')
    
    <form action="/reserve" method="post">
       <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
       <input type="text" name="name" placeholder="Name" />
       <button type="submit">Submit</button>
    </form>
    

    【讨论】:

    • 我做了,只是忘了提。
    • @Sheleftavor 它对我有用。
    猜你喜欢
    • 2020-02-10
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 2017-01-08
    • 2019-06-01
    • 1970-01-01
    相关资源
    最近更新 更多