Python array vertex in url_for

I can't find any information about generating a URL using so called massive queries: http://www.domain.com?page"limit>=20&page [ offset ]= 0

I've tried this:

url_for(endpoint, page={'limit': 0, 'offset': 0}, _external=True)

      

But it generated the following URL:

http://www.domain.com?page= {'limit': 0, 'offset': 0}

My current solution looks like this:

querystrings = []
querystrings.append('page[limit]=%d' % (limit))
querystrings.append('page[offset]=%d' % (offset))
url = '%s?%s' % (root_url, '&'.join(querystrings))

      

I really hope there is a better way!

Any help would be appreciated!


Edit

I ended up creating a wrapper that handles dicts separately, based on my previous solution:

from flask import g, url_for as _url_for

def url_for(endpoint, **values):
    # fix querystring dicts
    querystring_dicts = []
    for key, value in list(values.items()):
        if isinstance(value, dict):
            for _key, _value in list(value.items()):
                querystring_dicts.append('%s[%s]=%s' % (key, _key, _value))
            values.pop(key)

    # create url
    url = _url_for(endpoint, **values)

    # append querystring dicts
    if querystring_dicts:
        seperator = '?'
        if '?' in url:
            seperator = '&'
        url = '%s%s%s' % (url, seperator, '&'.join(querystring_dicts))

    return url

      

Then I call the shell like this:

url_for(endpoint, page={'limit': 20, 'offset': 0}, _external=True)

      

And it will return the following url:

http://www.domain.com?page [limit ]=20&page [offset ]=0

+3


source to share


1 answer


I don't believe that what you're trying is supported out of the box. Werkzeugurl_for

relies under the hood to convert routes to generate and encode these values, and there doesn't seem to be an encoder for the dictionaries (minor, that's what the syntax stands for {key: value}

, it's not an array).

I found this comment which describes the implementation of custom converters if you want to add support yourself. Flask project may even be happy to get PR, if you go down this route, however, if you do not want to use page[limit]

, and not page_limit

, I would have simply changed them.



url_for(endpoint, page_offset = 0, page_limit=0, _external=True)

      

+3


source







All Articles