Last active
December 29, 2015 16:09
-
-
Save diyan/7695718 to your computer and use it in GitHub Desktop.
Simple script wheezy.web with content negotiation skeleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import unicode_literals | |
import json | |
from wheezy.http import WSGIApplication, HTTPResponse | |
from wheezy.routing import url | |
from wheezy.web.handlers import BaseHandler | |
from wheezy.web.middleware import bootstrap_defaults, path_routing_middleware_factory | |
from wsgiref.simple_server import make_server | |
class ResourceHandler(BaseHandler): | |
def absolute_url_for(self, name, **kwargs): | |
absolute_url = super(ResourceHandler, self).absolute_url_for(name, **kwargs) | |
return absolute_url.encode('utf-8') | |
def negotiate_response(self, obj): | |
response = obj | |
if not isinstance(obj, HTTPResponse): | |
json_str = json.dumps(obj) | |
callback = self.request.query.get('callback') | |
if callback: | |
json_str = '{0}({1});'.format(callback, json_str) | |
response = HTTPResponse() | |
response.write(json_str) | |
return response | |
class IndexHandler(ResourceHandler): | |
def get(self): | |
return self.redirect_for('hello') | |
class HelloHandler(ResourceHandler): | |
def get(self): | |
# FIXME this does not looks nice | |
return self.negotiate_response(dict(message='Hello World!')) | |
all_urls = [ | |
url('', IndexHandler, name='default'), | |
url('hello/world', HelloHandler, name='hello') | |
] | |
if __name__ == '__main__': | |
options = {} | |
app = WSGIApplication( | |
middleware=[ | |
bootstrap_defaults(url_mapping=all_urls), | |
path_routing_middleware_factory | |
], | |
options=options) | |
try: | |
print('Running on http://localhost:8080/') | |
make_server('', 8080, app).serve_forever() | |
except KeyboardInterrupt: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment