Define manually routes using Flask
flask, python
Solution
There are several ways to do this:
Create a global instance of your class and route your rules to it:
class X(object):
# Your code here
INSTANCE_X = X()
# Note that we are not *calling* the methods
app.add_url_rule('/x/', view_func=INSTANCE_X.route1)
app.add_url_rule('/y/', view_func=INSTANCE_X.route2)
Create an instance in the view function and delegate to it:
# Using both methods of registering URLs here
# just to show that both work
@app.route('/x/')
def handle_route1():
return X().route1()
def handle_route2():
return X().route2()
app.add_url_rule('/y/', view_func=handle_route2)
Inherit from Flask's `View` or `MethodView` Pluggable View classes and use the `as_view` classmethod to handle this for you:
class X(View):
methods = ['GET']
def dispatch_request(self):
if request.path == '/x/':
return route1()
elsif request.path == '/y/':
return route2()
else:
abort(404)
app.add_url_rule('/x/', view_func=X.as_view('X.route1'))
app.add_url_rule('/y/', view_func=X.as_view('X.route2'))
Problem
I want to define routes manually to some method of classes, something like this : ``` class X: def route1(): #do stuff here def route2(): #do stuff here ``` and then make something like this : ``` app.add_url_rule('/x/', view_func=X.route1()) app.add_url_rule('/y/', view_func=X.route2()) ``` It's possible?? What's the correct way to acomplish this?