Priya v v
Priya v v

Reputation: 163

Multiple routing in flask- Python

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

Upvotes: 5

Views: 14386

Answers (1)

mhawke
mhawke

Reputation: 87134

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

Upvotes: 16

Related Questions