write urlqueryparse submodule for funky URL transforms
parent
e8ef36b9b1
commit
4524068245
@ -0,0 +1,39 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# -*- encoding: utf-8 -*-
|
||||||
|
|
||||||
|
# based on myurlparse.py by alexwlchan
|
||||||
|
# taken from: https://gist.github.com/alexwlchan/1956efe1acb1f2947cbd575651a3d529
|
||||||
|
# see also: https://alexwlchan.net/2016/08/dealing-with-query-strings/
|
||||||
|
|
||||||
|
try: # Python 3+
|
||||||
|
from urllib.parse import ( parse_qs, parse_qsl, urlencode, urlparse, urlunparse )
|
||||||
|
except ImportError: # Python 2
|
||||||
|
from urllib import urlencode
|
||||||
|
from urlparse import parse_qs, parse_qsl, urlparse, urlunparse
|
||||||
|
|
||||||
|
def get_query_fields( url ):
|
||||||
|
return dict( parse_qs( urlparse( url ).query ) )
|
||||||
|
|
||||||
|
def set_query_fields( url, querydict ):
|
||||||
|
components = urlparse( url )
|
||||||
|
parseddict = dict( parse_qsl( urlparse( url ).query ) )
|
||||||
|
parseddict.update( querydict )
|
||||||
|
components = ( components.scheme,
|
||||||
|
components.netloc,
|
||||||
|
components.path,
|
||||||
|
components.params,
|
||||||
|
urlencode( list( parseddict.items() ) ),
|
||||||
|
components.fragment
|
||||||
|
)
|
||||||
|
return urlunparse( components )
|
||||||
|
|
||||||
|
def set_url_components( url, scheme = None, netloc = None, path = None, params = None, query = None, fragment = None ):
|
||||||
|
components = urlparse( url )
|
||||||
|
components = ( callable( scheme ) and scheme( components.scheme ) or scheme or components.scheme,
|
||||||
|
callable( netloc ) and netloc( components.netloc ) or netloc or components.netloc,
|
||||||
|
callable( path ) and path( components.path ) or path or components.path,
|
||||||
|
callable( params ) and params( components.params ) or params or components.params,
|
||||||
|
callable( query ) and query( components.query ) or query or components.query,
|
||||||
|
callable( fragment ) and fragment( components.fragment ) or fragment or components.fragment,
|
||||||
|
)
|
||||||
|
return urlunparse( components )
|
Loading…
Reference in New Issue