cineclub-script/scripts/cineclubBlogSQ.py

271 lines
7.9 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 1 22:49:56 2018
@author: alice
TODO :
* simplifier l'input autant que possible
* remplir
* débug
* documenter
* publication FB
"""
import sqlite3
from config import db_path
from datetime import date
import locale
locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')
# def adapt_datetime(ts):
# return time.mktime(ts.timetuple())
# sqlite3.register_adapter(datetime.date, adapt_datetime)
class filmSQ():
def __init__(self, dic):
"""ceci est une aide"""
if type(dic) == type(""):
self.idN = dic
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
c = conn.cursor()
try:
c.execute("""SELECT i FROM films WHERE idN = ?""", (dic,))
r = c.fetchone()
self.i = r[0]
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
elif type(dic) == type(1):
self.i = dic
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
c = conn.cursor()
try:
c.execute("""SELECT idN FROM films WHERE i = ?""", (dic,))
r = c.fetchone()
self.idN = r[0]
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
else:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
c = conn.cursor()
try:
c.execute(
'INSERT INTO films VALUES (:i, :idN, :date, :nom, :realisateur, :duree, :synopsis, :pays, :annee, :youtube, :couleur, :image, :formatCopie, :langST)',
dic)
acteursToSq = [{'idFilm': dic['i'], 'acteur': a} for a in dic['acteurs']]
c.executemany('INSERT INTO acteurs VALUES (NULL, :idFilm, :acteur)', acteursToSq)
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
# id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT [PRIMARY KEY]
self.__setattr__('idN', dic['idN'])
def __setattr__(self, attr_name, attr_value):
if attr_name == 'idN':
object.__setattr__(self, 'idN', attr_value)
else:
try:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
c = conn.cursor()
if attr_name == 'acteurs':
c.execute("""DELETE FROM acteurs WHERE iFilm =?""", (self.i,))
acteursToSq = [{'iFilm': self.i, 'acteur': a} for a in attr_value]
c.executemany('INSERT INTO acteurs VALUES (NULL, :iFilm, :acteur)', acteursToSq)
else:
c.execute('UPDATE films SET %s = ? WHERE idN = ?' % attr_name, (attr_value, self.idN))
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
def __getattr__(self, attr_name):
conn = sqlite3.connect(db_path, detect_types=sqlite3.PARSE_DECLTYPES)
conn.row_factory = sqlite3.Row
c = conn.cursor()
try:
if attr_name == 'acteurs':
c.execute("""SELECT name FROM acteurs WHERE iFilm=?""", (self.i,))
r = c.fetchall()
res = [a[0] for a in r]
else:
c.execute("""SELECT %s FROM films WHERE idN=:idN""" % attr_name, {"idN": self.idN})
r = c.fetchone()
res = r[0]
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
return res
def __str__(self):
try:
conn = sqlite3.connect(db_path)
# conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('SELECT idN, nom, date FROM films WHERE idN = ?', (self.idN))
r = c.fetchone()
s = r[0] + ' : ' + r[1] + ' le ' + r[2]
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
return s
def max_id():
try:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('SELECT MAX(i) FROM films')
r = c.fetchone()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
return r[0]
def list_all():
try:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('SELECT idN, nom, date, i FROM films ORDER BY i ASC')
r = c.fetchall()
for movie in r:
print(movie[3], ' - ', movie[0], ' : ', movie[1], ' le ', movie[2])
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
pass
def make_actors_list():
l = []
new = input(
"Entrez le nom des acteurs en appuyant sur Entrée entre chaque. Pour terminer, appuyer sur Entrée avec une ligne vide.\n")
if (new == -1):
return -1
while (new != ""):
l += [new]
new = input()
pass
return l
def input_date():
ok = False
d = input("date de la séance (format JJ/MM/AAAA ) ")
while not ok:
try:
d = d.split("/")
res = date(int(d[2]), int(d[1]), int(d[0]))
ok = True
except IndexError:
print("Veuillez entrer la date au format JJ/MM/AAA")
return res
def input_duration():
ok = False
while not ok:
try:
res = eval(input("durée du film (en minutes) "))
ok = True
except (NameError, SyntaxError):
print("le format n'est pas correct. Ne rentrez que des chiffres svp")
pass
pass
return res
def input_color():
ok = False
while not ok:
d = input("le film est-il en couleur (oui/non) ? ")
if d in ["True", "true", "oui", "Oui", "y", "o", "Y", "y", "O", "yes", "Yes"]:
res = True
ok = True
elif d in ["False", "false", "non", "Non", "n", "N", "no", "No"]:
res = False
ok = True
return res
def new_film():
"""Interface d'ajout d'un nouveau film"""
dic = {}
i = filmSQ.max_id()
ok = False
dic['i'] = i + 1
dic['idN'] = input("identifiant du film ? ")
dic['date'] = filmSQ.input_date()
dic['nom'] = input("titre ? ")
dic['realisateur'] = input("realisateur ? ")
dic['acteurs'] = filmSQ.make_actors_list()
dic['synopsis'] = input("Donnez ici un synopsis rapide du film ")
dic['pays'] = input("pays de diffusion du film ? ")
dic['annee'] = input("année de sortie du film (format AAAA) ? ")
dic['duree'] = filmSQ.input_duration();
dic['youtube'] = input("adresse youtube de la bande-annonce ? ")
dic['image'] = input("url d'une affiche du film ? ")
dic['couleur'] = filmSQ.input_color();
dic['formatCopie'] = input("format de la copie ? ")
dic['langST'] = input("langue et sous-titre : VF/VOSTFR ? ")
seance = filmSQ(dic)
return seance
def strListe(liste):
res = ""
for l in liste[:-1]:
res += l + ', '
if liste != []:
res += liste[-1]
return res