Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Last active January 12, 2019 19:38
Show Gist options
  • Save jsbueno/20414880664c86a330f761c8fbd36d00 to your computer and use it in GitHub Desktop.
Save jsbueno/20414880664c86a330f761c8fbd36d00 to your computer and use it in GitHub Desktop.
class Cliente:
tabela = "clientes"
def __init__(self, id=None, nome="", telefone="", email=""):
self.id = id
self.nome = nome
self.telefone = telefone
self.email = email
def save(self, con, tabela=""):
if not self.id:
con.execute("""INSERT INTO {tabela}
('nome', 'telefone', 'email')
VALUES(?, ?, ?) """.format(tabela=(tabela if tabela else self.tabela)),
(self.nome, self.telefone, self.email))
else:
con.execute("""
UPDATE {tabela} SET
nome=?, telefone=?, email=?
WHERE id=?
""".format(tabela=(tabela if tabela else self.tabela)),
(self.nome, self.telefone, self.email, self.id))
con.commit()
@classmethod
def load(cls, id, con, tabela=""):
cursor = con.execute("""SELECT id, nome, telefone, email FROM {tabela} WHERE id=?""".format(tabela=(tabela if tabela else cls.tabela)), (id,))
dados = cursor.fetchall()[0]
cliente = Cliente(*dados)
return cliente
@classmethod
def last_id(cls, con, tabela=""):
response = con.execute("""SELECT MAX(id) FROM {tabela}""".format(tabela=(tabela if tabela else cls.tabela))).fetchall()[0][0]
return response if response is not None else 0
@classmethod
def cria_tabela(cls, con, tabela=""):
con.execute("""CREATE TABLE IF NOT EXISTS
{tabela}
(id integer primary key autoincrement,
nome char,
telefone char,
email char
)
""".format(tabela=(tabela if tabela else cls.tabela)))
@classmethod
def campos(cls):
return [
{'name': 'nome', 'label': 'Nome', 'type': str},
{'name': 'telefone', 'label': 'Telefone', 'type': str},
{'name': 'email', 'label': 'E-mail', 'type': str},
]
def __repr__(self):
return "<Cliente '{}', {}, {}>".format(self.nome, self.telefone, self.email)
config = [
{'fieldname': 'Cliente', 'type': str},
{'fieldname': 'Telefone', 'type': str},
{'fieldname': 'E-mail', 'type': str},
{'fieldname': 'nome do pet', 'type': str},
{'fieldname': 'telefone do pet'}
]
import csv
import os
import sqlite3
import tkinter
import modelos
from modelos import Cliente
FILENAME = "exemplo.db"
# global name, age, address, phone, email, index
#from registro_config import config
variaveis = {}
def init():
global con
con = sqlite3.connect(FILENAME)
Cliente.cria_tabela(con)
def save():
update()
cliente.save(con)
def load():
global cliente
try:
cliente = Cliente.load(index, con)
except IndexError:
cliente = Cliente()
def create_field(window, label):
f1 = tkinter.Frame(window)
f1.pack()
variable = tkinter.Variable(window)
l1 = tkinter.Label(f1, text=label)
e1 = tkinter.Entry(f1, textvariable=variable)
l1.pack(side="left")
e1.pack(side="left")
return variable
def next():
global index
index += 1
if index >= Cliente.last_id(con):
index = 1
load()
show()
def previous():
global index
index -= 1
if index < 1:
index = Cliente.last_id(con)
load()
show()
def new():
global index, cliente
index = Cliente.last_id(con) + 1
cliente = Cliente()
show()
def add_button(frame, t, command, side="left"):
button = tkinter.Button(frame, text=t, command=command)
button.pack(side="left")
def warn_user(message):
status_line["text"] = message
status_line["fg"] = "red"
def show():
global index, cliente
print(cliente)
for field in Cliente.campos():
var = variaveis[field["name"]]
name = field["name"]
var.set(getattr(cliente, name))
status_line["text"] = str(index)
status_line["fg"] = "black"
def update():
for field in Cliente.campos():
var = variaveis[field["name"]]
name = field["name"]
setattr(cliente, name, var.get())
def main():
global index, status_line
window = tkinter.Tk()
for field in Cliente.campos():
variaveis[field['name']] = create_field(window, field['label'])
f3 = tkinter.Frame(window)
f3.pack()
add_button(f3, "<<", previous)
add_button(f3, "Salvar", save)
add_button(f3, "Novo", new)
add_button(f3, ">>", next, side="right")
status_line = tkinter.Label(window)
status_line.pack()
index = 1
load()
show()
tkinter.mainloop()
if __name__ == "__main__":
init()
main()
import datetime
import sqlite3
import threading
from flask import Flask, request, redirect
# from flask_sqlalchemy import SQLAlchemy
from jinja2 import Template
from modelos import Cliente
app = Flask(__name__)
connections = {}
def get_con():
thread = threading.current_thread()
if thread not in connections:
connections[thread] = sqlite3.connect("../exemplo.db")
return connections[thread]
def init():
Cliente.cria_tabela(get_con())
# init()
@app.route("/")
def hello_world():
total_clientes = Cliente.last_id(get_con())
clientes = [Cliente.load(id, get_con()) for id in range(1, total_clientes + 1)]
template = Template("""
<h1>Clientes</h1>
<a href="novo">Inserir novo cliente</a><br>
<ul>
{% for cliente in clientes %}
<li>
<a href="editar/{{ cliente.id }}">
{{ cliente.nome }}
</a>, {{ cliente.telefone }}, {{ cliente.email }}
</li>
{% endfor %}
</ul>
""")
return template.render(clientes=clientes)
@app.route("/novo", methods=["GET", "POST"])
def novo():
if request.method == "GET":
template = Template("""
<h1> Novos dados para {{ nome }}</h1>
<form action="#" method="POST">
{% for campo in campos %}
{{ campo.label }}: <input type="entry" name="{{ campo.name }}"><br>
{% endfor %}
<input type="submit" value="Salvar">
</form>
""")
return template.render(campos=Cliente.campos(), nome="Cliente")
elif request.method == "POST":
form = request.form
cliente = Cliente(nome=form["nome"], telefone=form["telefone"], email=form["email"])
cliente.save(get_con())
return redirect("/")
@app.route("/editar/<int:id>", methods=["GET", "POST"])
def editar(id):
if request.method == "GET":
cliente = Cliente.load(id, get_con())
template = Template("""
<h1> Novos dados para {{ nome }}</h1>
<form action="#" method="POST">
<input type="hidden" name="cliente_id" value="{{ dados["id"] }}" >
{% for campo in campos %}
{{ campo.label }}: <input type="entry" name="{{ campo.name }}" value="{{ dados[campo.name] }}"><br>
{% endfor %}
<input type="submit" value="Salvar">
</form>
""")
return template.render(campos=Cliente.campos(), nome=cliente.nome, dados=cliente.__dict__)
elif request.method == "POST":
form = request.form
cliente = Cliente(nome=form["nome"], telefone=form["telefone"], email=form["email"])
cliente.id = form["cliente_id"]
cliente.save(get_con())
return redirect("/")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment