-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.py
83 lines (73 loc) · 2.84 KB
/
controller.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*
import psycopg2
__CONN_STRING__ = "postgresql://postgres:postgres@localhost:5432/trabalhobd2"
def get_connection():
return psycopg2.connect(__CONN_STRING__)
def get_logradouro(cep):
conn = get_connection()
cur = conn.cursor()
cur.execute("""select cep, nome, bairro, cidade, uf
from logradouro where cep = %d""" % cep)
rows = cur.fetchall()
logradouro = {}
for row in rows:
logradouro['cep'] = row[0]
logradouro['nome'] = row[1].decode('utf-8')
logradouro['bairro'] = row[2].decode('utf-8')
logradouro['cidade'] = row[3].decode('utf-8')
logradouro['uf'] = row[4]
return logradouro
def save(usuario):
try:
conn = get_connection()
cur = conn.cursor()
cur.execute("""insert into usuario(nome, cpf, sexo, telefone) values
(%(nome)s, %(cpf)s, %(sexo)s, %(telefone)s)
returning id""", usuario)
usuario_id = cur.fetchone()[0]
for endereco in usuario['enderecos']:
endereco['usuario_id'] = usuario_id
cur.execute("""insert into endereco_usuario
(usuario_id, cep, numero, complemento) values
(%(usuario_id)s, %(cep)s, %(numero)s,
%(complemento)s)""", endereco)
conn.commit()
return (True, '')
except Exception, e:
conn.rollback()
return (False, str(e))
def list_all():
conn = get_connection()
cur = conn.cursor()
cur.execute("select id, nome, cpf, sexo, telefone from usuario")
rows = cur.fetchall()
usuarios = []
for row in rows:
usuario = {}
usuario['id'] = row[0]
usuario['nome'] = row[1].decode('utf-8')
usuario['cpf'] = row[2]
usuario['sexo'] = row[3]
usuario['telefone'] = row[4]
usuario['enderecos'] = []
curEndereco = conn.cursor()
curEndereco.execute("""select e.id, l.nome as logradouro, e.numero,
e.complemento, l.cep, l.bairro, l.cidade, l.uf
from endereco_usuario e
inner join logradouro l on (l.cep = e.cep)
where e.usuario_id = %d""" % usuario['id'])
enderecos = curEndereco.fetchall()
for e in enderecos:
endereco = {}
endereco['id'] = e[0]
endereco['logradouro'] = e[1].decode('utf-8')
endereco['numero'] = e[2]
endereco['complemento'] = e[3].decode('utf-8')
endereco['cep'] = e[4]
endereco['bairro'] = e[5].decode('utf-8')
endereco['cidade'] = e[6].decode('utf-8')
endereco['uf'] = e[7]
usuario['enderecos'].append(endereco)
usuarios.append(usuario)
return usuarios