Forums

Files upload but not their representation in site

When I was testing my site in localhost, everything worked fine. Its a simple stock management program, you insert the item id and the number of remaining items, but what's happening is that when I change something and reload the page which displays the items list, the changes aren't applied.

Im gonna paste the code here since it isn't very important

from flask import Flask, render_template, url_for, flash, request, redirect
import os

import pandas as pd
from os import urandom

df = pd.read_csv('estoque.csv')
print(df)


app = Flask(__name__)
app.secret_key = urandom(24)



@app.route('/', methods=['GET'])

def index():
    try:
        os.remove('templates/aaaa.html')
    except:
        pass
    df.to_html('templates/aaaa.html')
    return render_template('index.html')


@app.route('/novo', methods=['GET', 'POST'])
def novo():
    global df
    if request.method == 'POST':
        nome = request.form['nome']
        numero = request.form['numero']

        if not nome:
            flash('Não inseriu o nome do item')
            return render_template('novo_item.html')
        if not numero:
            flash('Não inseriu o numero')
            return render_template('novo_item.html')


        else:
            df.loc[len(df), 'item'] = nome
            df.loc[len(df)-1, 'numero'] = numero
            df = df.sort_values(by=['item'])
            df.to_csv('estoque.csv', index=False)
            return render_template('novo_item.html')

    else:
        return render_template('novo_item.html')



@app.route('/inventario', methods=['GET'])
def tabela():
    try:
        os.remove('templates/aaaa.html')
    except:
        pass
    df.to_html('templates/aaaa.html')
    return render_template('aaaa.html')


@app.route('/registro', methods=['GET', 'POST'])
def registro():
    if request.method == 'POST':
        idd = request.form['id']
        numero = request.form['numero']

        if not idd:
            flash('Não inseriu o item')
            return render_template('registro.html')
        if not numero:
            flash('Não inseriu o numero')
            return render_template('registro.html')


        else:
            for row in range(0, len(df)):
                print(row, idd)
                if row==int(idd):
                    df.loc[row, 'numero'] = numero
                    print('\n', df.loc[row, 'numero'], '\n')


            df.to_csv('estoque.csv', index=False)
            return render_template('registro.html')

    else:
        return render_template('registro.html')

if __name__ == '__main__':
    app.run(debug=True)

I'm probably doing something extremely stupid, it's my first web app and I don't know my way through it very well yet. Thanks a lot

It looks like you're only making changes to the data in memory, so each time your website starts it will load the data from the file estoque.csv and drop any changes that had previously been made. You'll need to save that file each time there is a change if you want changes to persist.

That said, I'd recommend against doing persistent storage that way; in a free account with only one worker process, it would generally work, but if you upgraded to a paid account to handle more traffic, you'd have two processes accessing the file at the same time, and that would cause problems if they made conflicting changes. If I were you I'd look into storing the data in a MySQL database, which would work much better for concurrent access. We have a tutorial on creating a simple MySQL-backed Flask app here.

Thanks for answering. The thing is, when I look at my files folder and see the estoque.csv file, it is updated with the new information, but for some reason the program isn't able to see it. It looks as if it is using some older version of the csv for some reason, and I can't figure out why, or how could I make it use the updated version

Maybe you could try explicitly loading it using pd.read_csv at the start of each view function, rather than a one-off load at the top of the script?

Tried it but still no luck

@app.route('/inventario', methods=['GET'])
def tabela():
    df = pd.read_csv('estoque.csv')
    df.to_html('templates/aaaa.html')
    return render_template('aaaa.html')

Perhaps it's a working directory issue? The line

df = pd.read_csv('estoque.csv')

...will read the file estoque.csv from wherever the current working directory is, which might not be what you expect it to be. Try replacing all references to the filename with an explicit full path, like /home/danteramacciotti/something/estoque.csv

I found a fix and it was using a better way of displaying the table, instead of the dumb idea I had before. The aaaa.html file is now:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Inventário</title>
</head>
<body>

{% for table in tables %}
            {{titles[loop.index]}}
            {{ table|safe }}
{% endfor %}
</body>
</html>

which solved the problem, instead of creating a new html file with the Dataframe info every time someone opened /inventario. Thank you for your time, and sorry for the stupid question :)

Glad to hear that you made it work!