Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

python - Displaying CSV file as HTML page using Flask

I have a CSV file called random.csv which I want to render on a html page if the user is logged in. I've tried using tablib for this.

__init__.py

    from flask import Flask
    import tablib

    app = Flask(__name__)
    dataset = tablib.Dataset()
    with open(os.path.join(os.path.dirname(__file__), 'random.csv')) as f:
    dataset.csv = f.read()

routes.py

    @app.route('/dataset', methods=['GET', 'POST'])
    @login_required
    def dataset():
        return dataset.html

This is the index.html file from where I want to link to the html page for the csv file.

{% extends "base.html" %}

{% block content %}
    <p><a href="{{ url_for('dataset') }}">Click to see CSV</a> </p>
{% endblock %}

And this is the dataset.html file where I want to see the CSV data.

{% extends "base.html" %}

{% block content %}

{% endblock %}

I'm getting this error: AttributeError: 'function' object has no attribute 'html' The error is on the line in routes.py file where I return the dataset.html file.

question from:https://stackoverflow.com/questions/65936700/displaying-csv-file-as-html-page-using-flask

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I solved it by using pandas instead tablib. In my routes.py file just did this:

import pandas as pd

@app.route('/dataset', methods=['GET', 'POST'])
@login_required
def dataset():
    table = pd.read_csv('filepath', encoding= 'unicode_escape')
    return render_template("dataset.html", data=table.to_html())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...