Flask是個簡易的WebAPI撰寫框架, 短時間內即可實現網路服務, 這裡使用Flask做個範例, 並且搭配Python Decorator檢查Request參數, 最後用Json回傳結果 |
FlaskAPI寫法簡單, 但寫法卻不只一種, 這裡舉我最常使用的方式當成例子, 搭配Python Decorator做參數檢查, 最後用Json回傳結果
#!flask/bin/python # -*- coding: utf-8 -*- import pandas as pd import json from datetime import datetime,timedelta from flask import Flask, jsonify from flask.views import MethodView from FlaskApi_CheckAttribute import * from Utility_JsonConverter import JsonConverter app = Flask(__name__) class GetEmployeeIdView(MethodView): @requires_json_check_param #Decorator def post(self): """ Json { "EmployeeId":"12345678", } """ emp_id = request.json['EmployeeId'] #接值 try: api_start = datetime.now() #回傳Json return jsonify(code=StateCode.Success, message="success", api_start=api_start, emp_id=emp_id) except Exception as e: return jsonify(code=StateCode.Unexpected, message='exception : ' + str(e)), 999 if __name__ == "__main__": # 建立 View app.add_url_rule('/api/getEmployeeId', view_func=GetEmployeeIdView.as_view('GetEmployeeIdView')) # 啓動 app.run(port=5001, host='000.000.000.000', debug=True, use_reloader=False, threaded=True)
當Function有設定Decorator時, 會先進入Decorator進行規則判斷,這裏就是使用此原理,先對request參數進行檢查, 接下來就是建立Decorator, 當缺少EmployeeId這個參數就會引發例外, 程式中可會設定例外訊息
# encoding=UTF-8 #!flask/bin/python import sys from functools import wraps from werkzeug.exceptions import Unauthorized, UnsupportedMediaType, BadRequest from itsdangerous import BadSignature from flask import abort import numbers import collections # from . import app from flask import g, request def requires_json_check_param(f): @wraps(f) def decorated(*args, **kwargs): jsonError = "缺少參數 : " if not 'EmployeeId' in request.json: raise BadRequest(jsonError + "EmployeeId") return f(*args, **kwargs) return decorated
沒有留言:
張貼留言