WSGI - 设置内容类型为 JSON

7 投票
3 回答
10331 浏览
提问于 2025-04-16 16:21

我对Google App Engine上的WSGI完全是个新手。

我该怎么把内容类型设置为JSON呢?这是我目前的代码:

class Instructions(webapp.RequestHandler):
    def get(self):
        response = {}
        response["message"] = "This is an instruction object"

        self.response.out.write(json.dumps(response))



application = webapp.WSGIApplication([('/instructions', Instructions)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

另外,我正在构建一些RESTful服务,没什么太复杂的。我在用JAVA开发的时候是用restlets。请问有没有比WSGI更好的框架可以使用?我之所以用WSGI,是因为在App Engine的教程里就是这样做的。

谢谢!

3 个回答

1

有没有比WSGI更好的框架可以使用?

可以看看Pyramid(之前叫pylons,如果看到这个名字也不要奇怪)。在你的情况下,它可能比Django更合适。

2

就像任何HTTP响应一样,你可以添加或修改头部信息:

def get(self):
    response = {}
    response["message"] = "This is an instruction object"

    self.response.headers["Content-Type"] = "application/json"
    self.response.out.write(json.dumps(response))

更多内容请查看:重定向、头部和状态码

14

你可以用下面的方式设置合适的 Content-Type

self.response.headers['Content-Type'] = "application/json"
self.response.out.write(json.dumps(response))

WSGI 不是一个框架,而是一种规范;你现在使用的框架是 webapp 框架。

在Python这边,没有像Restlet那样复杂和特定的东西;不过,使用webapp你可以通过正则表达式创建 RESTful请求处理器,返回像你的处理器一样的JSON/XML数据。

撰写回答