skip to Main Content

I have the following environment deployed from VS Code

enter image description here

It was deployed in App Services on Azure using Python 3.9 and Flask to create an application on a B1 plan (Total ACU: 100, 1.75 GB memory, 1 vCPU). The app.py script is as follows:

from flask import Flask, render_template, request, send_file
import os
from scripts.misfunciones import process_data

app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(__file__), 'uploads')

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # Guardar los archivos subidos
        data_file = request.files['data_file']
        parametro_file = request.files['parametro_file']
        unidades_file = request.files['unidades_file']
        
        if not os.path.exists(app.config['UPLOAD_FOLDER']):
            os.makedirs(app.config['UPLOAD_FOLDER'])

        data_path = os.path.join(os.path.dirname(__file__), 'uploads', 'DATA.xlsx')
        parametro_path = os.path.join(os.path.dirname(__file__), 'uploads', '240424RF_Parametro.xlsx')
        unidades_path = os.path.join(os.path.dirname(__file__), 'uploads', '240306RF_Unidades.xlsx')
        output_path = os.path.join(os.path.dirname(__file__), 'uploads', 'DATA_FIN.xlsx')

        data_file.save(data_path)
        parametro_file.save(parametro_path)
        unidades_file.save(unidades_path)
        
        process_data(data_path, parametro_path, unidades_path, output_path)
        
        return send_file(output_path, as_attachment=True)

    return render_template('index.html')

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

and the script misfunciones.py:

import pandas as pd
import openpyxl
import re
chars_dict = {
    'n':'','*':'','°':'','(':'',')':'','+':'',
    '/':'','.':'','_':'',' ':'',',':'',''':'',
    'á':'a','é':'e','í':'i','ó':'o','ú':'u','-':''
}

def var_lower(df):
    for i in df.columns[1:]:
        df[str(i)] = df[str(i)].str.lower()
        
def remove_pattern(df, pattern):
    for column in df.columns:
        df[column] = df[column].replace(pattern, '', regex=True)
    return df

def process_data(data_path, parametro_path, unidades_path, output_path):
    DATA = pd.read_excel(data_path, engine='openpyxl')
    Parametro = pd.read_excel(parametro_path, engine='openpyxl')
    Unidades = pd.read_excel(unidades_path, engine='openpyxl')

    DATA_CORR = DATA.copy()
    Parametro_CORR = Parametro.copy()
    Unidades_CORR = Unidades.copy()

    DATA_CORR = remove_pattern(DATA_CORR, 'αφ')
    DATA_CORR = remove_pattern(DATA_CORR, 'αδ')
    DATA_CORR = remove_pattern(DATA_CORR, 'φ')

    var_lower(DATA_CORR)
    var_lower(Parametro_CORR)
    var_lower(Unidades_CORR)
    for char, replacement in chars_dict.items():
        escaped_char = re.escape(char)
        DATA_CORR = DATA_CORR.replace(escaped_char, replacement, regex=True)
        Parametro_CORR = Parametro_CORR.replace(escaped_char, replacement, regex=True)
        Unidades_CORR = Unidades_CORR.replace(escaped_char, replacement, regex=True)

    Unificar_Unidad = []
    cantidad = 0
    for i in DATA_CORR['ID-UNIDADES']:
        cantidad += 1
        for j in range(len(Unidades_CORR)):
            for k in Unidades_CORR.columns[1:]:
                if i == Unidades_CORR[k][j]:
                    Unificar_Unidad.append(j + 1)
                    break
            if cantidad == len(Unificar_Unidad):
                break
        if cantidad != len(Unificar_Unidad):
            Unificar_Unidad.append(9999)
    DATA['num_unid'] = Unificar_Unidad

    Unificar_Param = []
    cantidad = 0
    for i in DATA_CORR['ID-PARANETROS']:
        cantidad += 1
        for j in range(len(Parametro_CORR)):
            for k in Parametro_CORR.columns[1:]:
                if i == Parametro_CORR[k][j]:
                    Unificar_Param.append(j + 1)
                    break
            if cantidad == len(Unificar_Param):
                break
        if cantidad != len(Unificar_Param):
            Unificar_Param.append(9999)
    DATA['num_param'] = Unificar_Param

    DATA.to_excel(output_path, index=False)
    return output_path

script index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subir Archivos</title>
</head>
<body>
    <h1>Subir Archivos para Procesar</h1>
    <form method="POST" enctype="multipart/form-data">
        <label for="data_file">Archivo DATA:</label>
        <input type="file" name="data_file" id="data_file" required><br><br>
        <label for="parametro_file">Archivo Parametro:</label>
        <input type="file" name="parametro_file" id="parametro_file" required><br><br>
        <label for="unidades_file">Archivo Unidades:</label>
        <input type="file" name="unidades_file" id="unidades_file" required><br><br>
        <input type="submit" value="Procesar">
    </form>
</body>
</html>

However, the application gives an error
enter image description here

I have run it locally and it works correctly. I don’t know what is causing the problem, but I think it might be related to the Excel files or some kind of permission. An HTTP 503 error appears in the error list.

I have also tried running it in memory without storing the Excel files, and it worked locally, but not on Azure.

Please, I will appreciate your support to deploy this application correctly on azure.

2

Answers


  1. Chosen as BEST ANSWER

    In the end it was a version error issue between pandas and numpy libraries :D


  2. Yes, Issue could be related to file path of Excel file. I would request you to deploy the excel file with the app files or keep the Excel file in same folder structure of the app file, so that it gets deployed to azure with app file and paths are correct.

    To cross check if you application is deployed fine I would suggest to render only the index file in index route (‘/’), and perform process of excel file in different route and see if Index file is rendered or not.

    Below is my Flask app directory which worked for me.

    /Flask_App
    --/static
      --/images
        --azure-icon.svg
    --/templates
        -- index.html
    --app.py
    --requirements.txt
    

    index.html:

    <!doctype html>
    <head>
        <title>Hello Azure - Python Quickstart</title>
    </head>
    <html>
       <body>
        <div>
            <img src="{{url_for('static', filename='images/azure-icon.svg')}}" alt="Azure Logo" width="192" height="192"/>
            <h1>Welcome to Azure</h1>  
            <h2>{{message}}</h2>          
          </div>
       </body>
    </html>
    

    app.py:

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello():
        message = "Greetings! Wecome to Flask App"
        return render_template('index.html',message=message)
    
    if __name__ == "__main__":
        app.run()
    

    Steps to deploy to WebApp using VS code

    1. Click on Webapp icon in Azure extension and select Deploy to Web App
    2. Select your Project folder
    3. Select your Web App from the list
    4. Click on deploy.
    5. Deployment successful

    OUTPUT:

    Local :

    Azure :

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search