使用不带wtf_forms的flask_wtf.csrf [英] using flask_wtf.csrf without wtf_forms

查看:34
本文介绍了使用不带wtf_forms的flask_wtf.csrf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的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>

这篇关于使用不带wtf_forms的flask_wtf.csrf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