Only pass arguments that aren't None to Flask's url_for

时间:2019-04-17 00:43:11

标签: python flask

I am currently trying to set up a search in Flask using keywords and the form GET method.

To handle pagination, I have to pass all the keywords for the filters to the url_for for the next or last pages. However, sometimes these keywords aren't needed and just clutter up the url bar.

{{ url_for(request.endpoint, page=pagination.next_num, searchTerm=searchTerm, blendLicense=blendLicense, renderEngine=renderEngine, blenderVersion=blenderVersion) }}

Is there a way to only pass the keywords that aren't None so as not to clutter up the URL bar? If it were only one keyword to check, I'd use an if else block, but there are many keywords to check.

2 个答案:

答案 0 :(得分:0)

Perform the call like this:

kwargs = dict(searchTerm=searchTerm,
              blendLicense=blendLicense,
              renderEngine=renderEngine,
              blenderVersion=blenderVersion)

url_for(request.endpoint, page=pagination.next_num, **kwargs)

This works same as the code in your question. But now you can conveniently filter out a default value such as None:

def filter_default(kwargs):
    return {k: v
            for k, v in kwargs.items()
            if v}

(Or, use if v is not None if values like empty string might be present.)

Apply that filtering function to the dictionary before passing it in.

EDIT

{{ url_for(request.endpoint,
           page=pagination.next_num,
           **filter_default(dict(searchTerm=searchTerm,
                                 blendLicense=blendLicense,
                                 renderEngine=renderEngine,
                                 blenderVersion=blenderVersion))) }}

答案 1 :(得分:0)

url_for已经忽略了None的关键字。您无需在此之上做任何事情。

@app.route("/search")
def search():
    ...
url_for("search", name="Flask", page=2))
"/search?name=Flask&page=2"
url_for("search", name="Flask", page=None))
"/search?name=Flask"