WSGI - Set content type to JSON

10,062

Solution 1

You can set the proper Content-Type with something like this:

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

WSGI is not a framework but a specification; the framework you are currently using is the webapp framework.

There's nothing sophisticated and specific like Restlet on the Python side; however with webapp you can create RESTful request handlers through regular expressions returning JSON/XML data like your handler does.

Solution 2

Like any HTTP response, you can add or edit headers:

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))

More here: Redirects, Headers and Status Codes

Solution 3

Is there a better framework to be using than WSGI?

Look at Pyramid (previously named pylons, if you see that mentioned). It sounds like it'd be better in your case vs django.

Share:
10,062
Chris Dutrow
Author by

Chris Dutrow

Creator, EnterpriseJazz.com Owner, SharpDetail.com LinkedIn

Updated on June 23, 2022

Comments

  • Chris Dutrow
    Chris Dutrow almost 2 years

    I'm crazy green to WSGI on Google App Engine (GAE).

    How do I set the content type to JSON? This is what I have so far:

    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()
    

    Additionally, I'm building a few RESTful services, nothing too complicated. I was using restlets when I was developing in JAVA. Is there a better framework to be using than WSGI? The only reason I'm using WSGI is because that was what they used in the App Engine tutorial.

    Thanks!

    • Nick Johnson
      Nick Johnson about 13 years
      You're "crazy green"? I hear that isn't easy.
    • Chris Dutrow
      Chris Dutrow about 13 years
      Hey Nick, so I tried to write you a thank you not a while back for one of the questions that I had that you answered, but for the life of me I couldn't find your e-mail address