Skip to content

Commit f7a1b93

Browse files
authored
Merge branch 'master' into i19_better_idna
2 parents 91ca177 + 17dc8d3 commit f7a1b93

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

Diff for: hyperlink/_url.py

+15
Original file line numberDiff line numberDiff line change
@@ -1392,6 +1392,21 @@ def __repr__(self):
13921392
"""
13931393
return '%s.from_text(%r)' % (self.__class__.__name__, self.to_text())
13941394

1395+
def _to_bytes(self):
1396+
"""
1397+
Allows for direct usage of URL objects with libraries like
1398+
requests, which automatically stringify URL parameters. See
1399+
issue #49.
1400+
"""
1401+
return self.to_uri().to_text().encode('ascii')
1402+
1403+
if PY2:
1404+
__str__ = _to_bytes
1405+
__unicode__ = to_text
1406+
else:
1407+
__bytes__ = _to_bytes
1408+
__str__ = to_text
1409+
13951410
# # Begin Twisted Compat Code
13961411
asURI = to_uri
13971412
asIRI = to_iri

Diff for: hyperlink/test/test_url.py

+18-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from __future__ import unicode_literals
77

8+
import sys
89
import socket
910

1011
from .common import HyperlinkTestCase
@@ -13,6 +14,8 @@
1314
from .. import _url
1415
from .._url import inet_pton, SCHEME_PORT_MAP, parse_host
1516

17+
18+
PY2 = (sys.version_info[0] == 2)
1619
unicode = type(u'')
1720

1821

@@ -1150,8 +1153,7 @@ def test_normalize(self):
11501153

11511154
# test invalid percent encoding during normalize
11521155
assert URL(path=('', '%te%sts')).normalize().to_text() == '/%te%sts'
1153-
1154-
1156+
11551157
def test_idna_corners(self):
11561158
text = u'http://abé.com/'
11571159
url = URL.from_text(text)
@@ -1165,3 +1167,17 @@ def test_idna_corners(self):
11651167
assert url.to_uri().get_decoded_url().host == u'ドメイン.テスト.co.jp'
11661168

11671169
assert URL.from_text('http://Example.com').to_uri().get_decoded_url().host == 'example.com'
1170+
1171+
def test_str(self):
1172+
# see also issue #49
1173+
text = u'http://example.com/á/y%20a%20y/?b=%25'
1174+
url = URL.from_text(text)
1175+
assert unicode(url) == text
1176+
assert bytes(url) == b'http://example.com/%C3%A1/y%20a%20y/?b=%25'
1177+
1178+
if PY2:
1179+
assert isinstance(str(url), bytes)
1180+
assert isinstance(unicode(url), unicode)
1181+
else:
1182+
assert isinstance(str(url), unicode)
1183+
assert isinstance(bytes(url), bytes)

0 commit comments

Comments
 (0)