Python?flask?sqlalchemy的簡(jiǎn)單使用及常用操作
前言
說到面向?qū)ο?,大家都不陌生。關(guān)系型數(shù)據(jù)庫也是后端日常用來存儲(chǔ)數(shù)據(jù)的,但數(shù)據(jù)庫是關(guān)系型的,因此,ORM通過對(duì)象模型和數(shù)據(jù)庫的關(guān)系模型之間建立映射,我們就能像操作對(duì)象一樣來操作數(shù)據(jù)庫。 ORM的優(yōu)點(diǎn)主要是面向?qū)ο缶幊?,不需寫原生SQL,用操作對(duì)象的方式訪問數(shù)據(jù)。當(dāng)然,缺點(diǎn)就是當(dāng)遇到復(fù)雜的操作時(shí),ORM就不那么好寫了,還有就是加了一層映射,執(zhí)行效率低于原生sql。不過,對(duì)于大部分項(xiàng)目來說,這些缺點(diǎn)都是可以接受的。犧牲的性能可以接受;有復(fù)雜操作時(shí),實(shí)現(xiàn)就用原生SQL,ORM執(zhí)行罷了。
flask sqlalchemy的配置使用
在python中,常用的ORM工具就是sqlalchemy了。下面就以一個(gè)簡(jiǎn)單的flask例子來說明吧。
首先,寫一個(gè)最簡(jiǎn)單的flask項(xiàng)目,代碼如下:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def orm_test():
return "hello"接下來我們導(dǎo)入ORM配置,添加如下代碼:
from flask_sqlalchemy import SQLAlchemy
def orm_config():
url = "mysql+mysqlconnector://{user}:{pwd}@{host}:{port}/{db_name}?charset=utf8"
orm_conf = {
'SQLALCHEMY_DATABASE_URI': url
}
return orm_conf
# ORM 設(shè)置
app.config.from_mapping(orm_config)
db = SQLAlchemy(app)這樣我們就將ORM配置OK了。
- 然后我們新增一個(gè)表table1的model
# model表名
class Table1(db.Model):
# 表名
__tablename__ = "table1"
id = db.Column(db.Integer, primary_key=True)
col = db.Column(db.String(64), nullable=False, unique=True, comment='字段釋義')以上配置這是在數(shù)據(jù)源只有一個(gè)庫的時(shí)候,但很多時(shí)候我們還需要訪問別的庫,這時(shí)需要在ORM配置和model上做一些設(shè)置。
ORM配置中需要用到SQLALCHEMY_BINDS來添加數(shù)據(jù)庫, model中__bind_key__來指定數(shù)據(jù)庫了。
具體修改如下:
修改ORM配置:
def orm_config():
url = "mysql+mysqlconnector://{user}:{pwd}@{host}:{port}/{db_name}?charset=utf8"
# 指定的別庫
other_url = "mysql+mysqlconnector://{user1}:{pwd1}@{host1}:{port1}/{db_name1}?charset=utf8"
orm_conf = {
'SQLALCHEMY_DATABASE_URI': url,
# 添加別庫
"SQLALCHEMY_BINDS":{
"other_db":other_url
},
}
return orm_conf表model指定庫:
class Table2(db.Model):
# 指定別庫
__bind_key__ = 'other_db'
__tablename__ = "table2"
id = db.Column(db.Integer, primary_key=True)
col = db.Column(db.String(64), nullable=False, unique=True, comment='字段釋義')最后,我們?cè)诮涌谥惺褂孟翺RM。
@app.route('/')
def orm_test():
# 查詢table1數(shù)據(jù)
rows = Table1.query.filter(Table1.id<5)
res = []
for row in rows:
dict = {
"id": row.id,
"col": row.col
}
res.append(dict)
return "hhh"當(dāng)我們遇到復(fù)雜操作,不知道ORM語法該怎么寫時(shí),還可以直接用原生sql + ORM session execute的方式執(zhí)行,示例如下:
sql = "select count(*) as cnt from table1 group by col" rows = db.session.execute(sql)
以上例子我們是查詢table1表的id<5的數(shù)據(jù)。
完整代碼如下:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
def orm_config():
url = "mysql+mysqlconnector://{user}:{pwd}@{host}:{port}/{db_name}?charset=utf8"
other_url = "mysql+mysqlconnector://{user1}:{pwd1}@{host1}:{port1}/{db_name1}?charset=utf8"
orm_conf = {
'SQLALCHEMY_DATABASE_URI': url,
"SQLALCHEMY_BINDS":{
"other_db":other_url
},
}
return orm_conf
# ORM 設(shè)置
app.config.from_mapping(orm_config)
db = SQLAlchemy(app)
# model表名
class Table1(db.Model):
# 表名
__tablename__ = "table1"
id = db.Column(db.Integer, primary_key=True)
col = db.Column(db.String(64), nullable=False, unique=True, comment='字段釋義')
class Table2(db.Model):
# 指定庫
__bind_key__ = 'other_db'
__tablename__ = "table2"
id = db.Column(db.Integer, primary_key=True)
col = db.Column(db.String(64), nullable=False, unique=True, comment='字段釋義')
@app.route('/')
def orm_test():
# 查詢table1數(shù)據(jù)
rows = Table1.query.filter(Table1.id<5)
res = []
for row in rows:
dict = {
"id": row.id,
"col": row.col
}
res.append(dict)
return "hhh"
if __name__ =="__main__":
app.run()sqlalchemy的增刪改查
剛開始接觸sqlalchemy時(shí),對(duì)于語法不熟悉,寫代碼也是比較痛苦的。這里總結(jié)下sqlalchemy常用的語法吧。
查詢數(shù)據(jù)
# 查詢id<5的數(shù)據(jù)
q = Table1.query.filter(Table1.id<5)
# 查詢過濾用 and、or
from sqlalchemy import and_, or_
q = Table1.query.filter(and_(Table1.id<5, Table1.col=='掘金'))
q = Table1.query.filter(or_(Table1.id<5, Table1.col=='掘金'))
# 查詢過濾用in(語法:model.{字段名}.in_({列表}))
q = Table1.query.filter(Table1.id.in_([1,2,3]))
# 連表查詢
q = Table1.query.join(Table2, Table2.id==Table1.id) \
.filter(Table1.id<5)
# 解析數(shù)據(jù)
res = {'data': [dict(i) for i in q]}
# 查詢數(shù)據(jù)count
count = q.count()增加數(shù)據(jù)
row = Table1(id=1, col='掘金') db.session.add(row) db.seesion.commit()
修改數(shù)據(jù)
row = Table1.query.filter(Table1.id<5)
update_data = {"col": "掘金"}
row.update(update_data)
db.session.commit()刪除數(shù)據(jù)
row = Table1.query.filter(Table1.id<5) row.delete() db.session.commit()
備注: 增刪改都要commit()
總結(jié)
我們?cè)诠こ檀a中使用sqlalchemy時(shí),在配置時(shí)記得根據(jù)實(shí)際情況添加相關(guān)配置參數(shù),比如連接池的數(shù)量、自動(dòng)回收連接的秒數(shù)等等。
到此這篇關(guān)于Python flask sqlalchemy的簡(jiǎn)單使用及常用操作的文章就介紹到這了,更多相關(guān)Python flask sqlalchemy內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python?ORM框架之SQLAlchemy?的基礎(chǔ)用法
- python flask sqlalchemy連接數(shù)據(jù)庫流程介紹
- python sqlalchemy動(dòng)態(tài)修改tablename兩種實(shí)現(xiàn)方式
- Python+SQLAlchemy輕松實(shí)現(xiàn)管理數(shù)據(jù)庫
- Python SQLAlchemy簡(jiǎn)介及基本用法
- 3個(gè)Python?SQLAlchemy數(shù)據(jù)庫操作功能詳解
- Python使用SQLAlchemy模塊實(shí)現(xiàn)操作數(shù)據(jù)庫
- Python?SQLAlchemy與數(shù)據(jù)庫交互操作完整指南
- Python?SQLAlchemy庫的實(shí)現(xiàn)示例
相關(guān)文章
如何使用python傳入不確定個(gè)數(shù)參數(shù)
這篇文章主要介紹了如何使用python傳入不確定個(gè)數(shù)參數(shù),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
python 設(shè)置xlabel,ylabel 坐標(biāo)軸字體大小,字體類型
這篇文章主要介紹了python 設(shè)置xlabel,ylabel 坐標(biāo)軸字體大小,字體類型,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
解決python中畫圖時(shí)x,y軸名稱出現(xiàn)中文亂碼的問題
今天小編就為大家分享一篇解決python中畫圖時(shí)x,y軸名稱出現(xiàn)中文亂碼的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01
pyenv與virtualenv安裝實(shí)現(xiàn)python多版本多項(xiàng)目管理
這篇文章主要介紹了pyenv與virtualenv安裝實(shí)現(xiàn)python多版本多項(xiàng)目管理過程,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08
python 實(shí)現(xiàn)從高分辨圖像上摳取圖像塊
今天小編就為大家分享一篇python 實(shí)現(xiàn)從高分辨圖像上摳取圖像塊,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01
詳解python數(shù)組中的符號(hào)...與:符號(hào)的不同之處
這篇文章主要介紹了詳解python數(shù)組中的符號(hào)...與:符號(hào)的不同之處,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03

