当前位置:网站首页>Flask connects to existing tables in MySQL database
Flask connects to existing tables in MySQL database
2022-07-27 16:04:00 【fresh_ nam】
List of articles
Preface
flask Is based on python Of , More popular web frame , Want to do web Development inevitably needs to interact with the database , Now learn flask How to connect to the database .
One 、 Download related packages
download flask:
pip install flask
flask Specialized sql Processing packages , Use the following command to download :
pip install flask-sqlalchemy
Two 、 Connect to database
Import related packages and create flask example
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# establish Flask example
app = Flask(__name__)
Then connect to the database and create database objects :
# Write about yourself mysql Username 、 password 、 Host name 、 Port and database name
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://username:[email protected]:port/db"
# Dynamically track database changes . Poor performance . And will be removed in future versions . At present, it is only written to solve the prompt of the console
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
# Create database objects
db = SQLAlchemy(app)
Finally, get the data of a table in the database :
from flask import jsonify
@app.route('/')
def db_test():
dict_show = {
} # Define dictionary for data presentation
# Reflect existing tables in the database , And get all existing table objects .
db.reflect()
# Get all table names
all_table = {
table_obj.name: table_obj for table_obj in db.get_tables_for_bind()}
# obtain demo All data of table
all_data = db.session.query(all_table['demo'])
for data in all_data:
print(data) # View the data
dict_show[data[0]] = [data[1], data[2]]
# Translate the dictionary into json data
return jsonify(dict_show)
Finally check the results :
You can see demo All the data in the table , Be accomplished !
The last attached demo Complete code for :
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
# establish Flask example
app = Flask(__name__)
# Write about yourself mysql Username 、 password 、 Host name 、 Port and database name
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://username:[email protected]:port/db"
# Dynamically track database changes . Poor performance . And will be removed in future versions . At present, it is only written to solve the prompt of the console
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
# Create database objects
db = SQLAlchemy(app)
@app.route('/')
def db_test():
dict_show = {
} # Define dictionary for data presentation
# Reflect existing tables in the database , And get all existing table objects .
db.reflect()
# Get all table names
all_table = {
table_obj.name: table_obj for table_obj in db.get_tables_for_bind()}
# obtain demo All data of table
all_data = db.session.query(all_table['demo'])
for data in all_data:
print(data) # View the data
dict_show[data[0]] = [data[1], data[2]]
return jsonify(dict_show)
if __name__ == '__main__':
app.run(debug=True)
边栏推荐
- [tensorboard] oserror: [errno 22] invalid argument processing
- Zhaoqi scientific innovation and entrepreneurship competition planning and undertaking organization, mass entrepreneurship and innovation platform, project landing and docking
- Mlx90640 infrared thermal imager temperature sensor module development notes (VII)
- [regular expression] matching grouping
- [sword finger offer] interview question 56-i: the number of numbers in the array I
- 解决openwrt package目录下多个文件夹重名编译警告(call subdir 函数)
- Paper_Book
- Keil implements compilation with makefile
- 实现浅拷贝和深拷贝+
- [sword finger offer] interview question 46: translating numbers into strings - dynamic programming
猜你喜欢

drf使用:get请求获取数据(小例子)

数据表的约束以及设计、联合查询——8千字攻略+题目练习解答

Embedded development: tips and techniques -- seven techniques to meet the real-time deadline

leetcode234题-简单方法判断回文链表

C language: minesweeping games

leetcode25题:K 个一组翻转链表——链表困难题目详解

单机高并发模型设计

剑指 Offer 51. 数组中的逆序对

使用transform:translate()出现内容模糊问题

Three uses of static keyword
随机推荐
openwrt 编译驱动模块(在openwrt源代码外部任意位置编写代码,独立模块化编译.ko)
Ncnn reasoning framework installation; Onnx to ncnn
43亿欧元现金收购欧司朗宣告失败!ams表示将继续收购
[sword finger offer] interview question 41: median in data flow - large and small heap implementation
Clickhouse 20.x distributed table testing and chproxy deployment (II)
兆骑科创创业大赛策划承办机构,双创平台,项目落地对接
网络原理(1)——基础原理概述
SQL multi table query
synchronized和ReentrantLock的区别
Talk about ThreadLocal
UDP 的报文结构和注意事项
Single machine high concurrency model design
Understand │ what is cross domain? How to solve cross domain problems?
网络层的IP协议
C语言实现字节流与十六进制字符串的相互转换
It is said that the US government will issue sales licenses to Huawei to some US enterprises!
无线网络分析有关的安全软件(aircrack-ng)
[sword finger offer] interview question 54: the k-largest node of the binary search tree
Catalog component design and custom extended catalog implementation in spark3
[sword finger offer] interview question 52: the first common node of two linked lists - stack, hash table, double pointer