def save_to_firebase(self, file, documentId, filename): path_local = 'temp/' + filename file.save(path_local) path_on_cloud = "document/{}/{}".format(documentId, filename) upload = storage.child(path_on_cloud).put(path_local) url = storage.child(path_on_cloud).get_url(upload['downloadTokens']) return url
def post(self): pictureParser = reqparse.RequestParser() pictureParser.add_argument('picture', type=werkzeug.datastructures.FileStorage, location='files', required=True, help="This field cannot be blank." ) Data = pictureParser.parse_args() if not Data['picture']: return { 'status':'failed', 'message': 'This field cannot be blank.'},400 user=UserModel.find_by_id(get_jwt()['sub']) path_local="profile/{}.png".format(user.userId) Data['picture'].save(path_local) path_on_cloud = "profile/{}".format(user.userId) upload=storage.child(path_on_cloud).put(path_local) url=storage.child(path_on_cloud).get_url(upload['downloadTokens']) user.picture=url user.update_to_db() return { 'status':'success', 'data': user.picture},200
def update_problem(name, id): form = CreateQuestion() if request.method == 'GET': question = Question.query.filter_by(id=id).first() form.title.data = question.title form.content.data = question.content db.session.delete(question) db.session.commit() if form.validate_on_submit(): q = form ofile = q.title.data + '_o.txt' ifile = q.title.data + '_i.txt' #gerate inputfile q.inputfile.data.save('./' + ifile) storage.child('io/input/' + ifile).put('./' + ifile) os.remove(ifile) # f.close() #generate output file file = open('./' + ofile, 'w') file.close() with open('./' + ofile, 'w') as of: for line in q.output.data: line = line.rstrip('\n') of.write(line) of.close() storage.child('io/output/' + ofile).put('./' + ofile) os.remove(ofile) que = Question(title=q.title.data, content=q.content.data, outputfile=ofile, inputfile=ifile) for topic in request.form.getlist('topic'): t = Topic.query.filter_by(name=topic).first() t.questions.append(que) for company in request.form.getlist('company'): c = Company.query.filter_by(name=company).first() c.questions.append(que) db.session.add(que) db.session.commit() a = Admin.query.filter_by(username=name).first() a.question.append(que) db.session.commit() flash(que.title + "has been updated") return redirect(url_for('admin', name=name)) return render_template('update_problem.htm', name=name, id=id, form=form)
def mock_interview(name): if (request.method == "POST"): #update codes #update time return redirect(url_for('home')) questions = Question.query.all() n = len(questions) q1 = questions[random.randint(0, n - 1)] q2 = questions[random.randint(0, n - 1)] q3 = questions[random.randint(0, n - 1)] qs = [q1, q2, q3] inputs = [] outputs = [] for q in qs: fi = q.inputfile fo = q.outputfile storage.child('io/output/' + fo).download(fo) storage.child('io/input/' + fi).download(fi) custominput = open('./' + fi, 'r').read() customoutput = open('./' + fo, 'r').read() os.remove(fi) os.remove(fo) inputs.append(custominput) outputs.append(customoutput) print(custominput) else: # u = User.query.filter_by(username= name).first() # check = u.is_attempting # if not check: # u.is_attempting = True # db.session.commit() # return render_template('mock_interview.htm',name = name,q1 = q1,q2 = q2,q3 = q3,inputs = inputs,outputs = outputs) # else: # return render_template('not_allowed.htm') # return render_template('not_allowed.htm') return render_template('mock_interview.htm', name=name, q1=q1, q2=q2, q3=q3, inputs=inputs, outputs=outputs)
def problem(id): question = Question.query.filter_by(id=id).first() companies = [] topics = [] for c in Company.query.all(): if question in c.questions: companies.append(c) for t in Topic.query.all(): if question in t.questions: topics.append(t) fi = question.inputfile fo = question.outputfile customoutput = storage.child('io/output/' + fo).get_url(fo) custominput = storage.child('io/input/' + fi).get_url(fi) if request.method == 'POST': if request.form['solved'] == "true": flash("Well Done!!", "success") code = request.form["code"] question = Question.query.filter_by(id=id).first() if question not in current_user.solves: current_user.solves.append(question) return render_template('problem.htm', result="", code=code, inp="", question=question, id=question.id, companies=companies, topics=topics, customoutput=customoutput, custominput=custominput) else: return render_template('problem.htm', result="", code="", inp="", question=question, id=question.id, companies=companies, topics=topics, customoutput=customoutput, custominput=custominput)
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 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 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 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)