Home Backend Development Python Tutorial Detailed explanation of examples connecting flask and mysql (python)

Detailed explanation of examples connecting flask and mysql (python)

Apr 26, 2017 am 11:09 AM
flask mysql python

The birth of a web application based on flask is the fourth article. This article mainly introduces how to interconnect flask and mysql. It has certain reference value. Interested friends can refer to

Chapter 1 implements part of the login function. The reason why it is called a partial function is because it is definitely not allowed to write the user name and password as fixed values. A whole function requires at least registration, login, password modification, etc., which requires providing a The ability to store these values ​​into the database.

The current mainstream databases are divided into two types, namely relational databases and NoSql databases. For small and medium-sized systems, the performance and ease of use of the two databases are equivalent, and they are both good choices.

Basic configuration

The flask integration package of the SQLAlchemy database framework, flask-SQLAlchemy, is used here to perform database operations.

SQLAlchemy is a very good framework that simplifies database operations. It provides high-level ORM and low-level SQL functions, which is very convenient to use.

The installation method is the same as the previous type, or the pip command:

pip3.6 install flask-sqlalchemy
Copy after login

After the installation is completed, modify the default configuration part, first import the package:

from flask.ext.sqlalchemy import SQLAlchemy
Copy after login

Then configure the link string:

app.config["SQLALCHEMY_DATABASE_URI"]='mysql://root:1234@localhost/cblog'
Copy after login

Configure automatic commit of changes after the request is completed:

app.config["SQLALCHEMY_COMMIT_ON_TEARDOWN"]=True
Copy after login

Instantiate SQLAlchemy:

db=SQLAlchemy(app)
Copy after login

Model settings

After the installation is complete, continue to improve the login example, modify the default.py file, and add the User model (class) and Role model (to show association)

Role class

class Role(db.Model): #需继承模型
 __tablename__="roles" #db中表明,如果不设置,则会与class同的默认名
 id=db.Column(db.Integer,primary_key=True) #SQLAlchemy要求必须有主键,一般命名为id即可
 name=db.Column(db.String(50),unique=True) #表示name为字符串,不重复
 users=db.relationship("User",backref='role') #关联user模型,并在user中添加反向引用(backref)
Copy after login

User class

class User(db.Model):
 __tablename__="users"
 id=db.Column(db.Integer,primary_key=True)
 username=db.Column(db.String(50),unique=True,index=True) #此列带索引
 password=db.Column(db.String(50))
 role_id=db.Column(db.Integer,db.ForeignKey("roles.id")) #外键指向roles表中的id列
Copy after login

The following needs to be considered how to execute it. It must be convenient and whether the logic code can be invaded. This is The requirements cannot be hard-coded into the logic code. For example, the code to determine the db status is passed as a parameter to app.run(). At this time, the shell comes in handy

Configuration script

If you want flask to support command line scripts, you first need to install the flask-script extension:

pip3.6 install flask-script
Copy after login

Modify the code of default.py:

from flask.ext.script import Manager
mamager=Manager(app)
....
if __name__=='__main__':
 #app.run(debug=True)
 mamager.run()
Copy after login

After modification, run it again :

python default.py
Copy after login

It was found that it did not run successfully, but there was a prompt:


You can see that parameters are required at the end, respectively shell (execution Script), runserver (start service) and help

Start the service below:

python default.py runserver
Copy after login

Service successfully executed

More database configuration

But at this time, when accessing the site (127.0.0.1:5000), a 500 error will appear, indicating that there is no mysql module. Why is this? Obviously the reason is that the mysql driver is not installed. Use the pip command to install the driver:

pip3.6 install MySQL-python
Copy after login

An error is found and the displayed content is (only win system here):

According to the prompts, install the c++ tool package and follow the download address on the prompts

landinghub.visualstudio.com/visual-cpp-build-tools

After the download is completed, it will be directly an exe file , install

After restarting, I installed MySQL-python and found that it was still not possible. After going through Baidu, I found that the MySQLdb library only supports up to python2.7 and no longer supports 3.x. Then I have to use other methods. Use PyMySQL library:

pip3.6 install PyMySQL
Copy after login

Then modify the code of default.py and add two lines:

import pymysql
pymysql.install_as_MySQLdb()
Copy after login

Enter the source code and pay attention to this line:

sys.modules["MySQLdb"] = sys.modules["_mysql"] = sys.modules["pymysql"]
Copy after login

You can successfully use and connect to mysql.
Enter the connection in the browser and enter the site correctly.

Next, use shell to create the database table and enter the root directory of default.py:

python default.py shell
from default import db
db.create_all()
Copy after login

If no error is reported at this time, the database table should be created. :


Database migration

Then the problem comes. At this time, modify the model, yes It will not be reflected in the db, so what should I do if I modify it? For now, it is also very simple:

db.drop_all()
db.create_all()
Copy after login

But this is only used for debugging now. If there is already data in the db, this will definitely be unbearable. At this time, it is the turn of the database migration plug-in Migrate is here. The first thing is still the same. You need to install it:

pip3.6 install flask-migrate
Copy after login

As before, modify the default.py file for configuration after installation:

from flask.ext.migrate import Migrate,MigrateCommand
migrate=Migrate(app,db) #配置迁移
mamager.add_command("db",MigrateCommand) #配置迁移命令
Copy after login

Then use the init command to initialize the migration warehouse

 python default.py db init
Copy after login

The command line displays:


Then add the migrations directory:

indicates the migration file Initialization has been completed.

migrate框架提供了一些命令来进行迁移操作,分别为(使用default.py文件举例):

#根据差异创建迁移
python default.py db migrate -m "说明"
#改动差异 
python default.py db upgrade
#取消差异改动
python default.py db downgrade
Copy after login

回到表单

接下来看看登录如何与数据库关联起来,修改login方法内的代码:

@app.route("/login",methods=["POST"])
def loginPost():
 username=request.form.get("username","")
 password=request.form.get("password","")
 user=User.query.filter_by(username=username,password=password).first() #数据库查询
 if user is not None:
 session["user"]=username
 return render_template("/index.html",name=username,site_name='myblog')
 else:
 flash("您输入的用户名或密码错误")
 return render_template("/login.html") #返回的仍为登录页
Copy after login

执行结果非常完美。

一些总结

下面是一些关于python和db相连的总结性的东西

数据类型

列选项

数据库操作

查询过滤器

经过这几章,登录功能已经基本完成,在下一章中将讲解用户注册的相关功能。

The above is the detailed content of Detailed explanation of examples connecting flask and mysql (python). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to start the server with redis How to start the server with redis Apr 10, 2025 pm 08:12 PM

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

phpmyadmin connection mysql phpmyadmin connection mysql Apr 10, 2025 pm 10:57 PM

How to connect to MySQL using phpMyAdmin? The URL to access phpMyAdmin is usually http://localhost/phpmyadmin or http://[your server IP address]/phpmyadmin. Enter your MySQL username and password. Select the database you want to connect to. Click the "Connection" button to establish a connection.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

phpMyAdmin comprehensive use guide phpMyAdmin comprehensive use guide Apr 10, 2025 pm 10:42 PM

phpMyAdmin is not just a database management tool, it can give you a deep understanding of MySQL and improve programming skills. Core functions include CRUD and SQL query execution, and it is crucial to understand the principles of SQL statements. Advanced tips include exporting/importing data and permission management, requiring a deep security understanding. Potential issues include SQL injection, and the solution is parameterized queries and backups. Performance optimization involves SQL statement optimization and index usage. Best practices emphasize code specifications, security practices, and regular backups.

See all articles