如何在扭曲中返回json响应?

Mit*_*ril 3 python json twisted

当我使用django时:我总是这样做

return HttpResponse(json.dumps(result), mimetype='application/json')
Run Code Online (Sandbox Code Playgroud)

怎么能扭曲呢?官方文件不说这个.

文件在这里

只能Serving WSGI Applications设置mimetype.但我想处理GET和POST没有更多的例子,我搜索没有找到.

from twisted.web import resource
class MyGreatResource(resource.Resource):
    def render_GET(self, request):
        return "xxxx"
Run Code Online (Sandbox Code Playgroud)

它返回原始字符串

Jea*_*one 7

编码的JSON (字节)字符串.

如果您的问题是"我如何设置响应的内容类型application/json?" 然后答案是:

request.responseHeaders.addRawHeader(b"content-type", b"application/json")
Run Code Online (Sandbox Code Playgroud)