Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define manually routes using Flask

Tags:

python

flask

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?

like image 602
Victor Sigler Avatar asked Nov 28 '14 16:11

Victor Sigler


2 Answers

There are several ways to do this:

  1. 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)
    
  2. 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)
    
  3. 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 image 180
Sean Vieira Avatar answered Sep 19 '22 21:09

Sean Vieira


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>

like image 29
lealhugui Avatar answered Sep 21 '22 21:09

lealhugui