-3

My colleague would like to place all routes for the web server in a single routing file instead of spreading them around on a bunch of functions. This is how he does it in Java/Play:

GET    /recovery         controllers.application.recovery()
GET    /signup           controllers.application.signup(lang="sv")
GET    /<:lang>/signup   controllers.application.signup(lang: String)

Is it feasible/easy to do in Flask?

Jonas Byström
  • 25,316
  • 23
  • 100
  • 147

1 Answers1

-2

Yes, very easy:

from flask import Flask
import controllers.application

app = Flask(__name__)
routes = '''\
GET    /recovery        controllers.application.recovery
GET    /signup          controllers.application.signup
GET    /<lang>/signup   controllers.application.signup'''

for route in routes.splitlines():
    method,path,func = route.split()
    app.add_url_rule(rule=path, view_func=eval(func), methods=[method])

app.run()
Jonas Byström
  • 25,316
  • 23
  • 100
  • 147
  • 2
    This certainly could've been done without `eval()`. http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice – Ilja Everilä Apr 12 '17 at 12:18
  • Not everything should be subsumed under programmer convenience. The data would be much better expressed as a sequence of `(method, path, function)` triples like `('GET', '/recovery', controllers.application.recovery)`, allowing `for method, path, func in routes:`. This avoids the quite unnecessary `eval` calls. – holdenweb Apr 12 '17 at 13:09