发生错误时,如何不使Flask服务器中断? [英] how to not have the flask server break when an error occurs?

查看:136
本文介绍了发生错误时,如何不使Flask服务器中断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用flask创建了一个API应用程序,该应用程序使用数字(十进制)作为输入并返回一些字符串.如果我发送一个字符串,此应用程序将中断,并在重新启动它后可以正常工作.我不想每次在处理过程中发生任何错误时都重新启动.我该怎么做呢?

I have made an API app using flask, that takes a number(decimal) as input and returns some string. This app breaks if I send a string and works fine after re-starting it. I don't want to restart every time some error happens during processing. How do i do this?

这是我的代码:

from flask import Flask, request, jsonify

# initiating the app
flask_api_app = Flask(__name__)


# the app accepts requests via "GET" and "POST" methods
@flask_api_app.route("/", methods=["GET", "POST"])
def output_risk_and_report():
    # getting json data from api call
    json_data = request.get_json(force=True)

    # now the processing part
    if json_data['number'] < 2:
        return jsonify(["the number is less than two"])
    else:
        return jsonify(["the number is not less than two"])


# main function, in which app will be run
if __name__ == "__main__":
    # running the app on local host
    flask_api_app.run(debug=True, host='127.0.0.1', port='8080')

不中断应用的通话示例:{"number":4}
导致应用中断的呼叫示例:{"number":"adfa"}

example of call which doesn't break the app: {"number":4}
example of call which breaks the app: {"number":"adfa"}

我要对代码进行哪些更改以实现此目的?

What changes do I make in my code to accomplish this?

我天真地在我的问题中举那个例子.在我的原始程序中,将数据插入数据库时​​可能会出错,或者在进行某些算术计算或某些操作时可能会出错.因此,有什么方法可以告诉flask继续为新的api请求提供服务,并且仅通过一个api调用发生错误时就不会中断.

EDIT 1: i was naive to give that example in my question. in my original program, i may get an error when inserting data into database or may get an error with some arithmetic calculation or something. So, is there any way to tell flask to keep serving for new api requests and not break when an error occurs with only one api call.

推荐答案

您可以创建一个装饰器,该装饰器是全局异常处理程序:

You can make a decorator that is a global exception handler:

import traceback
from flask import current_app

def set_global_exception_handler(app):
    @app.errorhandler(Exception)
    def unhandled_exception(e):
        response = dict()
        error_message = traceback.format_exc()
        app.logger.error("Caught Exception: {}".format(error_message)) #or whatever logger you use
        response["errorMessage"] = error_message
        return response, 500

在创建应用实例的任何地方,都需要执行以下操作:

And wherever you create your app instance, you need to do this:

from xxx.xxx.decorators import set_global_exception_handler
app = Flask(__name__)
set_global_exception_handler(app)

这将处理应用程序中生成的所有异常以及处理异常所需的其他所有操作.希望这会有所帮助.

This will handle all exceptions generated in your application along with whatever else you need to do to handle them. Hope this helps.

这篇关于发生错误时,如何不使Flask服务器中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