Python?flask?sqlalchemy的簡單使用及常用操作
前言
說到面向?qū)ο?,大家都不陌生。關(guān)系型數(shù)據(jù)庫也是后端日常用來存儲數(shù)據(jù)的,但數(shù)據(jù)庫是關(guān)系型的,因此,ORM通過對象模型和數(shù)據(jù)庫的關(guān)系模型之間建立映射,我們就能像操作對象一樣來操作數(shù)據(jù)庫。 ORM的優(yōu)點主要是面向?qū)ο缶幊蹋恍鑼懺鶶QL,用操作對象的方式訪問數(shù)據(jù)。當然,缺點就是當遇到復雜的操作時,ORM就不那么好寫了,還有就是加了一層映射,執(zhí)行效率低于原生sql。不過,對于大部分項目來說,這些缺點都是可以接受的。犧牲的性能可以接受;有復雜操作時,實現(xiàn)就用原生SQL,ORM執(zhí)行罷了。
flask sqlalchemy的配置使用
在python中,常用的ORM工具就是sqlalchemy了。下面就以一個簡單的flask例子來說明吧。
首先,寫一個最簡單的flask項目,代碼如下:
from flask import Flask app = Flask(__name__) @app.route('/') def orm_test(): return "hello"
接下來我們導入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了。
- 然后我們新增一個表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ù)源只有一個庫的時候,但很多時候我們還需要訪問別的庫,這時需要在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='字段釋義')
最后,我們在接口中使用下ORM。
@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"
當我們遇到復雜操作,不知道ORM語法該怎么寫時,還可以直接用原生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時,對于語法不熟悉,寫代碼也是比較痛苦的。這里總結(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é)
我們在工程代碼中使用sqlalchemy時,在配置時記得根據(jù)實際情況添加相關(guān)配置參數(shù),比如連接池的數(shù)量、自動回收連接的秒數(shù)等等。
到此這篇關(guān)于Python flask sqlalchemy的簡單使用及常用操作的文章就介紹到這了,更多相關(guān)Python flask sqlalchemy內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python?ORM框架之SQLAlchemy?的基礎(chǔ)用法
- python flask sqlalchemy連接數(shù)據(jù)庫流程介紹
- python sqlalchemy動態(tài)修改tablename兩種實現(xiàn)方式
- Python+SQLAlchemy輕松實現(xiàn)管理數(shù)據(jù)庫
- Python SQLAlchemy簡介及基本用法
- 3個Python?SQLAlchemy數(shù)據(jù)庫操作功能詳解
- Python使用SQLAlchemy模塊實現(xiàn)操作數(shù)據(jù)庫
- Python?SQLAlchemy與數(shù)據(jù)庫交互操作完整指南
- Python?SQLAlchemy庫的實現(xiàn)示例
相關(guān)文章
python 設(shè)置xlabel,ylabel 坐標軸字體大小,字體類型
這篇文章主要介紹了python 設(shè)置xlabel,ylabel 坐標軸字體大小,字體類型,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07解決python中畫圖時x,y軸名稱出現(xiàn)中文亂碼的問題
今天小編就為大家分享一篇解決python中畫圖時x,y軸名稱出現(xiàn)中文亂碼的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01pyenv與virtualenv安裝實現(xiàn)python多版本多項目管理
這篇文章主要介紹了pyenv與virtualenv安裝實現(xiàn)python多版本多項目管理過程,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08詳解python數(shù)組中的符號...與:符號的不同之處
這篇文章主要介紹了詳解python數(shù)組中的符號...與:符號的不同之處,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03