Collection of commonly used methods and decorators. Feedback and PRs welcome!
pip install tornwrap
@ratelimited
- limit usage for guests and authenticated users
@validated
- using valideer to validate and adapt body and/or url args
- future
@cached
- cache requests, ex page builds
- future
@gist
- retrieve contents of a gist and return it to the handler
- future
@markdown
- generate html pages from a Github repo containing markdown
Requires
redis
from tornwrap import ratelimited
class Handler(RequestHandler):
def initialize(self, redis):
self.redis = redis # required
@ratelimited(guest=(1000, 3600), user=(10000, 1800))
def get(self):
# users get 10k requests every 30 min
# guests get 1k every 1h
self.write("Hello, world!")
def was_rate_limited(self, tokens, remaining, ttl):
# this is the default action
raise HTTPError(403, reason="You have been rate limited.")
Uses valideer
from tornwrap import validated
class Handler(RequestHandler):
@validated({"+name":"string"})
def get(self, arguments):
# can validate url arguments
self.finish("Hello, %s!" % arguments['name'])
@validated(body={"+name":"string"})
def post(self, body):
# can validate body (json or urlencoded)
self.finish("Hello, %s!" % body['name'])
Cache the results of the http request.
from tornwrap import cached
class Handler(RequestHandler):
@cached(key="%(arg)s")
def get(self, arg):
# maybe a long api request
return results # will call `self.finish(results)` for you
def set_cache(self, key, data):
self.memecached.set(key, data)
def get_cache(self, key):
return self.memecached.get(key)
Will create methods for
async
methods toget
andset
too. We all <3 async!
Fetch a Github gist content and return it to the handler method. Useful for chaning home page on the fly.
from tornwrap import gist
class Handler(RequestHandler):
@gist("stevepeak/5592167", refresh=False)
def get(self, gist):
self.render("template.html", gist=gist)
refresh
can be:True
: fetch on every request,False
: fetch right away, cache forever,:seconds
till expires then refetch For those using Heroku, keep in mind dynos reset every 24 hours-ish.
Merge torndown project