Using MySQL in flask

Source: Internet
Author: User
Tags mysql import

Using MySQL in flask

Install the relevant module first :

Pip Install Flask-mysql

Prepare the database First

Login:

Mysql-u root-p

Create DATABASE and CREATE 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‘);
Now, let's go back to hello.py and try using Flask-mysql to connect to MySQL. First, initialize the extension by importing it in hello.py, as follows:
from flask import Flaskfrom 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注入的危险,应该注意

Using MySQL in flask

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.