标签:验证 ble values mysql 模块 where 输入 插入 else
Flask中使用mysql
先安装相关模块:
pip install Flask-MySQL
先准备一下数据库
登录:
mysql -u root -p
创建Database和创建Table
mysql> CREATE DATABASE EmpData;
mysql> use EmpData;
mysql> CREATE TABLE User(
userId INT NOT NULL AUTO_INCREMENT,
userName VARCHAR(100) NOT NULL,
password VARCHAR(40) NOT NULL,
PRIMARY KEY(userId)
);
插入数据:
mysql> insert into User values(‘‘,‘Admin‘,‘admin‘);
现在,让我们回到hello.py并尝试使用flask-mysql连接MySQL。 首先,通过在hello.py中导入它来初始化扩展,如下所示:
from flask import Flask
from flaskext.mysql import MySQL
mysql = MySQL()
app = Flask(__name__)
app.config[‘MYSQL_DATABASE_USER‘] = ‘root‘
app.config[‘MYSQL_DATABASE_PASSWORD‘] = ‘root‘
app.config[‘MYSQL_DATABASE_DB‘] = ‘EmpData‘
app.config[‘MYSQL_DATABASE_HOST‘] = ‘localhost‘
mysql.init_app(app)
@app.route("/")
def hello():
return "Welcome to Python Flask App!"
if __name__ == "__main__":
app.run()
我们将使用cuesor从数据库访问数据,可以使用mysql对象创建一个。我们还可以添加一个叫Authenticate的方法,来验证登录过程,所以添加下面代码:
@app.route("/Authenticate")
def Authenticate():
username = request.args.get(‘UserName‘)
password = request.args.get(‘Password‘)
cursor = mysql.connect().cursor()
cursor.execute("SELECT * from User where Username=‘" + username + "‘ and Password=‘" + password + "‘")
data = cursor.fetchone()
if data is None:
return "Username or Password is wrong"
else:
return "Logged in successfully"
测试
python hello.py
假如我们在浏览器输入了错误的数据库数据(UserName和Password),比如:
http://127.0.0.1:5000/Authenticate?UserName=jay&Password=jay
浏览器会提示错误:
Username or Password is wrong
输入数据库内的数据:
http://127.0.0.1:5000/Authenticate?UserName=Admin&Password=admin
显示:
Logged in successfully.
不过前面都只是简单的操作数据库,如果没有配合参数过滤,容易遇到sql注入的危险,应该注意
标签:验证 ble values mysql 模块 where 输入 插入 else
原文地址:http://www.cnblogs.com/simonid/p/6353862.html