一:安装 flask_wtf

pip install flask_wtf

二:设置应用程序的 secret_key,用于加密生成的 csrf_token 的值

# session加密的时候已经配置过了.如果没有在配置项中设置,则如下:
app.secret_key = "#此处可以写随机字符串#"

三:导入 flask_wtf.csrf 中的 CSRFProtect 类,进行初始化,并在初始化的时候关联 app

from flask.ext.wtf import CSRFProtect
CSRFProtect(app)

四:在表单中使用 CSRF 令牌:

<form method="post" action="/">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
</form>

 

五:scrf的过程理解

代码显示方法不被允许的代码

#manage.py

  
from flask import Flask, render_template, request, g
from settings.dev import DevConfig
from flask.ext.wtf import CSRFProtect

app = Flask(__name__, template_folder="templates", static_folder="static")
app.config.from_object(DevConfig)

CSRFProtect(app)

# @app.route("/csrf_test", methods=["get", "post"])
@app.route("/csrf_test")
def index():
    if request.method == "GET":
        return render_template("form.html")

    else:
        print(request.form)

        return "ok"

if __name__ == "__main__":
    app.run()
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-25
  • 2022-12-23
  • 2022-02-07
  • 2022-01-18
  • 2022-12-23
  • 2021-09-07
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2021-10-16
  • 2022-02-26
  • 2021-11-12
  • 2021-06-19
相关资源
相似解决方案