Skip to content
Myr

utils.py

This file

Path

httpcore/utils.py

71 lines · 2.2 KiB · Python

Last changed by

Nicer headers interfaceTom Christiebefore adoption05e0649

History of this file

Take it

Nicer headers interfaceTom Christiebefore adoption05e0649

line 1why, one step back
1import typing

Rollin'Tom Christiebefore adoption8a29a0a

lines 2–12why, one step back
2from urllib.parse import quote
34from .exceptions import InvalidURL56# The unreserved URI characters (RFC 3986)7UNRESERVED_SET = frozenset(8 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"9)101112def unquote_unreserved(uri: str) -> str:

RestructuringTom Christiebefore adoptione09fc37

lines 13–14why, one step back
13 """
14 Un-escape any percent-escape sequences in a URI that are unreserved

Rollin'Tom Christiebefore adoption8a29a0a

lines 15–53why, one step back
15 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
16 """17 parts = uri.split("%")18 for i in range(1, len(parts)):19 h = parts[i][0:2]20 if len(h) == 2 and h.isalnum():21 try:22 c = chr(int(h, 16))23 except ValueError:24 raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)2526 if c in UNRESERVED_SET:27 parts[i] = c + parts[i][2:]28 else:29 parts[i] = "%" + parts[i]30 else:31 parts[i] = "%" + parts[i]32 return "".join(parts)333435def requote_uri(uri: str) -> str:36 """37 Re-quote the given URI.3839 This function passes the given URI through an unquote/quote cycle to40 ensure that it is fully and consistently quoted.41 """42 safe_with_percent = "!#$%&'()*+,/:;=?@[]~"43 safe_without_percent = "!#$&'()*+,/:;=?@[]~"44 try:45 # Unquote only the unreserved characters46 # Then quote only illegal characters (do not quote reserved,47 # unreserved, or '%')48 return quote(unquote_unreserved(uri), safe=safe_with_percent)49 except InvalidURL:50 # We couldn't unquote the given URI, so let's try quoting it, but51 # there may be unquoted '%'s in the URI. We need to make sure they're52 # properly quoted so they do not cause issues elsewhere.53 return quote(uri, safe=safe_without_percent)

Nicer headers interfaceTom Christiebefore adoption05e0649

lines 54–71why, one step back
54
5556def normalize_header_key(value: typing.AnyStr) -> bytes:57 """58 Coerce str/bytes into a strictly byte-wise HTTP header key.59 """60 if isinstance(value, bytes):61 return value.lower()62 return value.encode("latin-1").lower()636465def normalize_header_value(value: typing.AnyStr) -> bytes:66 """67 Coerce str/bytes into a strictly byte-wise HTTP header value.68 """69 if isinstance(value, bytes):70 return value71 return value.encode("latin-1")