Commit cefe623f0b25e45e3de3a8f0bc433cbd918d3399

Authored by Luan
1 parent 5eac0b83

Refactoring append_to_get to use urllib and urlparse

Showing 1 changed file with 6 additions and 55 deletions   Show diff stats
src/super_archives/utils/url.py
1 # -*- coding: utf-8 -*- 1 # -*- coding: utf-8 -*-
2 2
3 -def append_to_get(path, query=None, **kwargs):  
4 -# Getting the path with the query  
5 - current_url = u'{}?{}'.format(  
6 - path,  
7 - query,  
8 - ) 3 +import urllib
  4 +import urlparse
9 5
10 - if kwargs and query:  
11 - current_url += '&'  
12 6
  7 +def append_to_get(path, query=None, **kwargs):
  8 + query_dict = dict(urlparse.parse_qsl(query))
13 for key, value in kwargs.items(): 9 for key, value in kwargs.items():
14 - # get the key, value to check if the pair exists in the query  
15 - new = u'{}={}'.format(key, value)  
16 -  
17 - if new in current_url:  
18 - continue  
19 -  
20 - if u'&{}='.format(key) not in current_url:  
21 - current_url += u'{}={}&'.format(key, value)  
22 - continue  
23 -  
24 - parse_url = current_url.split(key)  
25 -  
26 - if len(parse_url) > 2:  
27 - continue  
28 -  
29 - if unicode(value) in parse_url[1][1:]:  
30 - continue  
31 -  
32 - check_kwargs_values = [  
33 - False for value in kwargs.values()  
34 - if unicode(value) not in parse_url[1]  
35 - ]  
36 -  
37 - if not all(check_kwargs_values):  
38 - list_remaining = parse_url[1][1:].split('&')  
39 - real_remaining = u''  
40 -  
41 - if len(list_remaining) >= 2:  
42 - real_remaining = u'&'.join(list_remaining[1:])  
43 -  
44 - current_url = u'{url}{key}={value}&{remaining}'.format(  
45 - url=parse_url[0],  
46 - key=key,  
47 - value=value,  
48 - remaining=real_remaining,  
49 - )  
50 - continue  
51 -  
52 - current_url = u'{url}{key}={value}+{remaining_get}'.format(  
53 - url=parse_url[0],  
54 - key=key,  
55 - value=value,  
56 - remaining_get=parse_url[1][1:],  
57 - )  
58 - if current_url[-1] == '&':  
59 - return current_url[:-1]  
60 - return current_url 10 + query_dict[key] = value
  11 + return u'{}?{}'.format(path, urllib.urlencode(query_dict))
61 12
62 13
63 def pop_from_get(path, query=None, **kwargs): 14 def pop_from_get(path, query=None, **kwargs):