How to run python function by clicking html button?

笑着哭i 提交于 2019-12-13 07:59:29

问题


I am trying to make this web app to work but I am getting an error. these are the steps that web app is supposed to handle:

  1. import a file
  2. run the python script
  3. export the results

when I run python script independently( without interfering with flask), it works fine( I use Jupyter notebook) on the other hand, when I run it with flask (from prompt) I get an error:

File "app.py", line 88, in <module>
    for name, df in transformed_dict.items():
NameError: name 'transformed_dict' is not defined

Any idea of how can I make this web app to work? This is my first time using flask and I will appreciate any suggestions or guidance.

python file & html file

from flask import Flask,render_template,request,send_file
from flask_sqlalchemy import SQLAlchemy
import os
import pandas as pd
from openpyxl import load_workbook
import sqlalchemy as db

def transform(df):
    # Some data processing here 
    return df

app=Flask(__name__)

@app.route('/')
def index():
    return render_template('firstpage.html')


@app.route('/upload',methods=['Get','POST'])
def upload():
    file=request.files['inputfile']

    xls=pd.ExcelFile(file)

    name_dict = {}

    snames = xls.sheet_names

    for sn in snames:
        name_dict[sn] = xls.parse(sn)

    for key, value in name_dict.items():
        transform(value)
    transformed_dict={}

    for key, value in name_dict.items():
        transformed_dict[key]=transform(value)

#### wirte to excel example:
writer = pd.ExcelWriter("MyData.xlsx", engine='xlsxwriter')
for name, df in transformed_dict.items():
    df.to_excel(writer, sheet_name=name)
writer.save()

if __name__=='__main__':
    app.run(port=5000)

回答1:


Your block:

#### wirte to excel example:
writer = pd.ExcelWriter("MyData.xlsx", engine='xlsxwriter')
for name, df in transformed_dict.items():
    df.to_excel(writer, sheet_name=name)
writer.save()

should be part of your upload() function since that's where you define and fill transformed_dict. You just need to match the indentation there to the block above it.

The current error is coming up because it's trying to run that code as soon as you start your script, and transformed_dict doesn't exist at that point.



来源:https://stackoverflow.com/questions/58676832/how-to-run-python-function-by-clicking-html-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!