How do you put a local file to download in flask or python?

Asked

Viewed 771 times

0

had to download a file in python or flask I tried so but I think it just opens the file

@app.route("/downloads/", methods=['GET', 'POST'])
def orac_detal():
                global datas, listaComTudo, nomesDespesas, df          
                state = {'gera':0, 'gera_total_csv':0, 'gera_orcamento':0, 'gera_total':0, 'taxas':0, 'gera_agrupamento':0, 'orac_detal':1}

                m = np.zeros((156,96))



                for loja in lojas:
                    if os.path.isfile("./.pickles/orcamentoAux_"+str(loja)+".pickle"):
                        with open(r"./.pickles/orcamentoAux_"+str(loja)+".pickle", "rb") as input_file:
                            foo = pickle.load(input_file)
                            datas = foo['datas'] # lista com todas as datas, para ser o cabeçalho da planilha
                            listaComTudo = foo['listaComTudo'] # lista de lista, em que cada lista interna tem os dados de uma despesa
                            nomesDespesas = foo['nomesDespesas'] # lista com o nome de todas as despesas, para ser inserida no final usando a função de colocar na primeira coluna


                for i in range(len(listaComTudo)):
                    m[i] += listaComTudo[i]

                for i in range(len(listaComTudo)):
                    nomesDespesas[i] = nomesDespesas[i].replace(","," ")
                    listaComTudo[i] = [nomesDespesas[i]] + listaComTudo[i]

                dicionario = {}
                for i in range(len(nomesDespesas)):
                    chave = nomesDespesas[i][23:]
                    dicionario[chave] = m[i] 

                df = pd.DataFrame.from_dict(data=dicionario, orient='index', columns=datas)

                writer = pd.ExcelWriter(
                    'despesas_detal.xlsx', engine='xlsxwriter')
                df.to_excel(writer, 'Sheet1')    
                writer.save()

                return df.to_csv('despesas_detal.csv',mode='a')

def return_files_tut():
        try:
            return send_file('/home/orbistec2/delphos_3.0/despesas_detal.xlsx', attachment_filename='despesas_detal.xlsx')
        except Exception as e:
            return str(e)

1 answer

2

Simply create a folder called static and put the file there; flask creates the route to that folder automatically.

Then just direct the download to the link; You can use the function url_for flask to generate the right link: `

return redirect(url_for('static', filename='despesas_detal.xlsx'))

Another less common way is to return bytes directly. You can pass bytes to the make_response:

with open('arquivo.xlsx', 'rb') as f: 
     dados = f.read() # le o arquivo binariamente
return make_response((dados, 
    {'content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
  • Return redirect(url_for('.Static','despesas_detal.csv')) , it accuses this error : Typeerror: url_for() takes 1 positional argument but 2 Were Given

  • 1

    Try it like this, @matheusteixeira: return redirect(url_for('static', filename='despesas_detal.xlsx')) adding the parameter filename.

  • 1

    That’s right, I forgot the filename - edited the reply @Igorcavalcanti thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.