Skip to content

Commit bc063e9

Browse files
Use get authed_url, add url_signed test
1 parent 4575587 commit bc063e9

File tree

4 files changed

+51
-35
lines changed

4 files changed

+51
-35
lines changed

aiogmaps/client.py

Lines changed: 16 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import asyncio
22
import logging
3+
import re
34

45
import aiohttp
56
import googlemaps
6-
from googlemaps.client import urlencode_params, sign_hmac
7+
from googlemaps import client as gmaps_client
78
from yarl import URL
89

910
from . import __version__
@@ -27,7 +28,7 @@
2728
class Client:
2829
def __init__(self, key=None, client_id=None, client_secret=None,
2930
session=None, close_session=False, verify_ssl=True,
30-
request_timeout=10, loop=None):
31+
request_timeout=10, channel=None, loop=None):
3132
if loop is None:
3233
loop = asyncio.get_event_loop()
3334

@@ -45,6 +46,16 @@ def __init__(self, key=None, client_id=None, client_secret=None,
4546
self.client_secret = client_secret
4647
self.request_timeout = request_timeout
4748

49+
if channel:
50+
if not client_id:
51+
raise ValueError("The channel argument must be used with a "
52+
"client ID")
53+
if not re.match("^[a-zA-Z0-9._-]*$", channel):
54+
raise ValueError("The channel argument must be an ASCII "
55+
"alphanumeric string. The period (.), underscore (_)"
56+
"and hyphen (-) characters are allowed.")
57+
self.channel = channel
58+
4859
self.close_session = close_session
4960
self.verify_ssl = verify_ssl
5061

@@ -62,7 +73,7 @@ def __init__(self, key=None, client_id=None, client_secret=None,
6273

6374
self.session = session
6475

65-
self.base_url = URL('https://maps.googleapis.com/')
76+
self.base_url = URL('https://maps.googleapis.com')
6677
self._user_agent = 'AsyncGoogleGeoApiClientPython/{}'.format(
6778
__version__)
6879
self._headers = {
@@ -72,20 +83,6 @@ def __init__(self, key=None, client_id=None, client_secret=None,
7283
def __getitem__(self, name):
7384
return getattr(self, name)
7485

75-
def _get_params(self, path, params, accepts_clientid):
76-
params = sorted(dict(params).items())
77-
if self.key is not None:
78-
if isinstance(params, (list, tuple)):
79-
params.append(('key', self.key))
80-
81-
if accepts_clientid and self.client_id and self.client_secret:
82-
params.append(("client", self.client_id))
83-
path = "?".join([str(path), urlencode_params(params)])
84-
sig = sign_hmac(self.client_secret, path)
85-
params.append(("signature", sig))
86-
87-
return params
88-
8986
async def _request(
9087
self,
9188
url,
@@ -106,22 +103,12 @@ async def _request(
106103
base_url = self.base_url
107104

108105
base_url = URL(base_url)
109-
params = self._get_params(
110-
path='/' + url.lstrip('/'),
111-
params=params,
112-
accepts_clientid=accepts_clientid
113-
)
106+
authed_url = gmaps_client.Client._generate_auth_url(self, '/' + url.lstrip('/'), params, accepts_clientid)
114107

115108
if aiohttp3:
116109
# https://docs.aiohttp.org/en/stable/client_reference.html#aiohttp.ClientSession.request
117110
kwargs.update({'ssl': self.verify_ssl})
118-
119-
combined_url = URL(
120-
"?".join([str(base_url / url.lstrip('/')),
121-
urlencode_params(params)]),
122-
encoded=True
123-
)
124-
111+
combined_url = URL(str(base_url) + authed_url, encoded=True)
125112
if post_json is not None:
126113
method = 'POST'
127114
data = post_json

tests/test_client.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from aiohttp import web
2+
from googlemaps.client import sign_hmac, urlencode_params
3+
4+
import aiogmaps
5+
6+
7+
async def test_url_signed(aresponses):
8+
client_id = "foo"
9+
client_secret = "test"
10+
address = "Test St."
11+
client = aiogmaps.Client(client_id=client_id, client_secret=client_secret)
12+
params = {
13+
'address': address,
14+
'client': client_id
15+
}
16+
path = "?".join(['/maps/api/geocode/json', urlencode_params(params.items())])
17+
expected_signature = sign_hmac(client_secret, path)
18+
aresponses.add(
19+
'maps.googleapis.com',
20+
path + '{}{}'.format('&signature=', expected_signature),
21+
'get',
22+
aresponses.Response(
23+
body='{"status": "OK", "results": ["foo"]}',
24+
status=web.HTTPOk.status_code,
25+
content_type='application/json',
26+
),
27+
match_querystring=True,
28+
)
29+
resp = await client.geocode(address)
30+
assert resp == ['foo']

tests/test_places.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ async def test_place(aresponses, client, api_key):
1111
patched_url = URL.build(
1212
path='/maps/api/place/details/json',
1313
query={
14-
'key': api_key,
1514
'placeid': place_id,
15+
'key': api_key
1616
},
1717
)
1818

@@ -36,13 +36,12 @@ async def test_places(aresponses, client, api_key):
3636
patched_url = URL.build(
3737
path='/maps/api/place/textsearch/json',
3838
query={
39-
'key': api_key,
40-
'minprice': 0,
4139
'maxprice': 4,
40+
'minprice': 0,
4241
'query': 'Google',
42+
'key': api_key
4343
},
4444
)
45-
4645
aresponses.add(
4746
'maps.googleapis.com',
4847
patched_url.human_repr(),
@@ -115,8 +114,8 @@ async def test_autocomplete(aresponses, client, api_key, query_type, handler):
115114
patched_url = URL.build(
116115
path=f'/maps/api/place/{query_type}autocomplete/json',
117116
query={
118-
'key': api_key,
119117
'input': 'Google',
118+
'key': api_key
120119
},
121120
)
122121

tests/test_timezone.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ async def test_timezone(aresponses, client, api_key):
88
patched_path = URL.build(
99
path='/maps/api/timezone/json',
1010
query={
11-
'key': api_key,
1211
'location': '{},{}'.format(*location),
1312
'timestamp': timestamp,
13+
'key': api_key
1414
},
1515
)
1616

0 commit comments

Comments
 (0)