Defining Routes Manually Using Flask

I want to define routes manually for some class method, something like this:

class X: def route1(): #do stuff here def route2(): #do stuff here 

and then do something like this:

 app.add_url_rule('/x/', view_func=X.route1()) app.add_url_rule('/y/', view_func=X.route2()) 

Maybe? What is the right way to accomplish this?

+5
source share
2 answers

There are several ways to do this:

  • Create a global instance of your class and send it your rules:

     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 View or MethodView Pluggable View and use 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')) 
+8
source

As I said in the comments, do you know flask-classy ?

From their example:

 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() 

Automatically generates routes for http://foobar.foo/quotes and http://foobar.foo/quotes/<id>

+3
source

Source: https://habr.com/ru/post/1207900/


All Articles