I am using this awesome library called requests
to maintain python 2 & 3 compatibility and simplify my application requests management.
I have a case where I need to parse a url and replace one of it's parameter. E.g:
http://example.com?param1=a&token=TOKEN_TO_REPLACE¶m2=c
And I want to get this:
http://example.com?param1=a&token=NEW_TOKEN¶m2=c
With the urllib
I can achieve it this way:
from urllib.parse import urlparse
from urllib.parse import parse_qs
from urllib.parse import urlencode
url = 'http://example.com?param1=a&token=TOKEN_TO_REPLACE¶m2=c'
o = urlparse(url)
query = parse_qs(o.query)
if query.get('token'):
query['token'] = ['NEW_TOKEN', ]
new_query = urlencode(query, doseq=True)
url.split('?')[0] + '?' + new_query
>>> http://example.com?param2=c¶m1=a&token=NEW_TOKEN
How can you achieve the same using the requests
library?