N.S.I. WorkSpace Compétence,T-Th-D3,Terminale Terminale – Compétence | API (Application Programming Interface) 1/4

Terminale – Compétence | API (Application Programming Interface) 1/4

Vous avez dit « wrapper Python » ?

De nombreuses API disposent d’un wrapper Python : c’est un module Python qui permet d’interroger la base de données d’un fournisseur de façon simplifiée, sans avoir à écrire les requêtes Web, ni à interpréter les réponses.

Ces dernières sont généralement écrites au format JSON, qui est un format d’échange de données, au même titre que le XML.

À partir de ces réponses, le wrapper Python génère des listes ou des dictionnaires, facilement manipulables.

Source

Utilisation du wrapper Python pour l’API de « Genius »

Contexte

Découvrir le site « Genius« . Identifier le service proposé.

Installation du wrapper

Télécharger le wrapper : lyricsgenius-3.0.1-py3-none-any.whl (source) – Après téléchargement, vérifier que le fichier se trouve bien dans le dossier « Téléchargement » de l’utilisateur en cours.

Ouvrir un éditeur/interpréteur Python (ex : Pyzo).

Dans la console, utiliser les commandes « cd » et « ls » (comme les commandes d’un shell) pour se déplacer dans l’arborescence du système de fichier et visualiser le contenu d’un répertoire afin d’atteindre le fichier du wrapper. [ Dans certains cas la commande cd Downloads suffit]

Dans la console taper et valider la commande :

pip install lyricsgenius-3.0.1-py3-none-any.whl

Des informations s’affichent dans la console sur la progression de l’installation. Ces informations varient variable selon la configuration de l’installation de Python.

Processing c:\users\user\downloads\lyricsgenius-3.0.1-py3-none-any.whl
...
... Vérification des dépendances... et installation si besoin...
...
Successfully installed lyricsgenius-3.0.1

Premiers pas avec le wrapper…

Obtenir un ‘jeton’ : pour cela il faut créer un compte à partir de cette adresse :
https://docs.genius.com/#/getting-started-h1 , suivre les consignes données.
Le jeton donné ci-après n’a qu’une valeur indicative. Il n’est plus actif.

Dans la console, entrer les instructions suivantes les unes après les autres :

import lyricsgenius
jeton = '9deeuHRzwNwxsG1Xa4diSQuGikKDVY3uj3OOGnvQ6XL67xPMW0S3eo0xpZQtjh'
genius = lyricsgenius.Genius(jeton)
artiste = 'Angèle'
artiste_datas = genius.search_artist(artiste, max_songs=3, sort='popularity')

Noter la réponse obtenue : vérifier sa validité en effectuant une recherche directement sur le site Genius.

Essayer avec un autre artiste.

Exploration des possibilités offertes par le wrapper

Identifier le paradigme de programmation du wrapper.

Se renseigner sur les fonctions « type() », « help() » et « dir() ».

A partir de ces fonctions, identifier et tester quelques unes des possibilités offertes par le wrapper, en particulier :

Afficher dans la console les paroles d'une chanson ;
>>> type(artiste_datas)
<class 'lyricsgenius.types.artist.Artist'>

'artiste_datas' est un objet (une instance) de la classe 'Artist'.

Ses attributs et méthodes sont :
>>> dir(artiste_datas)
['__abstractmethods__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_abc_impl', '_body', '_client', 'add_song', 'api_path', 'header_image_url', 'id', 'image_url', 'is_meme_verified', 'is_verified', 'name', 'num_songs', 'save_lyrics', 'song', 'songs', 'to_dict', 'to_json', 'to_text', 'url']

>>> type(artiste_datas.songs)
<class 'list'>
>>> artiste_datas.songs
[Song(id, artist, ...), Song(id, artist, ...), Song(id, artist, ...)]

