1. 程式人生 > >flask web開發(四) web表單 csrf,重定向

flask web開發(四) web表單 csrf,重定向

# -*- coding: cp936 -*- import os import sys import logging.config import flask import socket from flask import Flask,jsonify from flask import request from flask import abort from flask import redirect from flask import make_response from flask_wtf import Form from flask import render_template,session,url_for,flash from wtforms import StringField,SubmitField from wtforms.validators import Required from flask_bootstrap import Bootstrap   app = Flask(__name__)app.config['SECRET_KEY']='hard to guess string'

#需要再寫個檔案 app.config.from_pyfile('config.py') #內容為 SECRET_KEY = 'hard to guess string' # 程式設定金鑰,flask-wtf使用金鑰生成加密令牌,防止CSRF,即跨站請求偽造的攻擊

bootstrap=Bootstrap(app)app.config.from_pyfile('config.py')

class NameForm(Form):     name=StringField('What is your name?',validators=[Required()])     submit=SubmitField('Submit')

  @app.route('/',methods=['GET','POST']) def index():     #name=None     form=NameForm()     if form.validate_on_submit():         #name=form.name.data         #form.name.data=''         session['name']=form.name.data         return redirect(url_for('index'))     #return render_template('user.html',form=form,name=name)     return render_template('user.html',form=form,name=session.get('name'))                                                                                                                                                      if __name__ == "__main__":     ip='0.0.0.0'     app.run( host=ip,port=5000,debug=False )

user.html  

{%  extends "base45.html" %}{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Flasky{% endblock %}

{% block page_content %} <div class="page-header">     <h1>Hello,{% if name %}{{name}}{% else %} Strange!{% endif %}</h1> </div>{{wtf.quick_form(form)}} {% endblock %}