Created
March 20, 2023 06:37
-
-
Save kLiHz/0a69230fdad282f0aa566cebfb9ef7f6 to your computer and use it in GitHub Desktop.
JavaScript-Like Wrapper for Python 3 URL Parser
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
from urllib.parse import urlparse, urljoin, parse_qsl, urlencode | |
class URLSearchParams: | |
def __init__(self, options: str = '', hook = None) -> None: | |
self.hook = hook | |
if type(options) is str: | |
if len(options) == 0: | |
self.l = list() | |
else: | |
self.l = parse_qsl(options[1:] if options[0] == '?' else options) | |
elif type(options) is list: | |
self.l = [(i[0], i[1]) for i in options] | |
elif type(options) is dict: | |
self.l = [(k, options[k]) for k in options.keys()] | |
def __str__(self) -> str: | |
return urlencode(self.l) | |
def append(self, name, value): | |
self.l.append((name, value)) | |
self.hook(self) | |
def set(self, name, value): | |
self.delete(name) | |
self.append(name, value) | |
self.hook(self) | |
def delete(self, name): | |
self.l = [t for t in self.l if t[0] != name] | |
self.hook(self) | |
def get(self, name): | |
for t in self.l: | |
if t[0] == name: | |
return t[1] | |
def getAll(self, name): | |
return [t[1] for t in self.l if t[0] == name] | |
class URL: | |
def __init__(self, url: str, base: str = None) -> None: | |
p = urlparse(url if base == None else urljoin(base, url)) | |
self.hash = p.fragment | |
self.host = p.netloc | |
self.hostname = p.netloc[:p.netloc.find(':')] | |
self.protocol = p.scheme + ':' | |
self.origin = p.scheme + '://' + self.host | |
self.password = p.password | |
self.username = p.username | |
def hook(qs): | |
self.search = qs.__str__() | |
self.searchParams = URLSearchParams(p.query, hook=hook) | |
self.search = p.query |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment