Zack
Zack

Reputation: 13982

Redirect flask route if input matches something in data struct

Should be pretty basic. I am doing somewhat of a search with a flask app I am developing.

@app.route('/search_results/<search_string>', methods= ['GET', 'POST'])
def generateSearchResults(search_string = None):

    #an exact match
    if search_string in data_struct:
        return displayInfomation(search_string)

    else:
         #code that will figure out possible matches, and then render 
         #a template based on that

@app.route('/display_results/<search_string>', methods= ['GET', 'POST'])
def displayInfomation(search_string = None):

    #figures some stuff out based on the search string, then renders a template

For those of you not good at reading code, I am attempting to take another route if the thing passed in the url can be found in the datastruct I am using. However, when I try this, I see in the url bar

http://my_site_name/search_results/search_string

So it clearly ISN'T calling my displayInfomation function. I tried the thing that seemed intuitive to me, does anyone know how this can be done?

Upvotes: 2

Views: 3661

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124988

You are simply reusing another view to do the rendering here. Provided your if search_string in data_struct test is True, the other view is used as a function, and it will be called. That has little to do with the URL shown in the browser, as the browser doesn't know or care what the server does when accessing the /search_results/search_string URL.

If you wanted the URL to change you'd use redirect() to instruct the browser to load the other view:

from flask import redirect, url_for


@app.route('/search_results/<search_string>', methods= ['GET', 'POST'])
def generateSearchResults(search_string = None):

    if search_string in data_struct:
        return redirect(url_for('displayInfomation', search_string=search_string))


@app.route('/display_results/<search_string>', methods= ['GET', 'POST'])
def displayInfomation(search_string = None):

The url_for() call will construct a valid URL for the displayInformation view filling in search_string for you, and redirect() creates a response with a 302 redirect status.

Upvotes: 1

Related Questions