From 6d6af879045f6c8314a1cc6909b74ede71215e65 Mon Sep 17 00:00:00 2001 From: Vincent Le Gallic Date: Tue, 8 Apr 2014 01:44:53 +0200 Subject: [PATCH] =?utf8?q?Possibilit=C3=A9=20de=20dump=20et=20de=20restore?= =?utf8?q?=20dans=20un=20format=20lisible?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Comme ça, on peut faire le ménage très facilement --- config.py | 8 +++++++- quotes.py | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/config.py b/config.py index 4d74def..917ec0d 100644 --- a/config.py +++ b/config.py @@ -110,10 +110,16 @@ helpmsg_overops = u" SAY DO STAY NOSTAY OPS OVEROPS KICK DIE CRASH" blacklisted_masks = [("Flo!*@*", [])] #: Regexp utilisée pour parser des quotes -quote_regexp = ur"""\s*("|«|')\s*(?P.+?)\s*("|»|') ?~ ?(?P.+?)\s*$""" +quote_regexp = ur"""\s*(?:"|«|')\s*(?P.+?)\s*(?:"|»|') ?~ ?(?P.+?)\s*(?:$|\n)""" + +#: Regexp utlisée pour parser une quote avec timestamp +quote_regexp_with_timestamp = ur"(?P.{19}) " + quote_regexp #: Template pour afficher une quote quote_template = u"« %(content)s » ~ %(author)s" #: Fichier pour stocker les quotes quote_file = u"quotes.json" + +#: Fichier pour exporter les quotes +quote_dump_file = u"quotes.txt" diff --git a/quotes.py b/quotes.py index 73f711c..35f4860 100644 --- a/quotes.py +++ b/quotes.py @@ -97,3 +97,26 @@ class QuoteDB(object): def randomfrom(self, author): """ Sort une quote aléatoire de ``author`` """ return random.choice([q for q in self.quotelist if q.author == author]) + +def dump(quotedb, dump_file=None): + """Pour exporter les quotes dans un format readable vers un fichier.""" + if dump_file is None: + dump_file = config.quote_dump_file + t = "\n".join(["%s %s" % (q.timestamp.strftime("%F_%T"), q) for q in quotedb.quotelist]) + "\n" + with open(dump_file, "w") as f: + f.write(t) + +def restore(dump_file=None): + """Crée un DB de quotes en parsant le contenu d'un fichier de dump.""" + if dump_file is None: + dump_file = config.quote_dump_file + with open(dump_file) as f: + t = f.read() + t = t.decode("utf-8") # Oui, ça peut fail, mais on ne doit alors pas continuer + regex = re.compile(config.quote_regexp_with_timestamp) + l = [m.groupdict() for m in regex.finditer(t)] + # On instancie les quotes grâce aux dicos qui ont déjà la bonne tronche + l = [Quote(**q) for q in l] + newquotedb = QuoteDB() + newquotedb.quotelist = l + return newquotedb -- 2.39.2