看来 Flask 假设服务器将 html 返回给客户端(浏览器)。
这是一个简单的例子;
import json
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
msg = ['Hello, world!']
return json.dumps(msg) + '\n'
Run Code Online (Sandbox Code Playgroud)
此代码按预期工作并返回所需的 json;
$ curl -s http://localhost:5000/
["Hello, world!"]
Run Code Online (Sandbox Code Playgroud)
但如果我引入一个错误;
import json
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
msg = ['Hello, world!']
return json.dumps(XXmsg) + '\n'
Run Code Online (Sandbox Code Playgroud)
然后 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&cmd=resource&f=style.css">
<link rel="shortcut icon"
href="?__debugger__=yes&cmd=resource&f=console.png">
<script src="?__debugger__=yes&cmd=resource&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">
Run Code Online (Sandbox Code Playgroud)
如果您正在创建页面加载应用程序,则发出 html 是有意义的。但我正在创建一个仅返回 json 的 api。
有没有办法完全阻止 Flask 发出 html?
谢谢迈克
查看Flask 文档的以 JSON 形式返回 API 错误部分。
基本上,您必须将默认错误处理程序替换为以 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
Run Code Online (Sandbox Code Playgroud)