Skip to content

Instantly share code, notes, and snippets.

@prologic
Created June 15, 2015 12:46
Show Gist options
  • Save prologic/9e3fb6cbdc331972cc56 to your computer and use it in GitHub Desktop.
Save prologic/9e3fb6cbdc331972cc56 to your computer and use it in GitHub Desktop.
created by github.com/tr3buchet/gister
#!/usr/bin/python
"""A Fibonacci Web App and API
Inspired by SO Question:http://stackoverflow.com/questions/30844887
Usage::
$ curl -q -o - http://localhost:8000/
... this docstring ...
$ curl -q -o - http://localhost:8000/fib
{"errors": ["TypeError: http://localhost:8000/fib takes exactly 1 argument (0 given)"], "success": false}
~
$ curl -q -o - http://localhost:8000/fib/13
{"results": [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144], "success": true}
"""
from json import dumps
from circuits import handler, Component
from circuits.web import Controller, Server, Static
def fib(n=-1):
x = 0
y = 1
while n:
yield x
x, y = y, x + y
n -= 1
class JSONSerializer(Component):
channel = "web"
@handler("response", priority=1.0)
def on_response(self, response):
if isinstance(response.body, dict):
response.headers["Content-Type"] = "application/json"
response.body = dumps(response.body)
class FibonacciAPI(Controller):
channel = "/fib"
def GET(self, *args, **kwargs):
n = args and int(args[0]) or None
if not n:
return {
"success": False,
"errors": [
"TypeError: {0} takes exactly 1 argument (0 given)".format(self.uri.utf8())
]
}
return {"success": True, "results": list(fib(n))}
class Root(Controller):
def index(self, *args, **kwargs):
self.response.headers["Content-Type"] = "text/plain"
return __doc__
class FibonacciApp(Component):
def init(self, bind=None):
bind = bind or ("0.0.0.0", 8000)
Server(bind).register(self)
Static().register(self)
Root().register(self)
FibonacciAPI().register(self)
JSONSerializer().register(self)
FibonacciApp(("0.0.0.0", 8000)).run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment