shane806 / async_googlemaps

1 stars 0 forks source link

"places_photo" method does not seem to work #1

Open saizk opened 1 year ago

saizk commented 1 year ago

When calling places_photo() method it causes the following error:

with open('test.jpg', 'wb') as f:
    for chunk in gmaps.places_photo(photo_reference, max_width=100):
        if chunk:
            f.write(chunk)

TypeError: 'coroutine' object is not iterable
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001DEA4C4E310>

When the function call is awaited another error appears:

with open('test.jpg', 'wb') as f:
    for chunk in await gmaps.places_photo(photo_reference, max_width=100):
        if chunk:
            f.write(chunk)

async_googlemaps.exceptions.TransportError: ClientSession._request() got an unexpected keyword argument 'stream'
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001BD48A1E290>

I have modified places_photo() as follows:

...
response = await client._request(
    "/maps/api/place/photo",
    params,
    extract_body=lambda response: response,
    aiohttp_kwargs={"chunked": True},  # aiohttp_kwargs={"stream": True},
)
return response.content.iter_chunks()  # return response.iter_content()

But I got another error with less information:

aiohttp.client_exceptions.ClientConnectionError: Connection closed
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001C576452950>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x000001C576433C40>, 226194.703)]']
connector: <aiohttp.connector.TCPConnector object at 0x000001C576452990>

My Python version is 3.11.0 And my requirements are the following:

aiohttp            3.8.4
aiosignal          1.3.1
async-timeout      4.0.2
attrs              23.1.0
certifi            2023.5.7
charset-normalizer 3.1.0
frozenlist         1.3.3
googlemaps         4.10.0
idna               3.4
multidict          6.0.4
pip                21.3.1
requests           2.31.0
setuptools         60.2.0
urllib3            2.0.3
wheel              0.37.1
yarl               1.9.2

I would appreciate if you can help me with this issue. Thank you!

saizk commented 1 year ago

I have solved the issue by modifying the method places_photo() as follows:

params = {"photoreference": photo_reference, "key": client.key}

if max_width:
    params["maxwidth"] = max_width
if max_height:
    params["maxheight"] = max_height

 async with client.aiohttp_session as session:
    async with session.get('https://maps.googleapis.com/maps/api/place/photo', params=params) as resp:
        if resp.status != 200:
            raise ValueError(f"Unable to download image, status code: {resp.status}")
        image_content = await resp.read()

return image_content

It does not use native method client._request() but it solves the issue.

After that the image is saved normally:

with open(output_dir, 'wb') as f:
    f.write(image)