0

I have the following Flask app. It renders a html page with a form for each cell of the dataframe and allows the user to edit the cells and post the form data. The app then updates the dataframe.

'''

from flask import Flask, render_template, url_for, request, redirect
import pandas

app = Flask(__name__)

df_abc = pandas.read_excel('source1.xlsx')

@app.route('/modify/', methods=['POST', 'GET'])
def modify():
    if request.method == 'POST':
        global df_abc
        df_abc = update_df_function() # this function returns an updated df based on the POST data
        return redirect(url_for('modify'))
    
    else:
        table_data = df_abc.to_dict(orient='records')
        return render_template('modify.html', table_data=table_data)

''' However, I would like the following to work:

from flask import Flask, render_template, url_for, request, redirect
import pandas

app = Flask(__name__)

df_abc = pandas.read_excel('source1.xlsx')
df_xyz = pandas.read_excel('source2.xlsx')

@app.route('/modify/<name>', methods=['POST', 'GET'])
def modify(name):
    if request.method == 'POST':
        global name
        name = update_df_function() # this function returns an updated df based on the POST data
        return redirect(url_for('modify'))
    
    else:
        table_data = name.to_dict(orient='records')
        return render_template('modify.html', table_data=table_data)

'''

This app would get the variable name from the Flask path. How can I set the variable names in the modify function (e.g. global df_abc) by using the string < name > from the Flask path? I.e. posting data from www.site.com/modify/df_abc should update df_abc, ./modify/df_xyz should update df_xyz etc.

Any help would be greatly appreciated. Thanks!

Bob-78
  • 11
  • 1
  • 7

1 Answers1

0

The answer is using globals() with globals()[name], as shown below, and explained in this answer https://stackoverflow.com/a/1373201

from flask import Flask, render_template, url_for, request, redirect
import pandas

app = Flask(__name__)

df_abc = pandas.read_excel('source1.xlsx')
df_xyz = pandas.read_excel('source2.xlsx')

@app.route('/modify/<name>', methods=['POST', 'GET'])
def modify(name):
    if request.method == 'POST':
        globals()[name] = update_df_function() # this function returns an updated df based on the POST data
        return redirect(url_for('modify'))
    
    else:
        table_data = globals()[name].to_dict(orient='records')
        return render_template('modify.html', table_data=table_data)
Bob-78
  • 11
  • 1
  • 7