unquote_to_bytes('abc%20def') -> b'abc def'.
(string)
| 625 | _hextobyte = None |
| 626 | |
| 627 | def unquote_to_bytes(string): |
| 628 | """unquote_to_bytes('abc%20def') -> b'abc def'.""" |
| 629 | # Note: strings are encoded as UTF-8. This is only an issue if it contains |
| 630 | # unescaped non-ASCII characters, which URIs should not. |
| 631 | if not string: |
| 632 | # Is it a string-like object? |
| 633 | string.split |
| 634 | return b'' |
| 635 | if isinstance(string, str): |
| 636 | string = string.encode('utf-8') |
| 637 | bits = string.split(b'%') |
| 638 | if len(bits) == 1: |
| 639 | return string |
| 640 | res = [bits[0]] |
| 641 | append = res.append |
| 642 | # Delay the initialization of the table to not waste memory |
| 643 | # if the function is never called |
| 644 | global _hextobyte |
| 645 | if _hextobyte is None: |
| 646 | _hextobyte = {(a + b).encode(): bytes.fromhex(a + b) |
| 647 | for a in _hexdig for b in _hexdig} |
| 648 | for item in bits[1:]: |
| 649 | try: |
| 650 | append(_hextobyte[item[:2]]) |
| 651 | append(item[2:]) |
| 652 | except KeyError: |
| 653 | append(b'%') |
| 654 | append(item) |
| 655 | return b''.join(res) |
| 656 | |
| 657 | _asciire = re.compile('([\x00-\x7f]+)') |
| 658 |