Search code examples
flaskparametersblueprint

Flask blueprint and registering path


I am trying to create route and method for it with parameters. Some how I am getting error as "The requested URL was not found on the server."

If I dont pass parameters everything works fine.

app.py has below code :

def create_app():

    app = Flask(__name__)
    app.secret_key = 'ytestsone'
    app.register_blueprint(auth, url_prefix='/')
    app.register_blueprint(search, url_prefix='/search')
    return app

Search.py I have below:

search = Blueprint("search", __name__, static_folder='static', template_folder='templates')

#@search.route("/") -->this works
@search.route("/<search_key>") --> this does not work
def search_page(search_key):    --> this does not work
#def search_page(): --> this works 
    print(request.form)
    return render_template("search.html", user=current_user)

in my html I have below

<div class="col">
            <a class="btn btn-primary btn-lg" href="/search" role="button">Search Item</a>
        </div>

can someone please help me what is wrong here with passing parameters?


Solution

    1. Since you have url_prefix in your blueprint, it means the system is looking for all routes that start with that value i.e. /search. See this writeup

    2. If your flask route handler is /<search_key>, it means Flask is actually expecting a url of type /search/<search_key> but the url for your button only has /search. Therefore there is no handler for it in your App.

    3. You should try this

    @search.route("/") 
    @search.route("/<search_key>") 
    def search_page(search_key=None):
    
    

    The above will work for /search i.e. @search.route("/") and also work for /search/abc i.e. @search.route("/<search_key>"). But you'll have to add code to take care of when search_key is None