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!
The start_response Return Value – The write Callback For backward compatibility purposes, web servers implementing WSGI should return a write callable. This callback should allow the application to write body response data directly back to the client, instead of yielding it to the server via an iterator.
FieldStorage( fp=environ['wsgi. input'], environ=post_env, keep_blank_values=True ) html = b'Hello, ' + post['name']. value + '!' start_response('200 OK', [('Content-Type', 'text/html')]) return [html] if __name__ == '__main__': try: from wsgiref.
jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.
WSGI stands for "Web Server Gateway Interface". It is used to forward requests from a web server (such as Apache or NGINX) to a backend Python web application or framework. From there, responses are then passed back to the webserver to reply to the requestor.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With