def save_to_firebase(self): validation = self.validate() if validation: print("validation success") email = self.lineEdit_Login.text() password = self.lineEdit_Senha.text() name = self.lineEdit_nome.text() cpf = self.lineEdit_CPF.text() #Remove dots and dashes from CPF from re import sub as re_sub cpf = re_sub('[.-]', '', cpf) user = User(email, name, cpf, LevelOfAccess.COMMON_USER) auth.create_user_with_email_and_password(email, password) db.child('users').push(user.to_dict()) msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.NoIcon) msg.setText("Sucesso") msg.setInformativeText("Cadastrado com sucesso!") msg.setWindowTitle("Sucesso") msg.exec_() global loggedUser if self.mainWindow: if loggedUser != None and loggedUser.level == LevelOfAccess.ADMIN: self.mainWindow.stackedWidget.setCurrentIndex(4) else: self.mainWindow.stackedWidget.setCurrentIndex(0) else: print("validation error")
def cancelar(id): if current_user.is_active() and current_user.session_over(): current_user.reset_token usuario = db.child('users').child(current_user.localId).get(current_user.idToken) usuario = dict(usuario.val()) despesa = db.child('despesas').child(id).get(current_user.idToken) despesa = dict(despesa.val()) pode_cancelar = (usuario['departamento'] == despesa['departamento'] or usuario['email'] == despesa['criado_por']) if pode_cancelar and despesa['status'] != '7': despesa['status'] = '7' try: despesa['modificado_por'] = current_user.email despesa['data_ult_alt'] = datetime.now().strftime('%d/%m/%Y') db.child('despesas').child(id).update(despesa, current_user.idToken) send_mail(despesa, current_user) except Exception as e: mensagem = 'Não foi possível atualizar essa despesa.' print(e) flash(mensagem) return redirect(url_for('despesas.listar'))
def save_to_firebase(self): validation = self.validate() if validation: name = self.lineEdit_Nome.text() cpf = self.lineEdit_CPF.text() level = 1 if self.radioButton_admin.isChecked() else 0 #Remove dots and dashes from CPF from re import sub as re_sub cpf = re_sub('[.-]', '', cpf) user_update = {'name': name, 'cpf': cpf, 'level': level} user = db.child('users').order_by_child("email").equal_to( self.editing_user.email).get().each() db.child('users').child(user[0].key()).update(user_update) msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.NoIcon) msg.setText("Sucesso") msg.setInformativeText("Alterações salvas com sucesso!") msg.setWindowTitle("Sucesso") msg.exec_() if self.mainWindow: if loggedUser != None and loggedUser.level == LevelOfAccess.ADMIN: self.mainWindow.stackedWidget.setCurrentIndex(4) else: self.mainWindow.stackedWidget.setCurrentIndex(0)
def criar(): if current_user.is_active() and current_user.session_over(): current_user.reset_token() if verify_dba(current_user): return redirect(url_for('despesas.listar')) form = UserForm() if form.validate_on_submit(): uid = form.uid.data usuario = { 'nome': form.nome.data, 'sobrenome': form.sobrenome.data, 'email': form.email.data, 'departamento': form.departamento.data, 'RD': form.representante.data, 'DBA': form.dba.data, 'Diretor': form.diretor.data } try: db.child('users').child(uid).update(usuario, current_user.idToken) return redirect(url_for('users.listar')) except Exception as e: mensagem = 'Não foi possível incluir este usuário.' print(e) flash(mensagem) return redirect(url_for('users.criar')) return render_template('users/criar.html', form=form)
def control(self): username = self.username.text() email = self.email.text() password = self.password.text() if username.strip() == '' or email.strip() == '' or password.strip( ) == '': QMessageBox.warning(self, 'Error', "Pleas fill all the fields") return elif len(password.strip()) < 6: QMessageBox.warning(self, 'Error', "Password must tbe at least 6 characters") return try: auth.create_user_with_email_and_password(email, password) except: QMessageBox.warning(self, 'Error', "You already have an account") print(sys.exc_info()) return auth.sign_in_with_email_and_password(email, password) uid = auth.current_user['localId'] user_data = { 'username': username, 'email': email, 'password': password, 'id': uid } db.child('users').child(uid).set(user_data) self.confirm.emit(username) self.close()
def delete(self): from firebase import admin_auth user = db.child('users').order_by_child('email').equal_to( self.editing_user.email).get().each() db.child('users').child(user[0].key()).remove() auth_user = admin_auth.get_user_by_email(self.editing_user.email) admin_auth.delete_user(auth_user.uid)
def deletar(id): if current_user.is_active() and current_user.session_over(): current_user.reset_token if verify_dba(current_user): return redirect(url_for('despesas.listar')) db.child('users').child(id).remove(current_user.idToken) print('deletedo o usuário' + id) return redirect(url_for('users.listar'))
def desaprovacao(id): if current_user.is_active() and current_user.session_over(): current_user.reset_token usuario = db.child('users').child(current_user.localId).get(current_user.idToken) usuario = dict(usuario.val()) despesa = db.child('despesas').child(id).get(current_user.idToken) despesa = dict(despesa.val()) fin = (usuario['departamento'] == 'financeiro') if usuario['RD']: if current_user.departamento == despesa['departamento']: resp_depto = True elif (current_user.departamento == 'administrativo' and despesa['departamento'] == 'estoque'): resp_depto = True else: resp_depto = False else: resp_depto = False if usuario['RD'] and fin: resp_fin = True else: resp_fin = False form = MotivoDesaprovForm() if form.validate_on_submit(): motivo = form.motivo.data if despesa['status'] == '1' and resp_depto: despesa['status'] = '5' elif despesa['status'] == '2' and resp_fin: despesa['status'] = '6' try: despesa['modificado_por'] = current_user.email despesa['data_ult_alt'] = datetime.now().strftime('%d/%m/%Y') db.child('despesas').child(id).update(despesa, current_user.idToken) send_mail(despesa, current_user, motivo) except Exception as e: mensagem = 'Não foi possível atualizar essa despesa.' print(e) flash(mensagem) return redirect(url_for('despesas.listar')) return render_template('despesas/desaprovar.html', form=form, despesa=despesa)
def __init__(self, username): super().__init__() self.users_dic = dict() self.messages = dict() self.username = username self.uid = auth.current_user['localId'] self.win_id = None self.init_ui() self.users_streamer = db.child("users").stream(self.users_listener) self.message_streamer = db.child("user_messages").child(self.uid).stream(self.message_listener)
def add_book(): #book_id = uuid.uuid1().hex #id_b = str(book_id.hex) name = request.form['name'] author = request.form['author'] data = { #"id":book_id, "name": name, "author": author } db.child("books").push(data) #flash('Book Added!') return redirect("/")
def criar(): if current_user.is_active() and current_user.session_over(): current_user.reset_token() form = DespesaForm() if form.validate_on_submit(): despesa = { 'id': datetime.now().strftime('%Y%m%d%H%M%S'), 'centro_custo': form.centro_custo.data, 'criado_por': current_user.email, 'modificado_por': current_user.email, 'data_criacao': datetime.now().strftime('%d/%m/%Y'), 'data_pagamento': form.data_pagamento.data.strftime('%d/%m/%Y'), 'data_ult_alt': datetime.now().strftime('%d/%m/%Y'), 'departamento': form.departamento.data, 'descricao': form.descricao.data, 'empresa': form.empresa.data, 'fornecedor': form.fornecedor.data, 'forma_pagamento': form.forma_pagamento.data, 'previsao': form.previsao.data, 'observacao': form.observacao.data, 'tipo_solicitacao': form.tipo_solicitacao.data, 'valor_total': '{:.2f}'.format(form.valor_total.data), 'status': '1', 'tem_arquivo': False } if form.boleto.data is not None: despesa['tem_arquivo'] = True boleto = os.path.join('/tmp', secure_filename(form.boleto.data.filename)) form.boleto.data.save(boleto) if despesa['departamento'] == 'diretoria': despesa['status'] = '2' try: if form.boleto.data is not None: response = storage.child('boletos/' + despesa['id']).put(boleto, current_user.idToken) despesa['download_token'] = response['downloadTokens'] db.child('despesas').child(despesa['id']).update(despesa, current_user.idToken) send_mail(despesa, current_user) return redirect(url_for('despesas.listar')) except Exception as e: mensagem = 'Não foi possível incluir essa despesa.' print(e) flash(mensagem) return redirect(url_for('despesas.criar')) return render_template('despesas/criar.html', form=form)
def edit(id): if request.method == "POST": name = request.form['name'] author = request.form['author'] data = { "name": name, "author": author } #update the book db.child("books").child(id).update(data) return redirect("/") book = db.child("books").order_by_key().equal_to(id).get() return render_template('edit.html', data = book)
def listar(): if current_user.is_active() and current_user.session_over(): current_user.reset_token() usuario = db.child('users').child(current_user.localId).get(current_user.idToken) usuario = dict(usuario.val()) data = {} try: data = db.child('despesas').get(current_user.idToken) data = dict(data.val()) except Exception as e: data = {} despesas = [] for k, v in data.items(): despesa = v despesa['id'] = k despesa['data_criacao'] = datetime.strptime(despesa['data_criacao'], '%d/%m/%Y') despesa['data_pagamento'] = datetime.strptime(despesa['data_pagamento'], '%d/%m/%Y') despesa['data_ult_alt'] = datetime.strptime(despesa['data_ult_alt'], '%d/%m/%Y') delta = datetime.now() - despesa['data_ult_alt'] if despesa['status'] >= '4' and delta.days > 120: continue despesas.append(despesa) despesas = sorted(despesas, key=lambda k: k['data_criacao'], reverse=True) depto_usuario = current_user.departamento if depto_usuario == 'financeiro': return render_template('despesas/listar.html', despesas=despesas, is_dba=usuario['DBA']) elif current_user.departamento == 'administrativo': despesas = [despesa for despesa in despesas if (despesa['departamento'] == depto_usuario or despesa['departamento'] == 'estoque' or despesa['criado_por'] == current_user.email)] return render_template('despesas/listar.html', despesas=despesas, is_dba=usuario['DBA']) else: despesas = [despesa for despesa in despesas if (despesa['departamento'] == depto_usuario or despesa['criado_por'] == current_user.email)] return render_template('despesas/listar.html', despesas=despesas, is_dba=usuario['DBA'])
def Index(): #book_id = random.random() all_books = db.child("books").get() if all_books.val() == None: return render_template('index.html') else: return render_template('index.html', books_lst= all_books)
def editar(id): if current_user.is_active() and current_user.session_over(): current_user.reset_token() if verify_dba(current_user): return redirect(url_for('despesas.listar')) usuario = db.child('users').child(id).get(current_user.idToken) usuario = dict(usuario.val()) usuario['id'] = id form = UserForm() if form.validate_on_submit(): usuario = { 'nome': form.nome.data, 'sobrenome': form.sobrenome.data, 'email': form.email.data, 'departamento': form.departamento.data, 'RD': form.representante.data, 'DBA': form.dba.data, 'Diretor': form.diretor.data } print(usuario) try: db.child('users').child(id).update(usuario, current_user.idToken) except Exception as e: mensagem = 'Não for possível atualizar os dados deste usuário.' print(e) flash(mensagem) return redirect(url_for('users.detalhar', id=id)) elif request.method == 'GET': form.nome.data = usuario['nome'] form.sobrenome.data = usuario['sobrenome'] form.email.data = usuario['email'] form.departamento.data = usuario['departamento'] form.representante.data = usuario['RD'] form.dba.data = usuario['DBA'] form.diretor.data = usuario['Diretor'] return render_template('users/editar.html', form=form, usuario=usuario)
def deletar(id): if current_user.is_active() and current_user.session_over(): current_user.reset_token despesa = db.child('despesas').child(id).get(current_user.idToken) despesa = dict(despesa.val()) try: if despesa['tem_arquivo']: storage.child('gs://').delete('boletos/' + id) db.child('despesas').child(id).remove(current_user.idToken) except Exception as e: mensagem = 'Não foi possível deletar a despesa' print(e) flash(mensagem) return redirect(url_for('despesas.listar'))
def send_mail(despesa, current_user, motivo=None): MAIL_DOMAIN = Config.MAIL_DOMAIN ADMIN = Config.ADMIN sender = current_user.email + '@' + MAIL_DOMAIN departamento = 'administrativo' if despesa['departamento'] == 'estoque' else despesa['departamento'] recipients = dict(db.child('users').get(current_user.idToken).val()) recipients = [v['email'] + '@' + MAIL_DOMAIN for k, v in recipients.items() if v['RD'] and v['departamento'] == departamento] if despesa['status'] == '1': subject = '[WebSD] Uma nova solicitação foi criada' template = 'status1' elif despesa['status'] == '2': subject = '[WebSD] Uma nova solicitação foi aprovada pelo Responsável do Departamento' recipients = [ADMIN, despesa['criado_por'] + '@' + MAIL_DOMAIN] template = 'status2' elif despesa['status'] == '3': subject = '[WebSD] Há uma nova solicitação para ser incluida no sistema' recipients = [ADMIN] template = 'status3' elif despesa['status'] == '4': sender = ADMIN recipients += [despesa['criado_por'] + '@' + MAIL_DOMAIN] template = 'status4' elif despesa['status'] == '5': subject = '[WebSD] Sua solicitação de despesa NÃO foi aprovada pelo Responsável do Departamento' recipients = [despesa['criado_por'] + '@' + MAIL_DOMAIN] template = 'status5' elif despesa['status'] == '6': sender = ADMIN recipients += [despesa['criado_por'] + '@' + MAIL_DOMAIN] subject = '[WebSD] Sua solicitação de despesa NÃO foi aprovada pelo Depto Financeiro' template = 'status6' elif despesa['status'] == '7': recipients += [ADMIN] subject = '[WebSD] A despesa ' + despesa['id'] + ' foi cancelada pelo usuário' template = 'status7' else: return None msg = Message(subject, sender=sender, recipients=recipients) msg.body = render_template('mail/' + template + '.txt', despesa=despesa, motivo=motivo) msg.html = render_template('mail/' + template + '.html', despesa=despesa, motivo=motivo) Thread(target=send_async_email, args=(app, msg)).start()
def detalhar(id): if current_user.is_active() and current_user.session_over(): current_user.reset_token() usuario = db.child('users').child(current_user.localId).get(current_user.idToken) usuario = dict(usuario.val()) despesa = db.child('despesas').child(id).get(current_user.idToken) despesa = dict(despesa.val()) despesa['id'] = id if despesa['status'] <= '3' and despesa['tipo_solicitacao'] != '50': if 'previsao' not in despesa.keys(): teste_politica_pgto(despesa) elif despesa['previsao'] == "": teste_politica_pgto(despesa) if despesa['tem_arquivo']: try: arquivo_url = storage.child('boletos/' + id).get_url(despesa['download_token']) except Exception as e: print(e) else: arquivo_url = '#' despesa['forma_pagamento'] = FORMA_PGTO[despesa['forma_pagamento']] despesa['tipo_solicitacao'] = TIPO_SOLICITACAO[despesa['tipo_solicitacao']] if usuario['RD']: if current_user.departamento == despesa['departamento']: pode_aprovar = True elif current_user.departamento == 'administrativo' and despesa['departamento'] == 'estoque': pode_aprovar = True else: pode_aprovar = False else: pode_aprovar = False return render_template('despesas/detalhar.html', despesa=despesa, usuario=usuario, download=arquivo_url, pode_aprovar=pode_aprovar)
def detalhar(id): if current_user.is_active() and current_user.session_over(): current_user.reset_token() if verify_dba(current_user): return redirect(url_for('despesas.listar')) usuario = db.child('users').child(id).get(current_user.idToken) usuario = dict(usuario.val()) usuario['id'] = id return render_template('users/detalhar.html', usuario=usuario)
def setValuesInFirebase(self): validation = self.validate() if validation: titulo = self.lineEdit_titulo.text() numerodepaginas = self.lineEdit_numerodepaginas.text() ano = self.lineEdit_ano.text() genero = self.lineEdit_Genero.text() descricao = self.lineEdit_descricao.text() autor = self.lineEdit_autor.text() book_update = { 'title': titulo, 'pages': numerodepaginas, 'genre': genero, 'description': descricao, 'year': ano, 'author': autor } book = db.child('books').order_by_child("isbn").equal_to( self.editing_book.isbn).get().each() db.child('books').child(book[0].key()).update(book_update) msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.NoIcon) msg.setText("Sucesso") msg.setInformativeText("Alterações salvas com sucesso!") msg.setWindowTitle("Sucesso") msg.exec_() if self.mainWindow: if loggedUser != None and loggedUser.level == LevelOfAccess.ADMIN: self.mainWindow.stackedWidget.setCurrentIndex(4) else: self.mainWindow.stackedWidget.setCurrentIndex(0) else: print("Validation Error")
def save_to_firebase(self): validation = self.validate() if validation: titulo = self.lineEdit_titulo.text() isbn = self.lineEdit_ISBN.text() numerodepaginas = self.lineEdit_numerodepaginas.text() ano = self.lineEdit_ano.text() genero = self.lineEdit_Genero.text() descricao = self.lineEdit_descricao.text() autor = self.lineEdit_autor.text() book = Book(isbn, titulo, numerodepaginas, genero, descricao, ano, autor) db.child('books').push(book.to_dict()) msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.NoIcon) msg.setText("Sucesso") msg.setInformativeText("Cadastrado com sucesso!") msg.setWindowTitle("Sucesso") msg.exec_() self.lineEdit_titulo.setText('') self.lineEdit_ISBN.setText('') self.lineEdit_numerodepaginas.setText('') self.lineEdit_ano.setText('') self.lineEdit_Genero.setText('') self.lineEdit_descricao.setText('') self.lineEdit_autor.setText('') if self.mainWindow: if loggedUser != None and loggedUser.level == LevelOfAccess.ADMIN: self.mainWindow.stackedWidget.setCurrentIndex(4) else: self.mainWindow.stackedWidget.setCurrentIndex(0) else: print("Validation Error")
def list_books(self): self.titulos = [] self.textBrowser_info.setText("") self.books = db.child('books').get().each() if self.books: for book in self.books: #print(book.val()['title']) self.titulos.append(book.val()['title'].upper()) self.textBrowser_info.setText( self.textBrowser_info.toPlainText() + "{} (por {})\n".format(book.val()['title'], book.val()['author']))
def list_users(self): self.userslist = [] self.textBrowser_info.setText("") self.users = db.child('users').get().each() if self.users: for self.user in self.users: #print(self.user.val()['name']) self.userslist.append(self.user.val()['email'].lower()) self.textBrowser_info.setText( self.textBrowser_info.toPlainText() + "{} ({})\n".format(self.user.val()['email'], self.user.val()['name']))
def control(self): email = self.email.text() password = self.password.text() try: auth.sign_in_with_email_and_password(email, password) except: QMessageBox.warning(self, 'Error', "Wrong username or password! \n\n") print(sys.exc_info()) return uid = auth.current_user['localId'] username = db.child('users').child(uid).child('username').get().val() self.confirm.emit(username) self.close()
def load_user_info(self): try: user = db.child('users').child(self.localId).get(self.idToken) user = {info.key(): info.val() for info in user.each()} self.nome = user['nome'] self.sobrenome = user['sobrenome'] self.email = user['email'] self.departamento = user['departamento'] self.DBA = bool(user['DBA']) self.RD = bool(user['RD']) except: self.nome = 'Cadatrar' self.sobrenome = 'Usuário' self.email = admin self.departamento = 'Sem departamento' self.DBA = False self.RD = False return None
def listar(): if current_user.is_active() and current_user.session_over(): current_user.reset_token() if verify_dba(current_user): return redirect(url_for('despesas.listar')) data = db.child('users').get(current_user.idToken) data = dict(data.val()) usuarios = [] for k, v in data.items(): usuario = v usuario['id'] = k usuarios.append(usuario) usuarios = sorted(usuarios, key=lambda k: (k['departamento'], k['nome'])) return render_template('users/listar.html', usuarios=usuarios)
def authenticate(self): email = self.lineEdit_login.text() password = self.lineEdit_senha.text() global firebase_user global loggedUser firebase_user, loggedUser = None, None try: firebase_user = auth.sign_in_with_email_and_password( email, password) except requests.exceptions.HTTPError as e: error_json = e.args[1] error = json.loads(error_json)['error'] if error['message'] == "INVALID_PASSWORD": infoText = "Senha inválida" elif error['message'] == "EMAIL_NOT_FOUND": infoText = "Email não cadastrado" elif error['message'] == "INVALID_EMAIL": infoText = "Email inválido" else: infoText = "Erro no Login" msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Critical) msg.setText("Erro") msg.setInformativeText(infoText) msg.setWindowTitle("Erro") msg.exec_() if firebase_user: userDict = db.child('users').order_by_child('email').equal_to( email).get().each() loggedUser = User.from_dict(userDict[0].val()) if loggedUser.level == LevelOfAccess.ADMIN: self.mainWindow.stackedWidget.setCurrentIndex(2) else: self.mainWindow.stackedWidget.setCurrentIndex(3)
filename = os.path.join(scriptpath, 'config') with open (filename,"r") as file: uid=file.read() def handler(signum,frame): print("sig") break while True : print("==========Online===========") signal.signal(signal.SIGALRM,break) signal.alarm(10) tempStatus=status.getStatus() myMac=list(tempStatus.keys())[0] print(myMac) try: command=db.child("users").child(uid).child("status").child(myMac).child("command").get().val() shutdown=db.child("users").child(uid).child("status").child(myMac).child("shutdown").get().val() print(command," ",shutdown) #if command is not None and command!="-": # subprocess.getoutput(command) # #print(subprocess.getoutput(command)) # result=subprocess.getoutput(command) # db.child("users").child(uid).child("status").child(myMac).child("result_command").set(result) # print("command : ", command) #if shutdown is not None and shutdown==1: # #db.child("users").child(uid).child("status").child(myMac).child("shutdown").set(0) # subprocess.getoutput('sudo shutdown -h now') # print("shutdowned") #db.child("users").child(uid).child("status").update(tempStatus) print("Send status to Firebase finished") except Exception as exc:
import time from firebase import db import os.path import json scriptpath = os.path.dirname(__file__) filename = os.path.join(scriptpath, 'config') with open (filename,"r") as file: uid=file.read() while True : if checknet.is_connected()and uid is not '': print("==========Online===========") tempStatus=status.getStatus() myMac=list(tempStatus.keys())[0] print(myMac) try: command=db.child("users").child(uid).child("status").child(myMac).child("command").get().val() shutdown=db.child("users").child(uid).child("status").child(myMac).child("shutdown").get().val() print(command," ",shutdown) if command is not None and command!="-": subprocess.getoutput(command) #print(subprocess.getoutput(command)) result=subprocess.getoutput(command) db.child("users").child(uid).child("status").child(myMac).child("result_command").set(result) print("command : ", command) if shutdown is not None and shutdown==1: db.child("users").child(uid).child("status").child(myMac).child("shutdown").set(0) subprocess.getoutput('sudo shutdown -h now') print("shutdowned") db.child("users").child(uid).child("status").update(tempStatus) print("Send status to Firebase finished") except :
def editar(id): if current_user.is_active() and current_user.session_over(): current_user.reset_token() despesa = db.child('despesas').child(id).get(current_user.idToken) despesa = dict(despesa.val()) despesa['id'] = id if 'previsao' not in despesa.keys(): despesa['previsao'] = "" form = DespesaForm() if form.validate_on_submit(): despesa = { 'centro_custo': form.centro_custo.data, 'modificado_por': current_user.email, 'data_pagamento': form.data_pagamento.data.strftime('%d/%m/%Y'), 'data_ult_alt': datetime.now().strftime('%d/%m/%Y'), 'departamento': form.departamento.data, 'descricao': form.descricao.data, 'empresa': form.empresa.data, 'fornecedor': form.fornecedor.data, 'forma_pagamento': form.forma_pagamento.data, 'observacao': form.observacao.data, 'tipo_solicitacao': form.tipo_solicitacao.data, 'valor_total': '{:.2f}'.format(form.valor_total.data), 'previsao': form.previsao.data, 'status': '1' } if form.boleto.data is not None: despesa['tem_arquivo'] = True boleto = os.path.join('/tmp', secure_filename(form.boleto.data.filename)) form.boleto.data.save(boleto) try: despesa['modificado_por'] = current_user.email despesa['data_ult_alt'] = datetime.now().strftime('%d/%m/%Y') if form.boleto.data is not None: response = storage.child('boletos/' + id).put(boleto, current_user.idToken) despesa['download_token'] = response['downloadTokens'] db.child('despesas').child(id).update(despesa, current_user.idToken) send_mail(despesa, current_user) return redirect(url_for('despesas.listar')) except Exception as e: mensagem = 'Não foi possível atualizar essa despesa.' print(e) flash(mensagem) return redirect(url_for('despesas.detalhar', id=id)) elif request.method == 'GET': form.centro_custo.data = despesa['centro_custo'] form.data_pagamento.data = datetime.strptime(despesa['data_pagamento'], "%d/%m/%Y") form.departamento.data = despesa['departamento'] form.descricao.data = despesa['descricao'] form.empresa.data = despesa['empresa'] form.fornecedor.data = despesa['fornecedor'] form.forma_pagamento.data = despesa['forma_pagamento'] form.previsao.data = despesa['previsao'] form.observacao.data = despesa['observacao'] form.tipo_solicitacao.data = despesa['tipo_solicitacao'] form.valor_total.data = float(despesa['valor_total']) return render_template('despesas/editar.html', form=form, despesa=despesa)