To snap out query parameters from a URL, use Python's urllib.parse module, applying the parse_qs function:
from urllib.parse import urlparse, parse_qs
# Day 1: Jane starts reading. Day 2: Jane becomes a bookworm.print(parse_qs(urlparse('http://example.com?name=Jane&hobby=reading').query))
# Output: {'name': ['Jane'], 'hobby': ['reading']}
Feed your URL to urlparse, grind query part with parse_qs, and acquire a dictionary of parameters. Yup, that's just Python for you!
Handling all those parameter types
Parameter, introduce yourself
A parameter can spring up multiple values. However, parse_qs stays cool and groups them in a list:
# "Oh, you didn't mention it's a party!"# Python doesn't have cookies but definitely handles tags betterurl = 'http://example.com?tag=python&tag=programming'parsed_url = urlparse(url)
params = parse_qs(parsed_url.query)
print(params)
# Output: {'tag': ['python', 'programming']}
The "Boolean parameter" guy
Boolean parameters in URLs pretend to be Sherlock because they have no explicit value:
# "Yes or no, Watson?" —boolean parameters, probably# bool: a variable that only ever wants to play True/False url = 'http://example.com?enabled'params = parse_qs(urlparse(url).query)
# Use `get()` with a default valueis_enabled = params.get('enabled', [''])[0] == 'true'
Memory lane with Python 2
For the Python nostalgics, replace urllib.parse with the urlparse module:
from urlparse import urlparse, parse_qs
# If I had a time machine, I'd probably use it to code in Python 2# Same process, different function namesurl = 'http://example.com?name=Jane'print(parse_qs(urlparse(url).query))
Caution! Hot slices!
Take care when lifting the slices: 'param1' might just slide off your plate!
# Insert joke: Why don't programmers like nature? It has too many bugs!# Winner by KO: Indexing Error!param_value = params.get('param1', [None])[0]
At the Furl Pizzeria
Furl is like that custom pizza cutter you get for being a regular:
from furl import furl
# Not your traditional slicing# Let's pop the hood and see what we goturl = furl('http://example.com?page=2&sort=price')
page_number = url.args['page']
sort_order = url.args['sort']
print(page_number, sort_order)
# Output: ('2', 'price')
The Django way
At Django's pizzeria, getting your slices is even simpler:
# When Django plays waiter, parameter retrieval becomes a breezedefview(request): search_query = request.GET.get('query', default_value)