[230] | 1 | # -*- coding: utf-8 -*-
|
---|
| 2 | # Copyright (c) 2014 Rackspace
|
---|
| 3 | # Licensed under the Apache License, Version 2.0 (the "License");
|
---|
| 4 | # you may not use this file except in compliance with the License.
|
---|
| 5 | # You may obtain a copy of the License at
|
---|
| 6 | #
|
---|
| 7 | # http://www.apache.org/licenses/LICENSE-2.0
|
---|
| 8 | #
|
---|
| 9 | # Unless required by applicable law or agreed to in writing, software
|
---|
| 10 | # distributed under the License is distributed on an "AS IS" BASIS,
|
---|
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
---|
| 12 | # implied.
|
---|
| 13 | # See the License for the specific language governing permissions and
|
---|
| 14 | # limitations under the License.
|
---|
| 15 | """Compatibility module for Python 2 and 3 support."""
|
---|
| 16 | import sys
|
---|
| 17 |
|
---|
| 18 | try:
|
---|
| 19 | from urllib.parse import quote as urlquote
|
---|
| 20 | except ImportError: # Python 2.x
|
---|
| 21 | from urllib import quote as urlquote
|
---|
| 22 |
|
---|
| 23 | try:
|
---|
| 24 | from urllib.parse import parse_qsl
|
---|
| 25 | except ImportError: # Python 2.x
|
---|
| 26 | from urlparse import parse_qsl
|
---|
| 27 |
|
---|
| 28 | try:
|
---|
| 29 | from urllib.parse import urlencode
|
---|
| 30 | except ImportError: # Python 2.x
|
---|
| 31 | from urllib import urlencode
|
---|
| 32 |
|
---|
| 33 | __all__ = (
|
---|
| 34 | "to_bytes",
|
---|
| 35 | "to_str",
|
---|
| 36 | "urlquote",
|
---|
| 37 | "urlencode",
|
---|
| 38 | "parse_qsl",
|
---|
| 39 | )
|
---|
| 40 |
|
---|
| 41 | PY3 = (3, 0) <= sys.version_info < (4, 0)
|
---|
| 42 | PY2 = (2, 6) <= sys.version_info < (2, 8)
|
---|
| 43 |
|
---|
| 44 |
|
---|
| 45 | if PY3:
|
---|
| 46 | unicode = str # Python 3.x
|
---|
| 47 |
|
---|
| 48 |
|
---|
| 49 | def to_str(b, encoding="utf-8"):
|
---|
| 50 | """Ensure that b is text in the specified encoding."""
|
---|
| 51 | if hasattr(b, "decode") and not isinstance(b, unicode):
|
---|
| 52 | b = b.decode(encoding)
|
---|
| 53 | return b
|
---|
| 54 |
|
---|
| 55 |
|
---|
| 56 | def to_bytes(s, encoding="utf-8"):
|
---|
| 57 | """Ensure that s is converted to bytes from the encoding."""
|
---|
| 58 | if hasattr(s, "encode") and not isinstance(s, bytes):
|
---|
| 59 | s = s.encode(encoding)
|
---|
| 60 | return s
|
---|