基于 flask_restful 应用框架主要包含:
app = Flask(__name__)api_bp = Blueprint('api', __name__)logging.basicConfig(format='%(levelname)s - %(asctime)s - %(message)s', level=logging.DEBUG)class Api(_Api):def error_router(self, original_handler, e):if self._has_fr_route() and isinstance(e, HTTPException):try:return self.handle_error(e)except Exception:passreturn handle_error(e)api = Api(app)api.add_resource(SequenceRecommend, '/predict')# 注册蓝图app.register_blueprint(api_bp)if __name__ == '__main__':app.run()
SequenceRecommend
class SequenceRecommend(Resource):def __init__(self):def post(self):def valid_top_n(field):try:field = int(field)except ValueError:raise ValueError('top_n type must be int ')if 50 >= field > 0:return fieldelse:raise ValueError('top_n must be greater than 1 and less than 51')def valid_items(field):try:field = str(field)field = field.strip()except ValueError:raise ValueError('items type must be string, and required!')if len(field) <= 0:raise ValueError('items must not be a blank str!')items_array = field.split(",")if len(items_array) > 50:items_array = items_array[-50:]field = ",".join(items_array)return field#参数校验parser.add_argument('items', type=valid_items, required=True, nullable=False)parser.add_argument('top_n', type=valid_top_n, default=10, required=False)args = parser.parse_args()items = args['items']top_n = args['top_n']#TODOreturn ''
@app.after_requestdef wrap_response(response):# 在这里对响应进行额外的处理# 可以修改响应的头信息、添加额外的数据等status_code = response.status_codeif status_code in [200, 201]:data = parse_json(response.data)response.data = json.dumps({'code': status_code,'data': data if data is not None else str(data),'message': 'OK'})if 500 > status_code >= 400:data = parse_json(response.data)response.data = json.dumps({'code': status_code,'message': data['message'] if data is not None else str(data)})return response
@app.errorhandler(Exception)def handle_error(error):# flask在这里处理异常# 这个不能捕获flask-restful异常# 在这里进行异常处理逻辑# 可以根据异常类型进行不同的处理# 返回自定义的错误响应error_str = "Internal Server Error"try:error_str = str(error)except Exception:passresponse = {'code': 500,'message': error_str}logging.error("has error.", error)return jsonify(response), 500