Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions hyperlink/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -1343,6 +1343,21 @@ def __repr__(self):
"""
return '%s.from_text(%r)' % (self.__class__.__name__, self.to_text())

def _to_bytes(self):
"""
Allows for direct usage of URL objects with libraries like
requests, which automatically stringify URL parameters. See
issue #49.
"""
return self.to_uri().to_text().encode('ascii')

if PY2:
__str__ = _to_bytes
__unicode__ = to_text
else:
__bytes__ = _to_bytes
__str__ = to_text

# # Begin Twisted Compat Code
asURI = to_uri
asIRI = to_iri
Expand Down
17 changes: 17 additions & 0 deletions hyperlink/test/test_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from __future__ import unicode_literals

import sys
import socket

from .common import HyperlinkTestCase
Expand All @@ -13,6 +14,8 @@
from .. import _url
from .._url import inet_pton, SCHEME_PORT_MAP, parse_host


PY2 = (sys.version_info[0] == 2)
unicode = type(u'')


Expand Down Expand Up @@ -1150,3 +1153,17 @@ def test_normalize(self):

# test invalid percent encoding during normalize
assert URL(path=('', '%te%sts')).normalize().to_text() == '/%te%sts'

def test_str(self):
# see also issue #49
text = u'http://example.com/á/y%20a%20y/?b=%25'
url = URL.from_text(text)
assert unicode(url) == text
assert bytes(url) == b'http://example.com/%C3%A1/y%20a%20y/?b=%25'

if PY2:
assert isinstance(str(url), bytes)
assert isinstance(unicode(url), unicode)
else:
assert isinstance(str(url), unicode)
assert isinstance(bytes(url), bytes)