Outils pour utilisateurs

Outils du site


issue69:programmer_en_python

Table des matières

1

Last time, we had a gross discussion about the TVRAGE web API. Now we will start to look at writing code to work with it. The goal of this part is to begin the process of creating code that will be a reusable module that can be imported into any python program and will provide access to the API easily. While the TVRAGE API gives us a number of things we can do, and the registered version even more, we will concentrate on only three calls: 1 - Search for show by show name, and get the ShowID 2 - Get show information based on ShowID 3 - Get episode specific information based on ShowID

La dernière fois, nous avons eu une longue discussion à propos de l'API web TVRAGE. Cette fois-ci, nous allons commencer à écrire du code et à nous en servir.

Le but de cette partie est de commencer le processus de création de code qui sera un module réutilisable pouvant être importé dans un autre programme python et qui donnera accès à l'API facilement.

Bien que l'API TVRAGE nous fournisse un certain nombre de possibilités, a fortiori pour la version enregistrée, nous allons nous concentrer sur seulement trois appels : 1. Rechercher une émission par son nom et obtenir le ShowID. 2. Obtenir de l'information sur l'émission à partir du ShowID. 3. Obtenir des informations spécifiques à un épisode à partir du ShowID.

2

Last time, I showed you the “unregistered” and accessible-by-anyone API calls. This time we will use the registered calls – based on a registration key I have. I’m going to share this key with you (TVRAGE knows that I’m going to do this). However, I ask that, if you are going to use the API, that you please register and get your own key, and that you don’t abuse the site. Please also consider donating to them to support their continuing efforts. We will create three main routines to make the calls and return the information, three routines that will be used to display the returned information (assuming that we are running in the “stand alone” mode), and a main routine to do the work – again assuming that we are running in the “stand alone” mode.

La dernière fois, je vous ai montré les appels de l'API « non enregistrée » qui sont accessibles par tout le monde. Cette fois, nous allons utiliser les appels enregistrés - basés sur une clé d'enregistrement que j'ai. Je vais partager avec vous cette clé (TVRAGE sait que je vais le faire). Cependant, je vous demande, s'il vous plaît, si vous envisagez d'utiliser l'API, de vous inscrire et d'obtenir votre propre clé, pour ne pas abuser du site. Je vous saurais gré de réfléchir également à leur faire un don pour soutenir leurs efforts constants.

Nous allons créer trois programmes principaux pour faire les appels et retourner l'information, trois routines qui seront utilisées pour afficher les informations retournées (en supposant que nous sommes en mode « indépendant »), et un sous-programme principal pour faire le travail - en supposant, là encore, que nous sommes en mode « indépendant ».

3

Here is the list of routines we will be creating (although not all of them this time. I want to leave room for others in this issue.) def FindIdByName(self, showname, debug = 0) def GetShowInfo(self, showid, debug = 0) def GetEpisodeList(self, showid, debug = 0) def DisplaySearchResult(self, ShowListDict) def DisplayShowInfo(self, dict) def DisplayEpisodeList(self, SeriesName, SeasonCount, EpisodeList) def main()

Voici la liste des routines que nous allons créer (enfin pas toutes pour cette fois-ci. Je veux laisser la place à d'autres choses dans ce numéro).

def TrouverIdParNom(self, nomEmission, debug = 0)

def RecupererInformationEmission(self, showid, debug = 0)

def RecupererListeEpisodes(self, showid, debug = 0)

def AfficheResultatsEmission(self, ListeEmissionsDict)

def AfficheInformationEmission(self, dict)

def AfficheListeEpisodes(self, NomsEmission, NumeroSaison, ListeEpisodes)

def main()

4

The routine FindIdByName takes a string (showname), makes the API call, parses the XML response, and returns a list of shows that match with the information in a dictionary, so this will be a list of dictionaries. GetShowInfo takes the showid from the above routine and returns a dictionary of information about the series. GetEpisodeList also uses the showid from the above routine and returns a list of dictionaries containing information for each episode. We will use a series of strings to hold the key and the base URL, and then append to those what we need. For example consider the following code (we’ll expand these later). self.ApiKey = “Itnl8IyY1hsR9n0IP6zI” self.FindSeriesString = “http://services.tvrage.com/myfeeds/search.php?key=

La routine TrouverIdParNom prend une chaîne (nomEmission), effectue l'appel API, analyse la réponse XML et retourne une liste des émissions qui correspondent aux informations contenues dans un dictionnaire ; ainsi, ce sera une liste de dictionnaires. RecupererInformationEmission récupère le showid de la routine précédente et retourne un dictionnaire d'informations sur l'émission. RecupererListeEpisodes utilise également le showid de la routine ci-dessus et retourne une liste de dictionnaires contenant des informations pour chaque épisode.

Nous utiliserons une série de chaînes pour contenir la clé et l'URL de base, puis leur ajouter ce dont nous avons besoin. Par exemple, considérons le code suivant (nous le compléterons plus tard).

self.CleApi = “Itnl8IyY1hsR9n0IP6zI”

self.ChaineRechercheSerie = “http://services.tvrage.com/myfeeds/search.php?key=

5

The call we need to send (to get back a list of series information with the series id) would be: http://services.tvrage.com/myfeeds/search.php?key=Itnl8IyY1hsR9n0IP6zI&show={ShowName} We combine the string like this… strng = self.FindSeriesString + self.ApiKey + ”&show=” + showname For the purposes of testing, I will be using a show named “Continuum” which, if you’ve never seen it, is a wonderful science fiction show on the Showcase network out of Canada. I’m using this show for a few reasons. First, there are only (as of this writing) two shows that match the search string “Continuum”, so that makes your debug easy, and secondly, there’s currently only one season of 10 episodes for you to deal with.

L'appel que nous devons envoyer (pour récupérer une liste d'informations sur la série avec l'id de la série) serait :

http://services.tvrage.com/myfeeds/search.php?key=Itnl8IyY1hsR9n0IP6zI&show={NomEmission}

Nous combinons la chaîne comme ceci :

chaine = self.ChaineRechercheSerie + self.CleAPI + “&show=” + nomEmission

Pour les besoins des tests, je vais utiliser une série intitulée « Continuum » qui, si vous ne l'avez jamais vue, est une série géniale de science-fiction sur la chaîne canadienne Showcase. J'utilise cette série pour plusieurs raisons. Tout d'abord, il n'y a (lorsque j'écris ces lignes) que deux séries qui correspondent à la recherche « Continuum », ce qui rend votre débogage facile, et, d'autre part, il n'y a actuellement qu'une seule saison de 10 épisodes à gérer.

6

You should have an idea what you will be looking for in your parsing routines, so I’ve placed the full URL calls below for you to test, before you get started with your coding. Search using a show name… http://services.tvrage.com/myfeeds/search.php?key=Itnl8IyY1hsR9n0IP6zI&show=continuum Retrieve Series information using the ShowID (sid) http://services.tvrage.com/myfeeds/showinfo.php?key=Itnl8IyY1hsR9n0IP6zI&sid=30789 Retrieve Episode list and information using the ShowID (sid) http://services.tvrage.com/myfeeds/episode_list.php?key=Itnl8IyY1hsR9n0IP6zI&sid=30789

Vous devriez avoir une idée de ce que vous rechercherez dans vos routines d'analyse ; j'ai donc placé ci-dessous les URL complètes pour que vous les testiez avant de vous lancer dans votre code.

Rechercher en utilisant un nom d'émission : http://services.tvrage.com/myfeeds/search.php?key=Itnl8IyY1hsR9n0IP6zI&show=continuum

Récupérer des informations sur la série avec le ShowID (sid) : http://services.tvrage.com/myfeeds/showinfo.php?key=Itnl8IyY1hsR9n0IP6zI&sid=30789

Récupérer la liste des épisodes et leurs informations avec le ShowID (sid) : http://services.tvrage.com/myfeeds/episode_list.php?key=Itnl8IyY1hsR9n0IP6zI&sid=30789

7

Now that we have all that out of the way, let’s get started with our code. You’ll create a file with the name of “tvrage.py”. We’ll be using this for the next issue or two. We’ll start with our imports shown above right. You can see that we will be using ElementTree to do the XML parsing, and urllib for the internet communication. The sys library is used for sys.exit.

Maintenant que nous avons vu tout cela, nous allons commencer à écrire le code.

Vous allez créer un fichier nommé « tvrage.py ». Nous allons nous en servir pendant un ou deux articles.

Nous allons commencer avec nos importations indiquées en haut à droite.

Vous pouvez voir que nous allons utiliser ElementTree pour faire l'analyse XML et urllib pour la communication internet. La bibliothèque sys est utilisée pour sys.exit.

8

We’ll set up the main loop now so we can test things as we go (bottom right). Remember this is the last thing in our source file. As I said earlier, the first four lines are our partial strings to build the URL for the function that we want to use. (GetEpisodeListString should all be on one line.) The last four lines are the initialization of the lists we will be using later. First (middle right), we set up the string that will be used as the URL. Next, we set up the socket with an 8 second default timeout. Then we call urllib.urlopen with our generated URL and (hopefully) receive our xml file in the usock object. We call ElementTree setup so we can parse the xml information. (If you are lost here, please re-read my articles on XML (parts 10, 11 and 12 appearing in FCM #36, 37 and 38)). Next, we close the socket, and initialize the counter for the number of matches found, and reset the list ‘showlist’ to an empty list.

Nous allons mettre en place la boucle principale maintenant afin de pouvoir tester les choses au fur et à mesure (en bas à droite). Rappelez-vous que ceci doit être tout à la fin de notre fichier source.

Comme je l'ai dit plus tôt, les quatre premières lignes sont nos chaînes partielles pour construire l'URL de la fonction que nous voulons utiliser. (ChaineListeEpisodes doit être sur une seule ligne.) Les quatre dernières lignes sont l'initialisation des listes que nous utiliserons plus tard.

Tout d'abord (au milieu à droite), nous réglons la chaîne qui sera utilisée comme URL. Puis, nous réglons le socket avec un délai d'attente de 8 secondes par défaut. Ensuite, nous appelons urllib.urlopen avec l'URL générée et (espérons-le) recevons notre fichier xml dans l'objet usock. Nous utilisons ElementTree pour analyser les informations xml. (Si vous êtes perdus, relisez s'il vous plaît mes articles sur XML (les parties 10, 11 et 12 figurant dans les FCM n° 36, 37 et 38)). Enfin, on ferme le socket et on initialise le compteur pour le nombre de résultats trouvés, puis on réinitialise la liste listeEmissions à une liste vide.

9

Now we will step through the xml information using the tag ‘show’ as the parent for what we want. Remember the returned information looks something like that shown top right. We will be going through each group of information for the parent ‘show’ and parsing out the information. In practice, all we really need is the show name (<name>) and the showid (<showid>) shown bottom left, but we’ll handle all of the results. I’ll discuss the first one and you’ll understand the rest. As we go through the information, we look for tags (bottom right) that match what we want. If we find any, we assign each to a temporary variable and then put that into the dictionary as a value with a key that matches what we are putting in. In the case of the above, we are looking for the tag ‘showid’ in the XML data. When we find it, we assign that as a value to the dictionary key ‘ID’.

Maintenant, nous allons passer en revue les informations XML en utilisant la balise « show » comme parent de ce que nous voulons. Rappelez-vous que les informations retournées ressemblent à ce qui est en haut à droite.

Nous allons parcourir chaque groupe d'informations en cherchant « show » comme parent et analyser l'information. En pratique, nous n'avons besoin que du nom de l'émission (<name>) et du showid (<showid>) montré en bas à gauche, mais nous allons gérer tous les résultats.

Je vais expliquer le premier et vous comprendrez le reste. Lorsque nous parcourons les informations, nous recherchons les balises (en bas à droite) qui correspondent à ce que nous voulons. Si nous en trouvons une, nous l'affectons à une variable temporaire, puis mettons cela dans le dictionnaire comme valeur avec une clé qui correspond à ce que nous insérons. Dans le cas qui précède, nous recherchons la balise « showid » dans les données XML. Lorsque nous la trouvons, nous l'assignons en tant que valeur de la clé « ID ».

10

The next portion (next page, top right) deals with the genre(s) of the show. As you can see from the above XML snippet, this show has four different genres that it fits into. Action, Crime, Drama, and Sci-Fi. We need to handle each. Finally, we increment the foundcounter variable, and append this dictionary into the list ‘showlist’. Then we start the entire thing over until there is no more XML data. Once everything is done, we return the list of dictionaries (bottom right).

La partie suivante (page suivante, en haut à droite) porte sur le(s) genre(s) de la série. Comme vous pouvez le voir dans l'extrait XML ci-dessus, cette série se trouve dans quatre genres différents. Action, crime, drame et Sci-Fi. Nous devons les traiter tous.

Enfin, on incrémente la variable compteurTrouves et on ajoute ce dictionnaire dans la liste « listeEmissions ». Ensuite, nous recommençons le processus jusqu'à ce qu'il n'y ait plus aucune donnée XML. Une fois que tout est terminé, on retourne la liste des dictionnaires (en bas à droite).

11

Most of the code is pretty self explanatory. We’ll concentrate on the for loop we use to print out the information. We loop through each item in the list of dictionaries and print a counter variable, the show name (c[‘Name’]), and the id. The result looks something like this… Enter Series Name → continuum 2 Found ———————— 1 - Continuum - 30789 2 - Continuum (Web series) - 32083 Enter Selection or 0 to exit →

La plupart du code est assez explicite. Nous allons nous concentrer sur la boucle « for » que nous utilisons pour afficher les informations. Nous bouclons sur chaque élément de la liste de dictionnaires et affichons une variable compteur, le nom de l'émission (c['Nom']) et l'id. Le résultat ressemble à ceci :

Entrer le nom de la série → continuum 2 resultat(s)


1 - Continuum - 30789 2 - Continuum (Web series) - 32083 Choisir un nombre ou 0 pour quitter →

12

Please remember that the list of items is zero based, so when the user enters ‘1’, they are really asking for dictionary number 0. We do this, because “regular” people think that counting should start with ‘1’ not 0. And we can then use 0 to escape the routine and not make them use ‘Q’ or ‘q’ or ‘-1’. Now, the “main” routine that pulls it all together for us. For today, we’ll just start the routine (middle right) and continue it next time. Next time, we’ll add the other routines. For now, the code can be found at http://pastebin.com/6iw5NQrW See you soon.

Souvenez-vous que la liste des articles commence à zéro, donc lorsque l'utilisateur entre 1, en fait il demande le dictionnaire numéro 0. Nous faisons comme ça parce que les gens « normaux » pensent que le décompte doit commencer par 1, pas par 0. Et nous pouvons ainsi utiliser 0 pour quitter la routine et ne pas leur faire utiliser Q ou q ou -1.

Maintenant, la routine « main » va tout rassembler pour nous.

Pour aujourd'hui, nous allons juste commencer la routine (au milieu à droite) et nous la continuerons la prochaine fois.

La prochaine fois, nous ajouterons les autres routines. Pour l'instant, le code peut être trouvé sur http://pastebin.com/8F3Bd1Xd

À bientôt.

issue69/programmer_en_python.txt · Dernière modification : 2013/04/03 19:52 de fredphil91