如果我理解正确,您的问题是无法在您的视图代码中访问 de csrf 令牌数据。
我添加了一些代码,以便在收到 POST 请求时从服务器端返回令牌,并且它可以正常工作:
文件夹结构
├── app.py
└── templates
└── reserve.html
(默认情况下,Flask 会在项目根目录中的 templates 文件夹中查找)
app.py
from flask import Flask, request, render_template
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
csrf = CSRFProtect(app)
app.config['SECRET_KEY'] = 'secret'
@app.route('/reserve', methods=['GET', 'POST'])
def reserve():
if request.method == 'GET':
return render_template('reserve.html')
if request.method == 'POST':
return {
'token': request.form.get('csrf_token')
}
if __name__ == '__main__':
app.run()
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">
<button type="submit">
Submit
</button>
</form>
启动服务器:
$ python app.py
* Serving Flask app 'app' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
然后在浏览器中打开这个网址:http://127.0.0.1:5000/reserve
如果您检查 HTML 表单,您会看到如下内容:
<input type="hidden" name="csrf_token" value="IjZkNGZhMTI1MGVmNWUzZDA4OGEwOThlZjZiODIxMGY3MTljYjBiNWUi.YVg1pA.EzPIPEqadPoq8oZQNxWpi33WRqk">
提交输入值,你会看到接收到的token和隐藏输入中渲染的值是一样的:
{"token":"IjZkNGZhMTI1MGVmNWUzZDA4OGEwOThlZjZiODIxMGY3MTljYjBiNWUi.YVg1pA.EzPIPEqadPoq8oZQNxWpi33WRqk"}