flask數(shù)據(jù)庫序列化操作實(shí)例探究
什么是序列化?
在ORM(對象關(guān)系映射)中,序列化是一個將數(shù)據(jù)庫中的數(shù)據(jù)模型對象轉(zhuǎn)化為適合在網(wǎng)絡(luò)傳輸或存儲(如JSON、XML等格式)的過程。簡單來說,就是將數(shù)據(jù)庫表的一行記錄轉(zhuǎn)換為易于傳輸和理解的數(shù)據(jù)結(jié)構(gòu)。
序列化的作用就在于此:它能夠?qū)⒁粋€或多個數(shù)據(jù)庫模型對象轉(zhuǎn)換成JSON字符串或其他可傳輸格式。這個過程中,ORM框架提供的序列化功能會遍歷模型對象的所有屬性,并按照指定的規(guī)則(如日期時間格式、字段篩選等)進(jìn)行轉(zhuǎn)換。
Marshmallow是Python中廣泛使用的序列化與驗(yàn)證庫,而SQLAlchemyAutoSchema則是Marshmallow的一個擴(kuò)展,專門用于處理SQLAlchemy定義的模型。當(dāng)我們的數(shù)據(jù)模型通過SQLAlchemy定義后,就可以借助SQLAlchemyAutoSchema將其映射為可序列化的schema。
好了,話不多說,直接上代碼:
安裝序列化庫
首先我們需要安裝序列化庫
pip install marshmallow_sqlalchemy,marshmallow
定義一個數(shù)據(jù)庫模型
我們需要先定義一個數(shù)據(jù)庫模型(大家可以把看成是一張數(shù)據(jù)庫表結(jié)構(gòu))
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() # 定義一個數(shù)據(jù)庫表結(jié)構(gòu)的數(shù)據(jù)模型 class AssetModel(db.Model): __tablename__ = 'asset' id = db.Column(db.Integer, primary_key=True, autoincrement=True) init_date = db.Column(db.String(30), nullable=False) username = db.Column(db.String(20), nullable=False) account = db.Column(db.String(20), nullable=False) update_time = db.Column(db.DateTime, nullable=False) def __init__(self, username, init_date,account, update_time): self.username = username self.init_date = init_date self.account = account self.update_time = str(update_time) 3、接著我們開始定義一個序列化器 from models.assetmodel import AssetModel from marshmallow_sqlalchemy import SQLAlchemyAutoSchema from marshmallow import EXCLUDE,validate,fields class AssetSerializer(SQLAlchemyAutoSchema): class Meta: model = AssetModel # 配置對應(yīng)的模型 ordered = True # 設(shè)置是否排序 include_fk = True # 是否包含外鍵 unknown = EXCLUDE # 未知字段序列化選項(xiàng) # exclude = ("name",) # 序列化不需要的字段,反之對應(yīng)的是include
定義一個序列化器
from models.assetmodel import AssetModel from marshmallow_sqlalchemy import SQLAlchemyAutoSchema from marshmallow import EXCLUDE,validate,fields class AssetSerializer(SQLAlchemyAutoSchema): class Meta: model = AssetModel # 配置對應(yīng)的模型 ordered = True # 設(shè)置是否排序 include_fk = True # 是否包含外鍵 unknown = EXCLUDE # 未知字段序列化選項(xiàng) # exclude = ("name",) # 序列化不需要的字段,反之對應(yīng)的是include
序列化器的使用
from models.assetmodel import AssetModel,AssetSerializer testdata_blueprint = Blueprint('testdata', __name__, url_prefix='/TestData') @testdata_blueprint.route('/testdata', methods=['GET']) def get_testdata_list(): # 獲取當(dāng)前查詢頁碼,默認(rèn)為:1 page = request.args.get('page',1,type=int) # 獲取每頁顯示記錄數(shù),默認(rèn)是20 limit = request.args.get('limit',20,type=int) # 獲取查詢的資產(chǎn)賬號 account = request.args.get('account',type=int) # 計算當(dāng)前頁,開始的記錄編號 start = (page - 1) * limit # 計算當(dāng)前頁,結(jié)束的記錄編號; end = start + limit # 分頁查詢 items = AssetModel.query.slice(start, end) # 獲取記錄總數(shù) total = AssetModel.query.count() # 將查詢結(jié)果進(jìn)行序列化 items = AssetSerializer().dump(items,many=True) # 記得帶上many=True參數(shù),否則查詢結(jié)果為空 # 將結(jié)果轉(zhuǎn)成json結(jié)構(gòu)進(jìn)行返回 return jsonify({ 'code': 20000, 'msg': 'success', 'data': { 'items': items, 'total':total } })
通過上面的內(nèi)容,不知道大家有沒有留意到,我們根據(jù)查詢條件查詢數(shù)據(jù)庫表然后將數(shù)據(jù)記錄返回,這個過程我們并沒有寫查詢的sql語句,如select * from table_name where account='abc';這就是ORM框架中的序列化的作用,可以幫我們方便快捷地獲取到想要查詢的數(shù)據(jù),并且不需要我們手動將sql查詢結(jié)果整理成列表等數(shù)據(jù)結(jié)構(gòu),這大大提高了我們的開發(fā)效率。
以上就是flask數(shù)據(jù)庫序列化操作實(shí)例探究的詳細(xì)內(nèi)容,更多關(guān)于flask數(shù)據(jù)庫序列化操作的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Pytorch 多維數(shù)組運(yùn)算過程的索引處理方式
今天小編就為大家分享一篇Pytorch 多維數(shù)組運(yùn)算過程的索引處理方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12pandas調(diào)整列的順序以及添加列的實(shí)現(xiàn)
這篇文章主要介紹了pandas調(diào)整列的順序以及添加列的實(shí)現(xiàn)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03pytorch查看網(wǎng)絡(luò)參數(shù)顯存占用量等操作
這篇文章主要介紹了pytorch查看網(wǎng)絡(luò)參數(shù)顯存占用量等操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05