17.12.2012 Views

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

372<br />

La bibliothèque standard<br />

TROISIÈME PARTIE<br />

Persistance<br />

Exercice 10 : rendre persistants tous les objets d’un programme<br />

Description<br />

L’objectif de cet exercice est de mettre en place un mécanisme qui rende persistantes,<br />

de manière transparente, toutes les instances de classes dérivées d’une même classe de<br />

base dans un programme.<br />

À chaque fois que le programme se termine, les objets sont sauvegardés sur le système<br />

de fichiers. Ils peuvent ensuite être rechargés grâce à un identifiant unique qui<br />

leur est attribué.<br />

Points abordés<br />

shelve, atexit<br />

Solution<br />

Programme persistant<br />

#!/usr/bin/python<br />

# -*- coding: utf8 -*import<br />

shelve<br />

import atexit<br />

data = None<br />

objects = []<br />

def _load_objects():<br />

print('Loading...')<br />

global data<br />

data = shelve.open('objects.bin')<br />

def _save_objects():<br />

print('Saving...')<br />

for ob in objects:<br />

data[ob._id] = ob.__dict__<br />

data.close()<br />

class Persistent(object):<br />

def __new__(cls, id_):<br />

ob = super(Persistent, cls).__new__(cls)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!