将返回 HTML 错误消息而不是自定义 JSON 错误消息

问题描述 投票:0回答:2

我有一个用 Postman 调用的 API_1。如果计算出现错误,则会以 JSON 格式输出错误消息。我为此使用以下代码:

@app.errorhandler(Exception)
def handle_default_error(e):
    message = e.description
    return jsonify(error=message), e.code

Postman 中的输出如下所示:

这是将返回的正确 JSON 错误消息。

我的目标是让 API_1 与其他 API_Total 一起调用。如果我使用 Postman 调用 API_Total,然后 Postman 调用 API_1 并发生错误,我会得到以下输出:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Error response</title>
</head>
<body>
    <h1>Error response</h1>
    <p>Error code: 400</p>
    <p>Message: Bad Request.</p>
    <p>Error code explanation: 400 - Bad request syntax or unsupported method.</p>
</body>

但我不希望出现 HTML 错误消息,而是出现 JSON。 我已经尝试过:

return jsonify(error=message), e.code, {'Content-Type': 'application/json'}

不幸的是,这并没有改变任何东西,并且仍然没有 JSON 错误消息。

API_Total 对 API_1 的调用如下所示:

headers_content = {
    'Authorization': 'Bearer ' + bearer_token
}

payload_content = {}

try:
    response = requests.request("GET", url, headers=headers_content, data=payload_content, proxies=proxies)
except: 
    return None



if response.status_code != requests.codes.ok:
  return abort(my_status_code, message)
#Simplified procedure

#1. Postman calls API_Total

#2. API_1 is called by API_Total

    try:
        response = requests.request("GET", url, headers=headers_content, data=payload_content, proxies=proxies)
    except:
        return None
        
        
#3. API_1
    #Performing the calculations
    #If an error occurs:
    return abort(404, 'Bad Request')
    #app.errorhandler is called
    @app.errorhandler(Exception)
    def handle_default_error(e):
        message = 'e.description'
        #Return to API_Total
        return jsonify(error=message), e.code

#4 APi_Total is to represent the error message of API_1 in the JSON. However, as mentioned above, this does not happen
    

我从 API_1 收到此标题内容。内容类型是 text/html 而不是 Json:

{'Server': 'SimpleHTTP/0.6 Python/3.6.4', 'Date': 'Tue, 12 Sep 2023 05:39:26 GMT', 'Connection': 'close', 'Content-Type': 'text/html;charset=utf-8', 'Content-Length': '460'}
python api flask pycharm
2个回答
0
投票

也许这样的东西适合你:

 # Customize error responses based on the exception type
 if isinstance(e, ValueError):
     error_message = "ValueError: " + error_message
     error_code = 400  # Bad Request

 return jsonify({"error": error_message}), error_code

0
投票

我的意思是这样的,人们可以复制并粘贴来测试(来自 ChatGPT 的示例,而不是实际的代码或答案):

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/API_1', methods=['GET'])
def api_1():
    try:
        # Your API_1 logic here
        result = {"message": "API_1 response"}
        return jsonify(result)
    except Exception as e:
        return jsonify(error=str(e)), 500

@app.route('/API_Total', methods=['GET'])
def api_total():
    try:
        # Call API_1 and process its response
        response = api_1()
        
        # Your API_Total logic here, which may include processing the response from API_1
        total_result = {"message": "API_Total response", "API_1_response": response.json}
        
        return jsonify(total_result)
    except Exception as e:
        return jsonify(error=str(e)), 500

@app.errorhandler(Exception)
def handle_default_error(e):
    message = str(e)
    return jsonify(error=message), 500

if __name__ == '__main__':
    app.run(debug=True)

重点是看看你如何定义路由,我认为你不应该使用请求调用 API_1,因为你已经在 python 代码中并且可以直接访问 API_1。

© www.soinside.com 2019 - 2024. All rights reserved.