如何修复 Python bottle Unsupported response type: <class 'dict'>
问题:
你正在使用 bottle 运行 Python HTTP 服务器。当你访问 HTTP 服务器端点时,你看到类似这样的 HTTP 500 错误消息
bottle-error.txt
Unsupported response type: <class 'dict'>解决方案
发生这种情况是因为你试图返回 Python list 的字典,例如在
bottle-bad-example.py
from bottle import route, run, template, response
@route('/')
def index():
# 我们期望 bottle 在这里返回 JSON
# 但那没有发生!
return [{"a": "b"}]
run(host='localhost', port=8080)为了解决此行为,你需要设置 response.content_type 并显式使用 json.dumps() 将 JSON 转换为字符串:
bottle-fixed-example.py
from bottle import route, run, template, response
import json
@route('/')
def index():
response.content_type = 'application/json'
return json.dumps([{"a": "b"}])
run(host='localhost', port=8080)Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow