Outils pour utilisateurs

Outils du site


issue75:python

Ceci est une ancienne révision du document !


This time, we are going to rework our database program from the previous few articles (parts 41, 42 and 43). Then, over the next few articles, we will use QT to create the user interface. First, let's look at how the existing application works. Here's a gross overview: • Create a connection to the database – which creates the database if needed. • Create a cursor to the database. • Create the table if it doesn't exist. • Assign the video folder(s) to a variable. • Walk through the folder(s) looking for video files. • Get the filename, seriesname, season number, episode number. • Check to see if the episode exists in the database. • If it is not there, add it to the database with a “-1” as the TvRage ID. • Then walk through the database getting show id and status if needed, and update database.

Cette fois, nous allons retravailler notre programme de base de données à partir des quelques articles précédents (numéros 41, 42 et 43). Puis, au cours des prochains articles, nous allons utiliser QT pour créer l'interface utilisateur.

Tout d'abord, regardons comment fonctionne l'application existante. Voici un aperçu brut : • Créer une connexion à la base de données - qui crée la base de données si nécessaire. • Créer un curseur à la base de données. • Créer la table si elle n'existe pas. • Attribuer le(s) dossier(s) vidéo à une variable. • Recherche dans le(s) dossier(s) des fichiers vidéo. • Obtenir le nom du fichier de l'épisode, le nom de la série, le numéro de la saison, le numéro de l'épisode. • Vérifiez si l'épisode existe dans la base de données. • Si il n'est pas là, l'ajouter à la base de données avec un “-1” comme ID TvRage. • Parcourir ensuite la base de données, obtenir l'id de l'épisode et le statut, si nécessaire, et mettre à jour la base de données.

We will redesign the database to include another table and modify the existing data table. First, we will create our new table called Series. It will hold all the information about the tv series we have on our system. The new table will include the following fields: • Pkid • Series Name • TvRage Series ID • Number of seasons • Start Date • Ended Flag • Country of origin • Status of the series (ended, current, etc) • Classification (scripted, “reality”, etc) • Summary of the series plot • Genres • Runtime in minutes • Network • Day of the week it airs • Time of day it airs • Path to the series

Nous allons repenser la base de données pour inclure une autre table et modifier la table de données existante. Tout d'abord, nous allons créer notre nouvelle table appelée Séries. Elle contiendra toutes les informations sur les séries TV que nous avons sur notre système. La nouvelle table comprendra les champs suivants : • PKID. • Nom de la série. • TvRage série ID. • Nombre de saisons. • Date de début. • Drapeau de fin. • Pays d'origine. • Statut de la série (terminé, courant, etc). • Classification (script, la «réalité», etc). • Résumé de l'intrigue de la série. • Genres. • Durée en minutes. • Chaîne de diffusion. • Jour de diffusion dans la semaine. • Horaire de diffusion. • Chemin de la série.

We can use the existing MakeDataBase routine to create our new table. Before the existing code, add the code shown above right. The SQL statement (“sql = …”) should be all on one line, but is broken out here for ease of your understanding. We’ll leave the modification of the existing table for later. Now we have to modify our WalkThePath routine to save the series name and path into the series table. Replace the line that says sqlquery = 'SELECT count(pkid) as rowcount from TvShows where Filename = “%s”;' % fl with sqlquery = 'SELECT count(pkid) as rowcount from series where seriesName = “%s”;' % showname

Nous pouvons utiliser la routine MakeDataBase existant pour créer notre nouvelle table. Avant le code existant, ajoutez le code ci-dessus à droite.

L'instruction SQL (“sql = …”) doit être sur une seule ligne, mais est éclatée ici pour la facilité de votre compréhension. Nous laisserons la modification de la table existante pour plus tard.

Maintenant, nous devons modifier notre routine WalkThePath pour enregistrer le nom de la série et le chemin dans la table de Séries.

Remplacez la ligne qui dit

sqlquery = 'SELECT count(pkid) as rowcount from TvShows where Filename = “%s”;' % fl

par

sqlquery = 'SELECT count(pkid) as rowcount from series where seriesName = “%s”;' % showname

This (to refresh your memory) will check to see if we have already put the series into the table. Now find the two lines that say: sql = 'INSERT INTO TvShows (Series,RootPath,Filename,Season,Episode,tvrageid) VALUES (?,?,?,?,?,?)' cursor.execute(sql,(showname,root,fl,season,episode,-1)) and replace them with sql = 'INSERT INTO Series (SeriesName,Path,SeriesID) VALUES (?,?,?)' cursor.execute(sql,(showname,root,-1))

Cela (pour vous rafraîchir la mémoire) va vérifier si nous avons déjà mis les séries dans la table. Maintenant, trouver les deux lignes qui disent :

sql = 'INSERT INTO TvShows (Series,RootPath,Filename,Season,Episode,tvrageid) VALUES (?,?,?,?,?,?)'

  cursor.execute(sql,(showname,root,fl,season,episode,-1))

et les remplacer par

sql = 'INSERT INTO Series (SeriesName,Path,SeriesID) VALUES (?,?,?)'

  cursor.execute(sql,(showname,root,-1))

This will insert the series name (showname), path to the series, and a “-1” as the TvRage id. We use the “-1” as a flag to know that we need the series information from TvRage. Next we will rework the WalkTheDatabase routine to pull those series that we don’t have any information for (SeriesID = -1) and update that record. Change the query string from sqlstring = “SELECT DISTINCT series FROM TvShows WHERE tvrageid = -1”

to

sqlstring = “SELECT pkid,SeriesName FROM Series WHERE SeriesID = -1”

Ceci va insérer le nom de la série (showname), le chemin de la série, et un “-1” comme identifiant de TvRage. Nous utilisons le “-1” comme un drapeau pour savoir que nous avons besoin de l'information de série TvRage.

Ensuite, nous allons retravailler la routine WalkTheDatabase pour alimenter ces séries pour lesquelles nous n'avons pas d'informations pour (SeriesID = -1) et mettre à jour ce dossier.

Modifiez la chaîne de requête de

sqlstring = “SELECT DISTINCT series FROM TvShows WHERE tvrageid = -1”

en

sqlstring = “SELECT pkid,SeriesName FROM Series WHERE SeriesID = -1”

This will create a result-set that we can then use to query TvRage for each series. Now find/replace the following two lines

seriesname = x[0]

searchname = string.capwords(x[0],“ ”)

with

pkid = x[0]

seriesname = x[1]

searchname = string.capwords(x[1],“ ”)

We will use the pkID for the update statement. Next we have to modify the call to the UpdateDatabase routine to include the pkid. Change the line

  UpdateDatabase(seriesname,id)

to

  UpdateDatabase(seriesname,id,pkid)

and change the line

  GetShowStatus(seriesname,id)

to

  GetShowData(seriesname,id,pkid)

Which will be a new routine we will create in a moment.

Next, change the definition of the UpdateDatabase routine from

def UpdateDatabase(seriesname,id):

to

def UpdateDatabase(seriesname,id,pkid):

Next, we need to change the query string from

sqlstring = 'UPDATE tvshows SET tvrageid = ' + id + ' WHERE series = “' + seriesname + '”'

to

sqlstring = 'UPDATE Series SET SeriesID = ' + id + ' WHERE pkID = %d' % pkid

Now we need to create the GetShowData routine (top). We’ll grab the information from TvRage and insert it into the Series table.

Just as a memory refresher, we are creating an instance of the TvRage routines and creating a dictionary that holds the information on our series. We will then create variables to hold the data for updating the table (above).

Remember that Genres come in as subelements and contain one or many genre listings. Luckily when we coded the TvRage routines, we created a string that holds all the genres, no matter how many are returned, so we can just use the genre string:

  genres = dict['Genres']

runtime = dict['Runtime']

network = dict['Network']

airday = dict['Airday']

airtime = dict['Airtime']

Finally, we create the query string to do the update (bottom). Again, this should all be on one line, but I’ve broken it up here to make it easy to understand.

The {number} portion (just to remind you) is similar to the “%s” formatting option. This creates our query string replacing the {number} with the actual data we want. Since we’ve already defined all of these fields as text, we want to use the double quotes to enclose the data being added.

And lastly, we write to the database (below).

That is all for this time. Next time, we’ll continue as I laid out at the beginning of the article. Until next time, Enjoy.

issue75/python.1387260848.txt.gz · Dernière modification : 2013/12/17 07:14 de fcm_-_ekel