RoadieRich
RoadieRich

Reputation: 6586

Clean parsing of url query

Currently, whenever I need to parse a query string, I was originally doing

 from urllib import parse

 path = parse.urlparse(self.path)
 query = parse.parse_qs(path.query)

 value = query[name][0]

But I didn't like the [0]s dotted around my code - it felt wrong in some hard to pinpoint way, so I realised I could do

 from urllib import parse

 path = parse.urlparse(self.path)
 query = dict(parse.parse_qsl(path.query))

 value = query[name]

That has the advantage of removing the [0]'s, but it risks discarding multiple values (which should be fine for my application, which shouldn't be receiving multiple values anyway).

Is there a cleaner way of parsing urlencoded strings, that gives you a dict of minimal values: the value if there's only one value, or a list if there's multiple?

A function to do so shouldn't be too difficult, but I'm curious if there's a library that does this so I don't need to reinvent the wheel.

Upvotes: 0

Views: 94

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76386

In general, if you have such a dictionary query, you could always do

query = {[(k, v[0] if len(v) == 1 else v) for k, v in query.iteritems()]}

However, I really dislike this code, as it just produces stuff that is unintuitive later on.

Upvotes: 2

Related Questions