使用不带wtf_forms的flask_wtf.csrf

2022-02-21 00:00:00 python flask jinja2 flask-wtforms html

我有一个简单的flask Web应用程序,我想使用flask_wtf CSRF保护,但是每当我尝试运行以提交表单时,都会收到错误消息,说我缺少CSRF令牌。

是否可以在没有wtf表单的情况下使用CSRF? 如果是这样的话,我做错了什么?

我的代码:

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

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


<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>

解决方案

查看代码,需要用csfr初始化APP,示例如下:

from flask_wtf.csrf import CSRFProtect
from flask import Flask,render_template,request,redirect
app = Flask(__name__)
csrf = CSRFProtect(app)
csrf.init_app(app)
app.config['SECRET_KEY'] = 'SUPER SECRET KEY TEST'
@app.route("/reserve", methods=["GET", "POST"])
def reserve():
    context = {
        'gh':'as' 
    }
    if request.method == "GET" :
       return render_template("reserve.html", **context)
    
    else:
        user = request.form['ssss']
        return 'USER : '+user
@app.route("/")
def index():
    return redirect('/reserve')

和html


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

相关文章