Forums

struggle calling reload API & COR error

I have a flask app working fine , the only thing is when upload files(to work with pandas), need reload web to see new data. Every time I upload new excel files, the ones that are already uploaded are overwritten by the new ones and their upload date is modified to the current one, but in the rest of my flask, which is where I work with the data from those files, the data is from the previous ones until I do reload to the web.

I made a script when POST input files , call to API to reload. I've spent the last 8 hours trying to figure it out and trying things, but I don't know what else to do.

Currently my code is like this

html part:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form id="formulario-subida" action="/main" method="post" enctype="multipart/form-data">
      <label for="file1">Seleccione el primer archivo:</label><br>
      <input type="file" id="file1" name="file1"><br>
      <label for="file2">Seleccione el segundo archivo:</label><br>
      <input type="file" id="file2" name="file2"><br><br>
        <label for="file3">Seleccione el primer archivo:</label><br>
      <input type="file" id="file3" name="file3"><br>
      <input type="submit" value="Subir archivos">
    </form>

    <script>
    document.getElementById('formulario-subida').addEventListener('submit', function(event) {
      event.preventDefault();
      // Envía la solicitud de la API aquí
      username = 'xxxx';
      token = 'xxxxx'
      domain_name = "xxxxx;
      var xhr = new XMLHttpRequest();
      xhr.open('POST', 'https://www.pythonanywhere.com/api/v0/user/' + username + '/webapps/' + domain_name + '/reload/');
      xhr.setRequestHeader('Authorization', 'Token ' + token);
      xhr.onload = function() {
        if (xhr.status === 200) {
          // La solicitud se ha enviado correctamente. Puedes mostrar un mensaje de éxito al usuario aquí.
          window.location.href = '/main'
        }
      }
      xhr.onerror = function() {
        // Hubo un error con la solicitud. Puedes manejar el error aquí.
        console.error(xhr.status);
      }
      xhr.send();
    });
    </script>
</body>
</html>

flask app

from flask import Flask, request, render_template, make_response from flask_cors import CORS

app = Flask(__name__) cors = CORS(app)

lista = ["Menaje", "Textil 11", "Textil 12", "Orden", "Baños", "Iluminacion", "Deco", "Niños", "Actividades"] listaauto = ["pares", "impares", "fondopar", "fondoimpar", "pax", "2426", "1a3", "zona1", "zona2", "zona3", "zona4"]


@app.route("/") def archivos():
    return render_template("upload_files.html")

@app.route('/main', methods=['POST']) def main():
    # Obtener los campos de archivo del formulario
    archivo1 = request.files['file1']
    archivo2 = request.files['file2']
    archivo3 = request.files['file3']

    # Verificar si los archivos han sido enviados
    if archivo1 and archivo2:
        upload_dir ="/home/cesarmaestre84/inflowapp/static/archivos/"
        archivo1.save(upload_dir + "PROPUESTA_FINAL")
        archivo2.save(upload_dir + "PLAN")
        archivo3.save(upload_dir + "SG010")

        import datos
        repo = datos.check_datos()
        tied = datos.check_tie_dormunt()
        aires = datos.aire_total()
        return render_template("datos.html", repo=repo, tied=tied, aire=aires)


@app.route("/MV0") def metodoventa0():
    import check_market
    camion = check_market.check_market_repo()
    return render_template("MV0.html", camion=camion, lista=lista)

@app.route("/MV1") def metodoventa1():
    import repeticiones
    import datos_sgf
    import check_auto
    repo_sfg = datos_sgf.check_repoaire()
    repo_auto = check_auto.repo_auto()
    camion = check_auto.camiones_auto()
    reps = repeticiones.repeticiones_html
    return render_template("MV1.html", repo=repo_auto, lista=listaauto, camion=camion, reposgf=repo_sfg, reps=reps)

@app.after_request def add_header(response):
    response = make_response(response)
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

It is not clear from your post which data in your code is not updating.

Every time I upload new excel files, the ones that are already uploaded are overwritten by the new ones and their upload date is modified to the current one, but in the rest of my flask, which is where I work with the data from those files, the data is from the previous ones until I do reload to the web.

Sorry if I have not expressed myself correctly

When in your code do you load that data from file? If it's on the web app startup not inside the code that is handling request it won't be refreshed.

just when upload files , i have first "import datos" datos.py use pandas to read excel saved (one of them "file1"), and process data to return repo,tied and aires.

