0

I am creating a webapp with Python/Flask. I am using blueprints.

Say I search for a book and end up at the URL /search?book=somebook&author=someauthor via a GET request. On that page I have buttons for each result which will save that result to the user's saved books. This would be a POST request. However, I want to return the user to the same search page with the same URL params.

So the flow is:

  1. User submits a search and ends up on /search?book=somebook&author=someauthor
  2. User clicks subscribe on one of the results. A POST saves the book to the user's saved books.
  3. User ends up on /search?book=somebook&author=someauthor again and the search result page is repopulated.

I think, incorrectly, I want something like this:

@search_bp.route('/search', methods=["GET", "POST"]) def search(): if request.method == "POST": # save book to user's saved books # somehow end up back on the same page from here elif request.method == "GET": # use request.args to populate page with results return render_template("search.html", books=books) 

In my mind I want to return redirect(url_for("search_bp.search")) but somehow get the request.args back into the URL. Is my only choice to hardcode the URL, i.e. concatenate a string url = "/search?book=" + request.args.get("book") + "&author=" + request.args.get("author") so that I can return redirect(url)?

1 Answer 1

2

You can pass values/variables to flask.url_for, example:

book = request.args.get('book') author = request.args.get('author') my_url = url_for('search_bp.search', book=book, author=author) 

Additional values/parameters passed to url_for will be added to the URL as GET parameters, then you can do return redirect(my_url).

https://flask.palletsprojects.com/en/1.1.x/api/#flask.url_for

Sign up to request clarification or add additional context in comments.

1 Comment

Ah I'm a dolt. I thought that would pass them as template variables. I'll try it out tomorrow and approve your answer then.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.