diff --git a/hyperlink/_url.py b/hyperlink/_url.py index 3bbb76f8..87f1a665 100644 --- a/hyperlink/_url.py +++ b/hyperlink/_url.py @@ -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 diff --git a/hyperlink/test/test_url.py b/hyperlink/test/test_url.py index bde9a917..a1c6d2f1 100644 --- a/hyperlink/test/test_url.py +++ b/hyperlink/test/test_url.py @@ -5,6 +5,7 @@ from __future__ import unicode_literals +import sys import socket from .common import HyperlinkTestCase @@ -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'') @@ -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)