当前位置:网站首页>(07) flask is OK if you have a hand -- flask Sqlalchemy
(07) flask is OK if you have a hand -- flask Sqlalchemy
2022-07-27 12:23:00 【Free little ice】
zero 、 Preface
This article , Elaborate on Flask in Database ORM Use

install
Use it directly pip install flask-sqlalchemy that will do
Use
initialization
Use ORM So that we don't have to write complicated SQL sentence
Database we use Python Self contained sqlite3 This does not require installation .
establish exts.py file , Write the following :
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
The code above means : Create a SQLAlchemy object
establish models.py file , Write the following :
from exts import db
class User(db.Model):
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(80),unique=True)
def __repr__(self):
return '<User %s>' % self.username
The code above means : Create a user model , In terms of our operation
Finally create app.py file , Write the following :
from flask import Flask, jsonify
from exts import db
from models import User
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///foo.db"
db.init_app(app)
The code above means :
Combine our database with flask_appBinding .
The address of the database is : In the current directory foo.db file
thus , The initial operation of the database has been completed .
Smart little buddy is about to ask , Why not exts.py and app.py Merged ?
answer : If after the merger , that models.py Will quote SQLAlchemy object , and app.py And from models.py I quote User object , This will cause a circular reference problem .
Additions and deletions
@app.route('/create_table')
def create_table():
db.create_all()
return f" The database has been created successfully "
@app.route('/create/<name>')
def create(name):
user = User(username=name)
db.session.add(user)
db.session.commit()
return f" user {
name} Created successfully "
@app.route('/query/all')
def query_all():
users = User.query.all()
data = {
"all user": str(users)}
return jsonify(data)
@app.route('/query_by/<name>')
def query_by_name(name):
user = User.query.filter_by(username=name).first()
data = {
"user": str(user)}
return jsonify(data)
@app.route('/delete_by/<name>')
def delete_by_name(name):
user = User.query.filter_by(username=name).first()
db.session.delete(user)
db.session.commit()
return " user : Delete successful "
- First you need to visit
create_tableTo create a database - And then you can go through
create/xiaobingCreate a small soldier user - adopt
query_allQuery all users - adopt
delete_by/xiaobingDelete the soldier user
Extended literature
边栏推荐
- 虚拟偶像的歌声原来是这样生成的!
- Sword finger offer notes: t58 - ii Rotate string left
- mysql8msi安装教程(数据库mysql安装教程)
- Leetcode 02: sword finger offer 58 - I. flip the word order (simple); T123. Verify palindrome string; T9. Palindromes
- Go Beginner (4)
- Sword finger offer notes: t57 - ii Continuous positive sequence with sum s
- B 站 713 事故后的多活容灾建设|TakinTalks 大咖分享
- Principle, concept and construction process of MySQL database master-slave replication cluster
- go入门篇 (5)
- CMD Chinese garbled code solution
猜你喜欢
Ali II: what if the AOF file in redis is too large?

Image segmentation vs Adobe Photoshop (PS)

Iptables firewall

Alibaba cloud RDS exception during pool initialization

Idea: can't use subversion command line client: SVN solution

Go replace with local code

JS parasitic combinatorial inheritance

解决方案:idea project没有显示树状图

JVM memory model

广东:剧本杀等新行业新业态场所,消防安全监管不再“缺位”
随机推荐
go入门篇 (4)
JS-寄生组合式继承
JVM memory model
Docker MySQL Usage Note
Does the service layer need an interface
Strictly control outdoor operation time! Foshan housing and Urban Rural Development Bureau issued a document: strengthening construction safety management during high temperature
How to design a secure external interface
Chapter 12 generics
解决方案:Can not issue executeUpdate() or executeLargeUpdate() for SELECTs
Plus SBOM: assembly line BOM pbom
浪潮之巅——读书笔记+摘录+感悟
NPM step pit
上半年火灾起数下降27.7%,广东将这样提升全民消防安全素质
【数据库数据恢复】SQL Server数据库所在磁盘分区空间不足报错的数据恢复案例
npm踩坑
2021-3-17-byte-hu Pai
20210422 consolidation interval
Chapter 8 multithreading
CLS monitoring alarm: ensure high availability of online services in real time
Current situation and development trend of accounting computerization