L'attribut 'songs' est de type 'list'. Il s'agit d'une liste d'objets (d'instances) de la classe 'Song'.

>>> dir(artiste_datas.songs[0])
['__abstractmethods__', '__class__', '__cmp__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_abc_impl', '_body', '_client', 'annotation_count', 'api_path', 'artist', 'full_title', 'header_image_thumbnail_url', 'header_image_url', 'id', 'lyrics', 'lyrics_owner_id', 'lyrics_state', 'path', 'primary_artist', 'pyongs_count', 'save_lyrics', 'song_art_image_thumbnail_url', 'song_art_image_url', 'stats', 'title', 'title_with_featured', 'to_dict', 'to_json', 'to_text', 'url']

>>> type(artiste_datas.songs[0].lyrics)
<class 'str'>

L'attribut 'lyrics' est une chaîne de caractères. Il contient les paroles de la chanson.

print(artiste_datas.songs[0].lyrics)
Sauvegarder les paroles d'une chanson sous la forme d'un fichier au format 'txt' ;
La démarche est analogue à la précédente.
On s'intéresse à la méthode 'save_lyrics'.

>>> type(artiste_datas.songs[0].save_lyrics)
<class 'method'>

>>> help(artiste_datas.songs[0].save_lyrics)
Help on method save_lyrics in module lyricsgenius.types.song:

save_lyrics(filename=None, extension='json', overwrite=False, ensure_ascii=True, sanitize=True, verbose=True) method of lyricsgenius.types.song.Song instance
    Save Song(s) lyrics and metadata to a JSON or TXT file.
    
    If the extension is 'json' (the default), the lyrics will be saved
    alongside the song's information. Take a look at the example below.
    
    Args:
        filename (:obj:`str`, optional): Output filename, a string.
            If not specified, the result is returned as a string.
        extension (:obj:`str`, optional): Format of the file (`json` or `txt`).
        overwrite (:obj:`bool`, optional): Overwrites preexisting file if `True`.
            Otherwise prompts user for input.
        ensure_ascii (:obj:`bool`, optional): If ensure_ascii is true
            (the default), the output is guaranteed to have all incoming
            non-ASCII characters escaped.
        sanitize (:obj:`bool`, optional): Sanitizes the filename if `True`.
        verbose (:obj:`bool`, optional): prints operation result.
    
    Warning:
        If you set :obj:`sanitize` to `False`, the file name may contain
        invalid characters, and thefore cause the saving to fail.

artiste_datas.songs[0].save_lyrics(filename=artiste_datas.songs[0].title, extension="txt")

print(artiste_datas.songs[0].lyrics)
Lire l'URL d'une photographie de l'artiste ;
Là encore on suit la même démarche :

>>> dir(artiste_datas)
['__abstractmethods__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_abc_impl', '_body', '_client', 'add_song', 'api_path', 'header_image_url', 'id', 'image_url', 'is_meme_verified', 'is_verified', 'name', 'num_songs', 'save_lyrics', 'song', 'songs', 'to_dict', 'to_json', 'to_text', 'url']

>>> type(artiste_datas.image_url)
<class 'str'>

print(artiste_datas.image_url)
Lire l'URL de la page du site Genius sur laquelle figure une présentation de l'artiste.
Là encore on suit la même démarche :

>>> dir(artiste_datas)
['__abstractmethods__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_abc_impl', '_body', '_client', 'add_song', 'api_path', 'header_image_url', 'id', 'image_url', 'is_meme_verified', 'is_verified', 'name', 'num_songs', 'save_lyrics', 'song', 'songs', 'to_dict', 'to_json', 'to_text', 'url']

>>> type(artiste_datas.url)
<class 'str'>

print(artiste_datas.url)

Cliquez sur « + » pour obtenir une solution

Pour aller plus loin… avec ‘webbrowser’

Vous avez dit 'webbrowser' ? De quoi s'agit-il ?

>>> type(webbrowser)
<class 'module'>

>>> dir(webbrowser)
['BackgroundBrowser', 'BaseBrowser', 'Chrome', 'Chromium', 'Elinks', 'Error', 'Galeon', 'GenericBrowser', 'Grail', 'Konqueror', 'Mozilla', 'Netscape', 'Opera', 'UnixBrowser', 'WindowsDefault', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_browsers', '_lock', '_os_preferred_browser', '_synthesize', '_tryorder', 'get', 'main', 'open', 'open_new', 'open_new_tab', 'os', 'register', 'register_X_browsers', 'register_standard_browsers', 'shlex', 'shutil', 'subprocess', 'sys', 'threading']

>>> help(webbrowser)
Help on module webbrowser:

NAME
    webbrowser - Interfaces for launching and remotely controlling Web browsers.

MODULE REFERENCE
    https://docs.python.org/3.9/library/webbrowser
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.
.../...
FUNCTIONS
    get(using=None)
        Return a browser launcher instance appropriate for the environment.
    
    open(url, new=0, autoraise=True)
        Display url using the default browser.
        
        If possible, open url in a location determined by new.
        - 0: the same browser window (the default).
        - 1: a new browser window.
        - 2: a new browser page ("tab").
        If possible, autoraise raises the window (the default) or not.
    
    open_new(url)
        Open url in a new window of the default browser.
        
        If not possible, then open url in the only browser window.
    
    open_new_tab(url)
        Open url in a new page ("tab") of the default browser.
        
        If not possible, then the behavior becomes equivalent to open_new().
    
    register(name, klass, instance=None, *, preferred=False)
        Register a browser connector.
.../...

Afficher une photographie d'un artiste dans un navigateur à partir de Python
>>> type(webbrowser.open_new_tab)
<class 'function'>

>>> help(webbrowser.open_new_tab)
Help on function open_new_tab in module webbrowser:

open_new_tab(url)
    Open url in a new page ("tab") of the default browser.
    
    If not possible, then the behavior becomes equivalent to open_new().

webbrowser.open_new_tab(artiste_datas.image_url)

Afficher la page de présentation d'un artiste sur le site Genius dans un navigateur à pertir de Python
>>> type(webbrowser.open_new_tab)
<class 'function'>

>>> help(webbrowser.open_new_tab)
Help on function open_new_tab in module webbrowser:

open_new_tab(url)
    Open url in a new page ("tab") of the default browser.
    
    If not possible, then the behavior becomes equivalent to open_new().

webbrowser.open_new_tab(artiste_datas.url)

Cliquez sur « + » pour obtenir une solution