Broke down and wrote a thin compat module

This commit is contained in:
Ian Cordasco
2014-06-27 16:18:17 -05:00
parent 1c57749752
commit 58d167d9d2
3 changed files with 48 additions and 6 deletions

31
rfc3986/compat.py Normal file
View File

@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Rackspace
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
if sys.version_info >= (3, 0):
unicode = str # Python 3.x
def to_str(b, encoding):
if hasattr(b, 'decode') and not isinstance(b, unicode):
b = b.decode('utf-8')
return b
def to_bytes(s, encoding):
if hasattr(s, 'encode') and not isinstance(s, bytes):
s = s.encode('utf-8')
return s

View File

@@ -14,6 +14,7 @@
# limitations under the License.
import re
from .compat import to_bytes
from .misc import NON_PCT_ENCODED
@@ -95,10 +96,7 @@ def encode_component(uri_component, encoding):
if uri_component is None:
return uri_component
# We had a conditional to ensure we wouldn't hit a NoMethodError on
# Python3, but we're guaranteed to always have a unicode string passed in.
# I couldn't craft a test that would hit the else condition
uri_bytes = uri_component.encode(encoding)
uri_bytes = to_bytes(uri_component, encoding)
encoded_uri = bytearray()

View File

@@ -1,6 +1,20 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Rackspace
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import namedtuple
from .compat import to_str
from .exceptions import InvalidAuthority
from .misc import (
FRAGMENT_MATCHER, PATH_MATCHER, QUERY_MATCHER, SCHEME_MATCHER,
@@ -48,8 +62,7 @@ class URIReference(namedtuple('URIReference', URI_COMPONENTS)):
:param str encoding: The encoding of the string provided
:returns: :class:`URIReference` or subclass thereof
"""
if hasattr(uri_string, 'decode'):
uri_string = uri_string.decode(encoding)
uri_string = to_str(uri_string, encoding)
split_uri = URI_MATCHER.match(uri_string).groupdict()
return URIReference(split_uri['scheme'], split_uri['authority'],