简体   繁体   中英

When using flask, what is the best way to remembering parameters while paginating?

Say that I have a results page that has several filters. The filters are passed to flask as URL parameters. But once I press Next Page, this will be forgotten. What is the best way to keep these parameters as you go from page to page?

I'm sure javascript frameworks exist to do this, but I'd rather not use javascript frameworks.

Assuming you're rendering HTML and not JSON (which it seems like you are from the tag), why not just add the filter query parameters from the request into the rendered page?

For example, something like this:

Python:

@app.route('/search')
def search():
    page_no = request.args.get('page_no')
    color = request.args.get('color')
    brand = request.args.get('brand')
    # TODO: Generate your results here..
    return render_template('results.html', results=results, page_no=page_no, brand=brand color=color)

Template:

<a href="{{ url_for('search', page_no=str(page_no - 1), brand=brand, color=color) }}">Prev</a>
<a href="{{ url_for('search', page_no=str(page_no + 1), brand=brand, color=color) }}">Next</a>

This is a minimal example. You'll also want to handle special cases like not rendering a "previous" link on the first page. Probably also some validation on the input parameters. But it demonstrates how to maintain the filter parameters in the link URL.

Depending on how many filter parameters you have, you could also consider DRYing it up something like this:

Python:

FILTER_PARAM_NAMES = ['keyword', 'date', 'foo', 'bar']
# ...
def search():
    filter_params = {f: request.args.get(f) for f in FILTER_PARAM_NAMES}
    # ...
    return render_template('results.html', results=results, **filter_params)

Template:

url_for('search', page_no=page_no, **filter_params)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM