Files
user_manager_drupal6/csv_browser.py
2025-05-19 08:41:25 +02:00

73 lines
2.1 KiB
Python

import os
from flask import Flask, render_template_string, send_from_directory, request
import pandas as pd
EXPORTS_DIR = "exports"
PORT = 8899
app = Flask(__name__)
TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSV Viewer</title>
<link rel="stylesheet"
href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script
src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
</head>
<body>
<h2>📂 CSV Viewer</h2>
{% if files %}
<ul>
{% for file in files %}
<li><a href="/view?file={{ file }}">{{ file }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>Brak plików w katalogu <code>{{ dir }}</code>.</p>
{% endif %}
{% if table %}
<hr>
<h3>Plik: {{ filename }}</h3>
{{ table | safe }}
<script>
$(document).ready(function() {
$('#csv-table').DataTable();
});
</script>
{% endif %}
</body>
</html>
"""
@app.route("/")
def index():
files = [f for f in os.listdir(EXPORTS_DIR) if f.endswith(".csv")]
return render_template_string(TEMPLATE, files=files, table=None, dir=EXPORTS_DIR)
@app.route("/view")
def view_file():
filename = request.args.get("file")
if not filename or not filename.endswith(".csv"):
return "Niepoprawny plik.", 400
path = os.path.join(EXPORTS_DIR, filename)
if not os.path.exists(path):
return "Plik nie istnieje.", 404
try:
df = pd.read_csv(path)
html_table = df.to_html(classes="display", index=False, table_id="csv-table")
files = [f for f in os.listdir(EXPORTS_DIR) if f.endswith(".csv")]
return render_template_string(TEMPLATE, files=files, table=html_table, filename=filename, dir=EXPORTS_DIR)
except Exception as e:
return f"Błąd odczytu CSV: {e}", 500
if __name__ == "__main__":
os.makedirs(EXPORTS_DIR, exist_ok=True)
app.run(host="0.0.0.0", port=PORT)