前言
刚好最近了解了python装饰器,就在工作中用实践了一把,避免写很多重复的代码,在有多个路由的情况下效果显而易见。本文纯属一个学渣的探索历程,请以此小例子为参考,在工作中尽情发挥,可能flask本身有别的更好的实现,但是本人flask小白,如有更好的实现方法还请批评指正。python装饰器基础及多装饰器的运行顺序解析可参考//www.greatytc.com/p/4043735e839e
实例代码
# 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
#异常处理装饰函数
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服务启动了'
if __name__ == '__main__':
service = run_app()
print (service)
总结:
这样实现避免在每个路由下面都写一个try...except的代码块,代码的复用还是挺重要的,请大家都要坚持少写重复代码。此外flask中的用户登录验证、表单验证等都可用装饰器实现。表单验证逻辑可参考此篇文章//www.greatytc.com/p/2aabc4b3db4c谢谢!