Flask render_template with function return

Viewed 9465

I recently working on Flask. And i have a problem with it.

My script looks like this:

@app.route('/')
def index():
    // execute
    return render_template('index.html', body=body, block=block)
@app.route('/api/')
def api():
    // execute
    return 'api'

function api and index do exactly same thing.

What I think is to create a function that both page can call, and represent same thing.

Is there a possible way to achive that?

1 Answers

TL;DR In this situation I think I would opt to use the 4th option I present

I'm going to present 4 options, some may be more viable than others.

If you are worried about code duplication (DRY) for the code represented by execute you can simply define a function that both routes can call:

def execute():
    # execute, return a value if needed
    pass

@app.route('/')
def index():
    execute()
    return render_template('index.html', body=body, block=block)

@app.route('/api/')
def api():
    execute()
    return 'api'

This is probably what you mean and looking for.

However, if you want to actually provide two routes to the same function, you can do that also, just remember that they are getting scanned from top to bottom. Obviously you can't return 2 different values with this approach.

@app.route('/')
@app.route('/api/')
def index():
    # execute
    return render_template('index.html', body=body, block=block)


A 3rd option, which may seem like an overkill (and/or cumbersome) for what you are looking but I will mention it for the sake of completeness.

You can use a single route with an optional value, then decide what you want to return:

@app.route('/')
@app.route('/<path:address>/')
def index(address=None):
    # execute
    if address is None:
        return render_template('index.html', body=body, block=block)
    elif address == 'api':
        return 'api'
    else:
        return 'invalid value'  # or whatever else you deem appropriate


A 4th (and last, I promise) option will be to direct the 2 routes to the same function and then use the request object to find what route the client requested:

from flask import Flask, request

@app.route('/')
@app.route('/api')
def index():
    # execute
    if request.path == '/api':
        return 'api'
    return render_template('index.html', body=body, block=block)
Related