Like quote(), but accepts a bytes object rather than a str, and does not perform string-to-bytes encoding. It always returns an ASCII string. quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
(bs, safe='/')
| 1094 | return _Quoter(safe).__getitem__ |
| 1095 | |
| 1096 | def quote_from_bytes(bs, safe='/'): |
| 1097 | """Like quote(), but accepts a bytes object rather than a str, and does |
| 1098 | not perform string-to-bytes encoding. It always returns an ASCII string. |
| 1099 | quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f' |
| 1100 | """ |
| 1101 | if not isinstance(bs, (bytes, bytearray)): |
| 1102 | raise TypeError("quote_from_bytes() expected bytes") |
| 1103 | if not bs: |
| 1104 | return '' |
| 1105 | if isinstance(safe, str): |
| 1106 | # Normalize 'safe' by converting to bytes and removing non-ASCII chars |
| 1107 | safe = safe.encode('ascii', 'ignore') |
| 1108 | else: |
| 1109 | # List comprehensions are faster than generator expressions. |
| 1110 | safe = bytes([c for c in safe if c < 128]) |
| 1111 | if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe): |
| 1112 | return bs.decode() |
| 1113 | quoter = _byte_quoter_factory(safe) |
| 1114 | if (bs_len := len(bs)) < 200_000: |
| 1115 | return ''.join(map(quoter, bs)) |
| 1116 | else: |
| 1117 | # This saves memory - https://github.com/python/cpython/issues/95865 |
| 1118 | chunk_size = math.isqrt(bs_len) |
| 1119 | chunks = [''.join(map(quoter, bs[i:i+chunk_size])) |
| 1120 | for i in range(0, bs_len, chunk_size)] |
| 1121 | return ''.join(chunks) |
| 1122 | |
| 1123 | def urlencode(query, doseq=False, safe='', encoding=None, errors=None, |
| 1124 | quote_via=quote_plus): |
searching dependent graphs…