flask路由分模塊管理及自定義restful響應(yīng)格式詳解
一、flask路由分模塊管理
1.1、使用藍圖
在flask中可以使用藍圖Blueprint來進行創(chuàng)建路由進行分模塊。 具體操作,我們可以在項目根目錄下創(chuàng)建一個controller文件夾來存儲分模塊的路由。
在controller文件夾里創(chuàng)建product_controller.py,在里面如下寫法引入藍圖,并且注冊藍圖:
from flask import Blueprint
product_blue = Blueprint('product', __name__)
# 定義藍圖路徑及請求方法和請求返回邏輯
@product_blue.route('/get', methods=['get', 'post'])
def getproduct():
return 'product'
@product_blue.route('/search', methods=['get', 'post'])
def searchproduct():
return 'search'
那么我們在項目主邏輯文件main.py中,去引入并注冊這個藍圖:
from flask import Flask
from controller.product_controller import product_blue
app = Flask(__name__)
# 商品模塊
app.register_blueprint(product_blue, url_prefix='/product')
if __name__ == '__main__':
app.run()
接下來我們運行程序,可以看到如下效果:


可以看到我們使用藍圖分模塊的創(chuàng)建已經(jīng)生效了,這樣如果模塊對的話,我們就方便管理了。不會造成代碼全部冗余在一個主文件中。
1.2、使用flask_restful
那么相比與藍圖Blueprint,flask_restful的優(yōu)勢就在于它能夠做更多的操作,比如參數(shù)的驗證,返回直接字典就能解析成json。
首先我們輸入命令pip3 install flask_restful安裝flask_restful。 在product_controller中寫入如下代碼:
from flask_restful import Resource, reqparse
class ProductView(Resource):
@staticmethod
def post():
parse = reqparse.RequestParser()
parse.add_argument('product_id', type=str, help='商品id必傳', required=True, trim=True)
args = parse.parse_args()
product_id = args.product_id
return {
'msg': '商品id是' + product_id,
'code': 200
}
@staticmethod
def get():
return {
'msg': '商品',
'code': 200
}
那么main.py主文件中修改如下:
from controller.product_controller import ProductView
app = Flask(__name__)
api = Api(app)
api.add_resource(ProductView, '/product', endpoint='product')
if __name__ == '__main__':
app.run()
現(xiàn)在已經(jīng)是restful形式的api了,我們采用apifox或者postman測試請求接口如下:



可以看到get請求成功,但是在post請求時,我們沒有傳必傳參數(shù),所以出現(xiàn)了報錯。我們嘗試將必傳參數(shù)加上:


那么可以看到將必傳的參數(shù)加上后,請求成功。 兩種模式可以共存,但是一般我們只用一種就行了。
相信細心的小伙伴已經(jīng)發(fā)現(xiàn),失敗和成功返回的數(shù)據(jù)格式不一樣,成功有code,失敗卻沒有code,那么我想自定義失敗返回的數(shù)據(jù)格式,將怎么操作呢,接下來自定義flask_restful的錯誤響應(yīng)。
二、自定義flask_restful響應(yīng)格式
在根目錄下創(chuàng)建errors.py,寫入如下代碼:
"""
design the custom error response of flask-restful
"""
from flask_restful import abort
def generate_response(msg, status):
return {
'code': status,
'msg': msg,
}
def custom_abort(http_status_code, *args, **kwargs):
if http_status_code == 400:
abort(400, **generate_response(msg=[kwargs.get('message')], status=http_status_code))
abort(http_status_code)
我們將錯誤狀態(tài)拎出來自定義返回格式。 在main.py主文件中加入這兩行代碼:
from errors import custom_abort flask_restful.abort = custom_abort
效果如下:

可以看到我們成功的返回了相同的數(shù)據(jù)結(jié)構(gòu)。
以上就是flask路由分模塊管理及自定義restful響應(yīng)格式詳解的詳細內(nèi)容,更多關(guān)于flask路由管理restful響應(yīng)格式的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python編程新標(biāo)準(zhǔn)學(xué)會十項好習(xí)慣提升編碼質(zhì)量
這篇文章主要為大家介紹了Python編程新標(biāo)準(zhǔn)學(xué)會十項好習(xí)慣提升編碼質(zhì)量,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
用于ETL的Python數(shù)據(jù)轉(zhuǎn)換工具詳解
這篇文章主要介紹了用于ETL的Python數(shù)據(jù)轉(zhuǎn)換工具,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
Python實現(xiàn)程序判斷季節(jié)的代碼示例
今天小編就為大家分享一篇關(guān)于Python實現(xiàn)程序判斷季節(jié)的代碼示例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
python入門turtle庫實現(xiàn)螺旋曲線圖的方法示例
openCV入門學(xué)習(xí)基礎(chǔ)教程第二篇

