0

I want to parse file names from my app.py to graph.js. But I cannot get variable name to js file. I am using flask

Here is the file structure

- app/
  - flask_app.py
  - templates/
    -> index.html
    -> data/
      -> file1.csv
  - static/
    -> js/
      -> create-graph.js

My app looks like this (related part):

data_files = ["file1.xlsx", "file2.xlsx", "file3.xlsx"]
cur = 0
df1 = pd.read_excel("data/" + data_files[cur])

df1.to_csv('templates/data/' + data_files[cur][:10] + '.csv', encoding='utf-8', index=False)

So I have files that I convert from xlsx to csv, and then I want to pull the csv file with its name. I need to pass the data_files and cur to my .js file... Here is the related .js:

function parseData(createGraph) {
var name = '{{data_files[cur][:10]}}';
console.log(name);
Papa.parse("static/data/" + name + ".csv", {
    download: true,
    complete: function(results) {
        createGraph(results.data);
    }
});

}

But it seems that I cannot pass the file name to here: var name = '{{data_files[cur][:10]}}';

On the console it gives me the exact same string

So what I am doing wrong ?

I also tried adding this to app:

@app.route('/create-graph.js')
def script():
    return render_template('create-graph.js', fileName="data_files[cur][:10]")

Still no luck...

If anyone asks, here is how I call .js file:

...
<script src="{{ url_for('static', filename='js/create-graph.js') }}"></script>
...
0

1 Answer 1

0

You need to pass the parameter to render_template as a variable with desired values.

If you've only one file then you can just use.

app.py

@app.route('/create-graph.js')
def script():
    data_file = "test.csv"
    return render_template('create-graph.js', file_name=data_file)

.js file

function parseData(createGraph) {
var name = '{{file_name}}';
console.log(name);
Papa.parse("static/data/" + name + ".csv", {
    download: true,
    complete: function(results) {
        createGraph(results.data);
    }
});
}

If data_files is a list of list or dictionary of the list.

.js

function parseData(createGraph) {
var name = '{{data_files_cur[:10]}}'; // here you can get at max 10 files
console.log(name);
Papa.parse("static/data/" + name + ".csv", {
    download: true,
    complete: function(results) {
        createGraph(results.data);
    }
});
}

app.py

@app.route('/create-graph.js')
def script():
    # define cur  and data_files
    data_files_cur = data_files[cur];
    return render_template('create-graph.js', data_files_cur=data_files_cur)

It looks you don't know much about flask template engine syntax. I would recommend you should read about Jinja/Mako or Django template syntax.

Sign up to request clarification or add additional context in comments.

2 Comments

No it is not working.. I am doing the exact same thing.
@BedirTapkan Could you paste your complete code in pastebin and share the link?