如何防止 Flask (python) 发出 html?

How to prevent Flask (python) from emitting html?

Flask 似乎假定服务器正在向客户端(浏览器)返回 html。

这是一个简单的例子;

import json
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
  msg = ['Hello, world!']
  return json.dumps(msg) + '\n'

此代码按预期工作并且 returns 所需 json;

$ curl -s http://localhost:5000/
["Hello, world!"]

但是如果我引入错误;

import json
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
  msg = ['Hello, world!']
  return json.dumps(XXmsg) + '\n'

然后 Flask 发出包裹在几页价值 html 中的错误,开始像;

$ curl -s http://localhost:5000/
<!DOCTYPE html>
<html>
  <head>
    <title>NameError: name 'XXmsg' is not defined
 // Werkzeug Debugger</title>
    <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css">
    <link rel="shortcut icon"
        href="?__debugger__=yes&amp;cmd=resource&amp;f=console.png">
    <script src="?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js"></script>
    <script>
      var CONSOLE_MODE = false,
          EVALEX = true,
          EVALEX_TRUSTED = false,
          SECRET = "Mq5TSy6QE4OuOHUfvk8b";
    </script>
  </head>
  <body style="background-color: #fff">
    <div class="debugger">

如果您正在创建页面加载应用程序,则发出 html 很有意义。但是我正在创建一个 api 只有 returns json.

有没有办法完全阻止 Flask 发出 html?

谢谢 麦克

查看 Flask 文档的 Returning API Errors as JSON 部分。

基本上,您必须将默认错误处理程序替换为 returns 错误为 json 的函数。一个非常基本的例子:

@app.errorhandler(HTTPException)
def handle_exception(exception):
    response = exception.get_response()
    response.content_type = "application/json"
    response.data = json.dumps({"code": exception.code})
    return response