Behebung von Python bottle Unsupported response type: <class 'dict'>

English Deutsch

Problem:

Du betreibst einen Python-HTTP-Server mit bottle. Wenn du auf deinen HTTP-Server-Endpunkt zugreifst, siehst du eine HTTP-500-Fehlermeldung wie

bottle-error.txt
Unsupported response type: <class 'dict'>

Lösung

Dies tritt auf, weil du versuchst, eine Python-list von Dictionaries zurückzugeben, z.B. in

bottle-bad-example.py
from bottle import route, run, template, response

@route('/')
def index():
    # We expect bottle to return a JSON here
    # but that doesn't happen!
    return [{"a": "b"}]

run(host='localhost', port=8080)

Um dieses Verhalten zu umgehen, musst du response.content_type setzen und explizit json.dumps() verwenden, um dein JSON in einen String umzuwandeln:

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