Skip to content

Instantly share code, notes, and snippets.

@hirokiky
Last active December 15, 2015 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirokiky/5181190 to your computer and use it in GitHub Desktop.
Save hirokiky/5181190 to your computer and use it in GitHub Desktop.
The decorator named 'node' takes mapping and call next wsgi apprication. The mapping's key is URL pattern you want to match, and the value is a name for a function which will be called when the key pattern matches to URL. In this example, '/a/' calls node2, '/b/' calls node3, '/' calls node1 and '/b/a/' calls node1 too.
from wsgiref.simple_server import make_server
from webob.dec import wsgify
def node(mapping):
def deco(func):
def wrapper(request):
try:
called_count = request.environ['nodechain.chaincount']
except KeyError:
called_count = 0
node_name = request.path_info.split('/')[called_count+1] # /a/b/c => a
node = mapping.get(node_name)
if not node:
node = func
else:
from os.path import basename, splitext
name, _ = splitext(basename(__file__))
mod = __import__(name)
if hasattr(mod, node):
node = getattr(mod, node)
else:
node = func
try:
request.environ['nodechain.chaincount'] += 1
except KeyError:
request.environ['nodechain.chaincount'] = 1
response = node(request)
return response
return wrapper
return deco
@wsgify
def node2(request):
return "OK. I'm node2"
@wsgify
@node({'a': 'node1', 'b': 'node2'})
def node3(request):
return "OK. I'm node3"
@wsgify
@node({'a': 'node2', 'b': 'node3'})
def node1(request):
return "OK. I'm node1"
if __name__ == '__main__':
httpd = make_server('', 8080, node1)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment