Created
September 1, 2020 12:07
-
-
Save SebDeclercq/e4759db36fbb72844387066f9ccab433 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
import sys | |
import time | |
from typing import Any, ClassVar, Dict, List | |
import asyncio | |
from gql import gql, Client, AIOHTTPTransport | |
from graphql.language.ast import DocumentNode | |
@dataclass | |
class Artist: | |
'''Basic Artist representation.''' | |
name: str | |
slug: str | |
qwant_url: str | |
class QwantMusicClient: | |
TRANSPORT: ClassVar[AIOHTTPTransport] = AIOHTTPTransport( | |
url='https://qwant-music.herokuapp.com/graphql/' | |
) | |
QUERY: ClassVar[DocumentNode] = gql( | |
''' | |
query($name: String!) { | |
artist(name: $name) { | |
name | |
slug | |
qwantUrl | |
} | |
} | |
''' | |
) | |
@classmethod | |
async def fetch_artists(cls, artists: List[str]) -> List[Artist]: | |
"""Fetch Artists from the API asynchronously and print the lasting | |
time. | |
Params: | |
artists: The list of the artist name to fetch | |
Return: | |
The list of instanciated Artists | |
""" | |
result: List[Artist] = [] | |
async with Client( | |
transport=cls.TRANSPORT, fetch_schema_from_transport=True | |
) as session: | |
async def search(artist_name: str) -> None: | |
start: float = time.time() | |
res: Dict[str, Any] = await session.execute( | |
cls.QUERY, variable_values={'name': artist_name} | |
) | |
res['artist']['qwant_url'] = res['artist'].pop('qwantUrl') | |
artist: Artist = Artist(**res['artist']) | |
end: float = time.time() | |
print(f'Lasted {end - start:.2f} second(s) for {artist}') | |
result.append(artist) | |
coros = [search(artist) for artist in artists] | |
await asyncio.gather(*coros) | |
return result | |
async def main() -> None: | |
'''Main function''' | |
artists: List[str] | |
if not (artists := sys.argv[1:]): | |
artists = ['Flight Facilities', 'Roosevelt', 'Satin Jackets', 'Bonobo'] | |
await QwantMusicClient.fetch_artists(artists) | |
if __name__ == '__main__': | |
asyncio.run(main()) |
Author
SebDeclercq
commented
Sep 1, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment