Created
August 13, 2021 09:25
-
-
Save alexbodn/f0cef7bf95b5548946f6d9f08c2edad7 to your computer and use it in GitHub Desktop.
url builder in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
from urllib.parse import urlunparse, ParseResult, urlencode, quote, unquote | |
def url_builder( | |
netloc=None, hostname=None, port=None, username=None, password=None, | |
scheme='http', params='', fragment='', path=(), query=dict()): | |
""" | |
build an url from the fields returned by urlparse. | |
please note, path may be an iterable of unicode strings, or | |
a string made of parts that each of them is quoted, joined by '/' | |
""" | |
if hostname: | |
netloc = hostname | |
if port and ':' not in netloc: | |
netloc += (':%d' % port) | |
if username: | |
user = username | |
if password: | |
user += ':%s' % password | |
netloc = '%s@%s' % (user, netloc) | |
if isinstance(path, str): | |
path = [unquote(_dir) for _dir in path.split('/')] | |
path = '/'.join([quote(_dir, safe='') for _dir in path]) | |
ql = list() | |
try: | |
for (k, v) in query.items(): | |
if not isinstance(v, str): | |
try: | |
for v1 in v: | |
ql.append((k, v1)) | |
continue | |
except: | |
pass | |
ql.append((k, v)) | |
except: | |
ql = query | |
query = urlencode(ql) | |
build = ParseResult(scheme, netloc, path, params, query, fragment) | |
return urlunparse(build) | |
def test(): | |
url = 'amqp://guest:guest@localhost:5672/%2F?connection_attempts=3&heartbeat=3600' | |
parts1 = dict( | |
scheme='aqmp', hostname='localhost', port=5672, path='%2F', | |
username='guest', password='guest', | |
query=dict(connection_attempts=3, heartbeat=[3600, 3601]), | |
) | |
parts2 = dict( | |
scheme='aqmp', netloc='localhost:5672', path=['/'], | |
username='guest', password='guest', | |
query=(('connection_attempts', 3), ('heartbeat', 3600), ('heartbeat', 3601)), | |
) | |
print(url) | |
print(url_builder(**parts1)) | |
print(url_builder(**parts2)) | |
if __name__ == '__main__': | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment