Skip to content

Instantly share code, notes, and snippets.

@Kellel
Created June 30, 2014 20:12
Show Gist options
  • Save Kellel/fcb7dc8aef18760b98f6 to your computer and use it in GitHub Desktop.
Save Kellel/fcb7dc8aef18760b98f6 to your computer and use it in GitHub Desktop.
Class based bottle routes
from bottle import route, abort, Bottle
class BasicRoute(object):
path = ''
def __init__(self, apppath, app):
self.app = app
self.methods = {
'GET': self.get,
'POST': self.post,
'HEAD': self.head,
'PUT': self.put,
}
for method in self.methods.iterkeys():
#print(apppath + self.path)
self.app.route(apppath + self.path, method)(self._wraps(self.methods[method]))
def _wraps(self,fn):
return fn
def get(self, *args, **kwargs):
abort(404)
def post(self, *args, **kwargs):
abort(404)
def head(self, *args, **kwargs):
abort(404)
def put(self, *args, **kwargs):
abort(404)
class BasicApplication(object):
root = ''
routes = {}
def __new__(cls, app=Bottle()):
obj = super(BasicApplication, cls).__new__(cls)
obj.__init__(app)
return app
def __init__(self, app):
self.app = app
for r in self.routes:
eval("self.{}(self.root,self.app)".format(r))
class MetaApplication(BasicApplication):
def __init__(self, app):
self.app = app
for r in self.routes:
self.app = r(self.app)
appl = bottle.app()
class AuthRoute(BasicRoute):
def _wraps(self,fn):
return cas.require(fn)
class MyApp(BasicApplication):
root = '/'
routes = [ 'MainRoute', 'TestRoute', 'TwoRoute']
class MainRoute(BasicRoute):
def get(self):
return "Home"
def head(self):
pass
class TestRoute(AuthRoute):
path = '<ty>/<pk>'
def get(self, ty ,pk):
return "Hello World {}, {}".format(ty, pk)
class TwoRoute(AuthRoute):
path = 'two'
def get(self):
return "Two"
class MyApp2(BasicApplication):
root = '/stuff/'
routes = [ 'OneRoute' ]
class OneRoute(BasicRoute):
def get(self):
return "Hello My App 2!"
class MetaApp(MetaApplication):
root = '/two/'
routes = [ MyApp, MyApp2 ]
if __name__ == "__main__":
app = MetaApp(appl)
bottle.run(app=app, host='localhost', port=8001)
@Kellel
Copy link
Author

Kellel commented Jun 30, 2014

I wanted to explore writing class based routes within the bottle framework.

@Kellel
Copy link
Author

Kellel commented Jun 30, 2014

You can use a multiple basic routes to build an BasicApplication object

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment