Created
June 30, 2014 20:12
-
-
Save Kellel/fcb7dc8aef18760b98f6 to your computer and use it in GitHub Desktop.
Class based bottle routes
This file contains 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
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) |
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
I wanted to explore writing class based routes within the bottle framework.