含有flask的校验form
main.py
from flask import Flask
from flask import request
from flask import render_template
from flask import redirect
from model import *
# app=Flask(__name__) # 此处要注销, 否则报错KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'
# 今天新搭建了一个框架, 总是遇到KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'这个错误.
# 查了很多,有的说降低版本pip install Flask-SQLAlchemy==2.1
# 最终再stackoverflow上查到了解决办法,就是犯了一个很蠢的问题,app = Flask(__name__)出现了两次。。。
# 如果谁遇到这个问题
# 1. 可以先查看一下是否一个项目初始化了两次app = Flask(__name__)
# 2. 然后降低下版本pip install Flask-SQLAlchemy==2.1
# 原文链接:https://blog.csdn.net/suzimuyu99/article/details/100036148
from wtforms import Form,TextField,PasswordField,validators
import MySQLdb
class LoginForm(Form):
username = TextField("username",[validators.Required()])
password = PasswordField("password",[validators.Required()])
class PublishForm(Form):
content = TextField("content",[validators.Required()])
sender = TextField("sender",[validators.Required()])
@app.route("/register",methods=['GET','POST'])
def register():
myForm=LoginForm(request.form)
if request.method=='POST':
u = User(myForm.username.data,myForm.password.data)
a = u.add()
print(a)
return redirect("http://www.jikexueyuan.com")
return render_template('index.html',form=myForm)
@app.route("/login",methods=['GET','POST'])
def login():
myForm=LoginForm(request.form)
if request.method =='POST':
u= User(myForm.username.data, myForm.password.data)
if (u.isExisted()):
return redirect("http://www.jikexueyuan.com")
else:
return "Login Failed"
return render_template('index.html',form=myForm)
@app.route("/show",methods=['GET','POST'])
def show():
myEntryForm = PublishForm(request.form)
l = getAllEntry()
if request.method =='POST':
e = Entry(myEntryForm.content.data,myEntryForm.sender.data)
e.add()
return render_template("show.html",entries=l,form=myEntryForm)
return render_template("show.html",entries=l,form=myEntryForm)
if __name__=="__main__":
app.run(port=8080,debug=True)
model.py
# model.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:666@10.0.0.105:3306/flask_test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # 这个配置一定要有,否则也是报错
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(32),unique=True)
password = db.Column(db.String(32))
def __init__(self,username,password):
self.username = username
self.password = password
def add(self):
try:
db.session.add(self)
db.session.commit()
return self.id
except Exception as e:
print('chucuol')
db.session.rollback()
return e
finally:
return 0
def isExisted(self):
temUser=User.query.filter_by(username=self.username,password=self.password).first()
if temUser is None:
return 0
else:
return 1
def getAllEntry():
Entlist=[]
Entlist=Entry.query.filter_by().all()
return Entlist
class Entry(db.Model):
id = db.Column(db.Integer,primary_key=True) # primary_key就会自增
content = db.Column(db.Text)
sender = db.Column(db.String(32))
def __init__(self,content,sender):
self.content = content
self.sender = sender
def add(self):
try:
db.session.add(self)
db.session.commit()
return self.id
except Exception as e:
db.session.rollback()
return e
finally:
return 0
if __name__ == '__main__':
# 清除数据库里的所有数据(第一次使用时用,清除数据库中是脏数据)
# db.drop_all()
# 创建所有的表
# db.create_all()
user1 = User('wang15', '123456')
user2 = User('wang16', '1234567')
a = user1.add()
b = user2.add()
e1 = Entry('wang16', '123456')
e2 = Entry('wang17', '1234567')
a = e1.add()
b = e2.add()
migrate.py
# _*_ encoding: utf-8 _*_ @author: ty hery 2019/12/20
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, EqualTo
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand
app = Flask(__name__)
manager = Manager(app)
app.config['SQLALCHEMY_DATABASE_URL'] = 'mysql://root:666@127.0.0.1/flask_test'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
# 第一个参数是Flask的实例,第二个参数是Sqlalchemy数据库实例,创建flask脚本管理工具
migrate = Migrate(app, db)
# managet是Flask-Script的实例,这条语句在flask_Script中添加一个db命令
manager.add_command('db', MigrateCommand)
# 定义模型Role
class Role(db.Model):
# 定义表名
__table__ = 'roles2'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(64),unique=True)
def __repr__(self):
return 'Role:'.format(self.name)
# 定义模型用户
class User(db.Model):
# 定义表名
__table__ = 'users2'
id = db.Colunm(db.Integer,pramary_key=True)
username = db.Column(db.string(64),unique=True,index=True)
def __repr__(self):
return 'User:'.format(self.username)
if __name__ =="__main__":
manager.run()
原始sql
import MySQLdb
conn = MySQLdb.connect("10.0.0.105","root","666","flask_test")
cur = conn.cursor()
def insert(username,password):
sql = "insert into user (username,password) values ('%s','%s')" %(username,password)
cur.execute(sql)
conn.commit()
conn.close()
def isExisted(username,password):
#sql="select * from user where username ='%s' and password ='%s'" %(username,password)
sql="select * from user where username ="+username+" and password ="+password
cur.execute(sql)
result = cur.fetchall()
if (len(result) == 0):
return False
else:
return True
insert("nihao",'asdfdsaf')
'''
username = 1
password = 1 or 1 = 1
select * from user where username = 1 and password =1 or 1 = 1
'''
写入自己的博客中才能记得长久