@app.route('/main', methods=['POST']) def main():
    # Obtener los campos de archivo del formulario
    archivo1 = request.files['file1']
    archivo2 = request.files['file2']
    archivo3 = request.files['file3']

    # Verificar si los archivos han sido enviados
    if archivo1 and archivo2:
        upload_dir ="/home/cesarmaestre84/inflowapp/static/archivos/"
        archivo1.save(upload_dir + "PROPUESTA_FINAL")
        archivo2.save(upload_dir + "PLAN")
        archivo3.save(upload_dir + "SG010")

        import datos
        repo = datos.check_datos()
        tied = datos.check_tie_dormunt()
        aires = datos.aire_total()
        return render_template("datos.html", repo=repo, tied=tied, aire=aires)

DATOS.PY:

import pandas as pd

archivo = "rute_to_my_file"


df2 = pd.read_excel(archivo, sheet_name="PICKING")
df = df2[["LV", "MV", "HASTA", "DESDE", "TIE"]].dropna()


def aire_total():
    aire0 = 0
    aire1 = 0
    aire2 = 0

    articulo0 = df[df["DESDE"].str.contains("-", regex=False, na=False) & (df['MV'] == 0) & (df["HASTA"] == "Buffer")]
    for articulo in articulo0["MV"]:
        aire0 += 1
    articulo1 = df[df["DESDE"].str.contains("-", regex=False, na=False) & (df['MV'] == 1) & (df["HASTA"] == "Buffer")]
    for articulo in articulo1["MV"]:
        aire1 += 1
    articulo2 = df[df["DESDE"].str.contains("-", regex=False, na=False) & (df['MV'] == 2) & (df["HASTA"] == "Buffer")]
    for articulo in articulo2["MV"]:
        aire2 += 1
    return aire0, aire1, aire2


def check_datos():
    repo_mv0 = 0
    repo_mv1 = 0
    repo_mv2 = 0
    df0 = df[df["DESDE"].str.contains("-", regex=False, na=False) & (df['MV'] == 0) & (df["HASTA"] == "Sales")]
    for articulo0 in df0["HASTA"]:
        if articulo0 == "Sales":
            repo_mv0 += 1

    df1 = df[df["DESDE"].str.contains("-", regex=False, na=False) & (df['MV'] == 1) & (df["HASTA"] == "Sales")]
    for articulo1 in df1["HASTA"]:
        if articulo1 == "Sales":
            repo_mv1 += 1

    df2 = df[df["DESDE"].str.contains("-", regex=False, na=False) & (df['MV'] == 2) & (df["HASTA"] == "Sales")]
    for articulo2 in df2["HASTA"]:
        if articulo2 == "Sales":
            repo_mv2 += 1

    return repo_mv0, repo_mv1, repo_mv2


def check_tie_dormunt():
    tie00d = 0
    tie01d = 0
    tie02d = 0

    articulo0d = df[(df['TIE'] == 0) & (df['MV'] == 0) & (df["HASTA"] == "Sales") & (
        df["DESDE"].str.contains("064-", regex=False, na=False))]

    for articulo in articulo0d["MV"]:
        tie00d += 1

    articulo1d = df[(df['TIE'] == 0) & (df['MV'] == 1) & (df["HASTA"] == "Sales") & (
        df["DESDE"].str.contains("064-", regex=False, na=False))]

    for articulo in articulo1d["MV"]:
        tie01d += 1

    articulo2d = df[(df['TIE'] == 0) & (df['MV'] == 2) & (df["HASTA"] == "Sales") & (
        df["DESDE"].str.contains("064-", regex=False, na=False))]

    for articulo in articulo2d["MV"]:
        tie02d += 1

    return tie00d, tie01d, tie02d

It's the first time I've tried to make an application, so I'm sorry if I'm failing in something obvious

It looks like everything (in terms of the input data) is dependent on this line in DATOS.PY: archivo = "rute_to_my_file" -- I'm assuming that this is not a real path; you should check if the path that you have there exists and if it matches the upload dir path.

Yes, sorry archivo = "/home/cesarmaestre84/inflowapp/static/archivos/PROPUESTA_FINAL" this real path i have , are same than upload_dir , path exist the files are uploading fine(and if check in the route i have files with the new upload datetime) every time.

Testing in my IDE, in datos.py i put a print after:

df2 = pd.read_excel(archivo, sheet_name="PICKING") // print df column ["LV"] print(df2["LV"])

when it started it prints, but if I relupload files without restarting the app, it doesn't print anymore

seems find the solution , just add a inside data.py:

def read_excel():
    df2 = pd.read_excel(archivo, sheet_name="PICKING")
    df = df2[["LV", "MV", "HASTA", "DESDE"]].dropna()
    return df

and call read_excel() every function i need.

Thx for help guys, appreciated