5

I am a beginner in flask - Python. I am facing an issue with multiple routing. I had gone through google searches. But didn't get the full idea of how to implement it. I have developed an flask application where i need to reuse the same view function for different urls.

@app.route('/test/contr',methods=["POST", "GET"],contr=None)
@app.route('/test/primary', methods=["POST", "GET"])
def test(contr):                                          
    if request.method == "POST":
        if contr is None:
            print "inter"
        else:
            main_title = "POST PHASE"
...

I want to call test function for 2 routing..& have different in few functionalities, except that all other are same. So i though of reusing. But not getting how to differentiate routing inside the test function using some parameters passing from function which redirects the call to this test function.

I couldn't find a good tutorial which defines basics of multiple routing from scratch

2
  • Why not just use two route functions for your two routes? Any logic you want to share between them can be in a third function that they both call. Commented Sep 30, 2017 at 10:44
  • 1
    Daniel, I have already created many routes like that..So thought of reusing the code.,if there are 20 pages in an application, do I need to create 20 route functions for that? Flask should have something for that. Commented Sep 30, 2017 at 17:29

1 Answer 1

16

There are a couple of ways that you can handle this with routes.

You can dig into the request object to learn which rule triggered the call to the view function.

  • request.url_rule will give you the rule that was provided as the first argument to the @app.route decorator, verbatim. This will include any variable part of the route specified with <variable>.
  • Use request.endpoint which defaults to the name of the view function, however, it can be explicitly set using the endpoint argument to @app.route. I'd prefer this because it can be a short string rather than the full rule string, and you can change the rule without having to update the view function.

Here's an example:

from flask import Flask, request

app = Flask(__name__)

@app.route('/test/contr/', endpoint='contr', methods=["POST", "GET"])
@app.route('/test/primary/', endpoint='primary', methods=["POST", "GET"])
def test():
    if request.endpoint == 'contr':
        msg = 'View function test() called from "contr" route'
    elif request.endpoint == 'primary':
        msg = 'View function test() called from "primary" route'
    else:
        msg = 'View function test() called unexpectedly'

    return msg

app.run()

Another method is to pass a defaults dictionary to @app.route. The dictionary will be passed to the view function as keyword arguments:

@app.route('/test/contr/', default={'route': 'contr'}, methods=["POST", "GET"])
@app.route('/test/primary/', default={'route': 'primary'}, methods=["POST", "GET"])

def test(**kwargs):
    return 'View function test() called with route {}'.format(kwargs.get('route'))
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much dude. You saved my day...This is what I was looking for. Can you please share any doc which has the detail description of the same
the endpoint can be set but it based on route. if the path is admin/site set endpoint='site', the result will be admin.site, not only site

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.