Search code examples
pythonflaskjinja2

Flask redirect to url_for


I have he following data_analytics.html` which in the end provides the

enter image description here view:

{% extends 'base.html' %} {% block title %}Home{% endblock %}
{% block content %}
<!-- <h1 align="center" >Your Files</h1> -->
<br />
<table class="table table-bordered table-hover">

    <caption> Files Uploaded</caption>
    <tr>
        <th class="table-light"> # </th>
        <th class="table-light">File Name</th>
        <th class="table-light">Date</th>
        <th class="table-light">Access Data</th>
    </tr>

{% for file in csv_file %}
<tr>
    <!-- <td>{{ file.id }}</td> -->
    <th scope="row">1</th>
    <td>{{ file.data }}</td>
    <td>{{ file.date }}</td>
    <td><a href="{{ url_for('views.data_analytics', data=file.data) }}">View Data</a></td>
{%endfor%}
</table>

{% endblock %}

Is there a way that when the user clicks on the link to have displayed the content of the .csv file using python/flask ?

Tried to create a function that redirects to an url_for but not working`


Solution

  • try this:

    In this 'a' put a 'target="_blank"'

    <a href="{{ url_for('views.data_analytics', data=file.data) }}" target="_blank">View Data</a>
    

    And, in the python let's create a new function:

    from flask import send_from_directory    
    
    @app.route('/csv')
    def see_file():
       return send_from_directory(directory='static', path='files/cheat_sheet.pdf')
    

    Just change the path and the directory. And the file is going to open in a new tab.