Created
August 18, 2011 20:39
-
-
Save amcgregor/1155136 to your computer and use it in GitHub Desktop.
An example response registry for WebCore 2, eliminating the need for the hard-coded response handlers in web.core.application and the weirdness of the templating middleware.
This file contains hidden or 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
import types | |
class IFile(object): | |
pass | |
class ResponseRegistry(object): | |
def __init__(self): | |
self.registry = list() | |
def register(self, *kinds): | |
def inner(fn): | |
self.registry.append((kinds, fn)) | |
return fn | |
return inner | |
def __call__(self, response): | |
for k, v in self.registry: | |
if isinstance(response, k): | |
result = v(response) | |
if result is not None: | |
return result | |
def main(): | |
registry = ResponseRegistry() | |
# @registry.register(Response) | |
# def webob_response(response, environ, start_response): | |
# return response | |
@registry.register(tuple) | |
def templated_response(args): | |
return "template response" | |
@registry.register(list, types.GeneratorType) | |
def generator_response(generator): | |
return "generator response" | |
# web.core.response.app_iter = generator | |
# return web.core.response(environ, start_response) | |
@registry.register(unicode) | |
def unicode_response(body): | |
return "unicode response" | |
# web.core.response.unicode_body = body | |
# return web.core.response(environ, start_response) | |
@registry.register(str) | |
def string_response(body): | |
return "string response" | |
# web.core.response.body = body | |
# return web.core.response(environ, start_response) | |
@registry.register(type(None)) | |
def none_response(body): | |
return "empty response" | |
# return web.core.response(environ, start_response) | |
@registry.register(file, IFile) | |
def file_response(fh): | |
return "file or filelike response" | |
print registry(None) | |
print registry("foo") | |
print registry(open('/dev/null')) | |
print registry(u"bar") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment