WSGI - 将内容类型设置为JSON

Chr*_*row 7 python rest google-app-engine wsgi

我对谷歌应用引擎(GAE)上的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()
Run Code Online (Sandbox Code Playgroud)

另外,我正在构建一些RESTful服务,没什么太复杂的.我在JAVA开发时使用的是restlets.是否有比WSGI更好的框架?我使用WSGI的唯一原因是因为这是他们在App Engine教程中使用的.

谢谢!

sys*_*out 14

您可以使用以下内容设置正确的Content-Type:

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

WSGI不是框架,而是规范; 您当前使用的框架是webapp框架.

在Python方面没有像Restlet那样复杂和具体的东西; 但是使用webapp,您可以通过正则表达式创建RESTful请求处理程序,像处理程序一样返回JSON/XML数据.