Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1from urllib.parse import urlparse, parse_qsl, urlunparse, urlencode 

2 

3 

4def url_equals(a: str, b: str) -> bool: 

5 """ 

6 Compares two URLs/paths and returns True if they point to same URI. 

7 For example, querystring parameters can be different order but URLs are still equal. 

8 :param a: URL/path 

9 :param b: URL/path 

10 :return: True if URLs/paths are equal 

11 """ 

12 a2 = list(urlparse(a)) 

13 b2 = list(urlparse(b)) 

14 a2[4] = dict(parse_qsl(a2[4])) # type: ignore 

15 b2[4] = dict(parse_qsl(b2[4])) # type: ignore 

16 return a2 == b2 

17 

18 

19def url_mod(url: str, new_params: dict) -> str: 

20 """ 

21 Modifies existing URL by setting/overriding specified query string parameters. 

22 Note: Does not support multiple querystring parameters with identical name. 

23 :param url: Base URL/path to modify 

24 :param new_params: Querystring parameters to set/override (dict) 

25 :return: New URL/path 

26 """ 

27 res = urlparse(url) 

28 query_params = dict(parse_qsl(res.query)) 

29 for k, v in new_params.items(): 

30 if v is None: 30 ↛ 31line 30 didn't jump to line 31, because the condition on line 30 was never true

31 query_params[str(k)] = '' 

32 else: 

33 query_params[str(k)] = str(v) 

34 parts = list(res) 

35 parts[4] = urlencode(query_params) 

36 return urlunparse(parts) 

37 

38 

39def url_host(url: str) -> str: 

40 """ 

41 Parses hostname from URL. 

42 :param url: URL 

43 :return: hostname 

44 """ 

45 res = urlparse(url) 

46 return res.netloc.split(':')[0] if res.netloc else ''