Python - simple crud usando pickle

   
Vista:

simple crud usando pickle

Publicado por Horacio (18 intervenciones) el 02/07/2016 00:01:59
Buenas les muestro el codigo que hice de un simple crud de banco con los campos id, descripcion. mi duda es como recorrer los objetos dentro del archivo con pickle por que lo que use fue cargar el contenido, procesar, eliminar el archivo y guardar.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import pickle, os
 
class Bank:
 
    def __init__(self, id, description):
        self.id = id
        self.description = description
 
    def __str__(self):
        return "Id: {0}\nDescription: {1}".format(self.id, self.description)
 
class Banks:
 
    def __init__(self):
        self.filename = 'banks.txt'
        self.load()
 
    def load(self):
        try:
            with open(self.filename, 'rb') as f:
                self.banks = pickle.load(f)
        except:
            self.banks = []
 
    def exists(self, code):
        if self.banks:
            for b in self.banks:
                if b.id == code:
                    return True
        return False
 
    def save_data(self):
        if os.path.isfile(self.filename):
            os.remove(self.filename)
        with open(self.filename, 'wb') as f:
            pickle.dump(self.banks, f)
 
    def search(self, code):
        for pos, b in enumerate(self.banks):
            if b.id == code:
                return pos, b
        return 0, None
 
 
    def add_bank(self, code):
        description = raw_input("Description: ")
        bank = Bank(code, description)
        self.banks.append(bank)
        self.save_data()
 
    def show_bank(self, code):
        if self.exists(code):
            pos, bank = self.search(code)
            print bank
        else:
            print "bank does not exist"
        raw_input("Press ENTER to continue")
 
    def update(self, code):
        if self.exists(code):
            pos, bank = self.search(code)
            print bank
            print "Write new data: "
            description = raw_input('Description:')
            self.banks[pos].description = description
            self.save_data()
            print "successfully updated"
        else:
            print "Bank does not exist"
        raw_input("Press ENTER to continue")
 
    def delete(self, code):
        if self.exists(code):
            pos, bank = self.search(code)
            print bank
            confirm = raw_input("Are you sure? (Y/N): ").upper()
            if confirm == 'Y':
                del self.banks[pos]
                self.save_data()
                print "successfully deleted"
        else:
            print "Bank does not exist"
        raw_input("Press ENTER to continue")
 
 
def menu():
    while True:
        prompt = "1) Create\n"
        prompt += "2) Read\n"
        prompt += "3) Update\n"
        prompt += "4) Delete\n"
        prompt += "5) Exit\n"
        prompt += "Choose: "
        choose = int(raw_input(prompt))
        banks = Banks()
        if choose == 1:
            code = int(raw_input("Id Bank: "))
            if not banks.exists(code):
                banks.add_bank(code)
                print "successfully recorded"
            else:
                print "bank already exists"
            raw_input("Press Enter to continue")
        elif choose == 2:
            code = int(raw_input("Id Bank: "))
            banks.show_bank(code)
        elif choose == 3:
            code = int(raw_input("Id Bank: "))
            banks.update(code)
        elif choose == 4:
            code = int(raw_input("Id Bank: "))
            banks.delete(code)
        elif choose == 5:
            break
menu()

Desde ya ,gracias
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder