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?
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'))
Like I said in the comments, do you know flask-classy?
From their exemple:
from flask import Flask
from flask.ext.classy import FlaskView
# we'll make a list to hold some quotes for our app
quotes = [
    "A noble spirit embiggens the smallest man! ~ Jebediah Springfield",
    "If there is a way to do it better... find it. ~ Thomas Edison",
    "No one knows what he can do till he tries. ~ Publilius Syrus"
]
app = Flask(__name__)
class QuotesView(FlaskView):
    def index(self):
        return "<br>".join(quotes)
    def get(self, id):
        id = int(id)
        if id < len(quotes) - 1:
            return quotes[id]
        else:
            return "Not Found", 404     
QuotesView.register(app)
if __name__ == '__main__':
    app.run()
Would generate automatically routes for http://foobar.foo/quotes and http://foobar.foo/quotes/<id>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With