前言
剛好最近了解了python裝飾器,就在工作中用實(shí)踐了一把,避免寫很多重復(fù)的代碼烁焙,在有多個路由的情況下效果顯而易見。本文純屬一個學(xué)渣的探索歷程耕赘,請以此小例子為參考骄蝇,在工作中盡情發(fā)揮,可能flask本身有別的更好的實(shí)現(xiàn)操骡,但是本人flask小白九火,如有更好的實(shí)現(xiàn)方法還請批評指正。python裝飾器基礎(chǔ)及多裝飾器的運(yùn)行順序解析可參考http://www.reibang.com/p/4043735e839e
實(shí)例代碼
# coding: utf-8
import numpy as np
import os
import time
import datetime
from flask import Flask, request, jsonify, Response, abort
import json
import uuid
from functools import wraps
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
#異常處理裝飾函數(shù)
def decorator(fun):
@wraps(fun)
def wrapper(*args, **kwargs):
try:
try_result = fun(*args, **kwargs)
return try_result
except KeyError as e:
error_warning = {'error_warning': 'A key error has occurred. Please check if the keys of the uploaded json are correct.'}
return jsonify(error_warning)
except TypeError as e:
error_warning = {'error_warning': 'A type error has occurred. Please check if the uploaded json data type is correct.'}
return jsonify(error_warning)
except Exception as e:
error_warning = {'error_warning':repr(e)}
return jsonify(error_warning)
return wrapper
#定義路由
@app.route('/assign', methods=['GET', 'POST'])
@decorator
def assignment():
data = {'flags': 'haha', 'corpus': 'hello'}
setsd = {}
setsd['label'] = data['flag']
results = setsd
return jsonify(results)
@app.route('/', methods=['GET', 'POST'])
@decorator
def sayhi():
return 'hellow world'
# 捕獲404錯誤
@app.errorhandler(404)
def errors(error):
return jsonify(repr(error))
@decorator
def run_app():
app.run(debug=True, host = *****, port = 5000)
return 'web服務(wù)啟動了'
if __name__ == '__main__':
service = run_app()
print (service)
總結(jié):
這樣實(shí)現(xiàn)避免在每個路由下面都寫一個try...except的代碼塊册招,代碼的復(fù)用還是挺重要的岔激,請大家都要堅(jiān)持少寫重復(fù)代碼。此外flask中的用戶登錄驗(yàn)證是掰、表單驗(yàn)證等都可用裝飾器實(shí)現(xiàn)虑鼎。表單驗(yàn)證邏輯可參考此篇文章http://www.reibang.com/p/2aabc4b3db4c謝謝!