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='/')
| 921 | return _Quoter(safe).__getitem__ |
| 922 | |
| 923 | def quote_from_bytes(bs, safe='/'): |
| 924 | """Like quote(), but accepts a bytes object rather than a str, and does |
| 925 | not perform string-to-bytes encoding. It always returns an ASCII string. |
| 926 | quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f' |
| 927 | """ |
| 928 | if not isinstance(bs, (bytes, bytearray)): |
| 929 | raise TypeError("quote_from_bytes() expected bytes") |
| 930 | if not bs: |
| 931 | return '' |
| 932 | if isinstance(safe, str): |
| 933 | # Normalize 'safe' by converting to bytes and removing non-ASCII chars |
| 934 | safe = safe.encode('ascii', 'ignore') |
| 935 | else: |
| 936 | # List comprehensions are faster than generator expressions. |
| 937 | safe = bytes([c for c in safe if c < 128]) |
| 938 | if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe): |
| 939 | return bs.decode() |
| 940 | quoter = _byte_quoter_factory(safe) |
| 941 | return ''.join([quoter(char) for char in bs]) |
| 942 | |
| 943 | def urlencode(query, doseq=False, safe='', encoding=None, errors=None, |
| 944 | quote_via=quote_plus): |