Aarushi
Aarushi

Reputation: 564

Correct Url generation flask

I have a flask app in which there is a template with a form. It contain 2 options and when the user submit them. It generates a url like

http://127.0.0.1:5000/search/?code=L00&option=cin

so i get both values like this:

ta = request.args.get('code', "", type=str)
tb = request.args.get('option', "", type=str)

now after some processing on it. I generate the result. There are many results so i have pagination applied to it. The problem is how do i form the url?

@app.route('/search/', defaults={'page': 1})
@app.route('/search/page/<int:page>')
def search(page):
    ta = request.args.get('code', "", type=str)
    tb = request.args.get('option', "", type=str)
    ***some processing ***

this won't work because '/search/page/<int:page>' this is not right. I need something like this '/search/?code=L00&option=cin/page/<int:page>' Now how do i get this? I tried this too while testing it:

with app.test_request_context():
    print url_for('search',code='L00',option='cin',page=3)

but it generates /searcht/page/3?code=L00&option=cin

Upvotes: 1

Views: 123

Answers (2)

Sean Azlin
Sean Azlin

Reputation: 916

I think you have two options here: Either define the page you want as a resource using:

'/search/page/<int:page>'

or define the page you want as another query arg, like you're doing with 'code' and 'option'. Why aren't either of those options workable for you?

Also, it'd help if you include an example of the URL that you ultimately want flask to generate... I'm not sure what you're expecting from this code:

'/search/?code=L00&option=cin/page/<int:page>'

Upvotes: 0

Dragu
Dragu

Reputation: 3297

Why don't you make something like this ?

@app.route('/search'
def search():
    tp = request.args.get('page', 1, type=int)
    ta = request.args.get('code', "", type=str)
    tb = request.args.get('option', "", type=str)
    ***some processing ***

page is a url param, and you just define the default as 1. Then your url_for will generate correct url like

/search?code=L00&option=cin&page=3

Upvotes: 2

Related Questions