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