Interactive Flask Web App for Displaying CSV Data with Dynamic Text Visibility
from flask import Flask, render_template, request
import csv
app = Flask(__name__)
# Global variables to store selected chapter and section
selected_chapter = None
selected_section = None
@app.route('/', methods=['GET', 'POST'])
def index():
chapters = ['Chapter 1', 'Chapter 2']
sections = ['Section 1', 'Section 2']
if request.method == 'POST':
global selected_chapter, selected_section
selected_chapter = request.form['chapter']
selected_section = request.form['section']
return render_template('index.html', chapters=chapters, sections=sections, selected_chapter=selected_chapter, selected_section=selected_section)
return render_template('index.html', chapters=chapters, sections=sections)
@app.route('/choose', methods=['POST'])
def choose():
if selected_chapter and selected_section:
csv_file = f'Text/{selected_chapter}_{selected_section}.csv'
with open(csv_file, 'r') as file:
reader = csv.reader(file)
data = list(reader)
return render_template('index.html', data=data, selected_chapter=selected_chapter, selected_section=selected_section)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
This code demonstrates a Python web application built with Flask that provides an interactive way to display data from CSV files.
Features:
- Dropdown Selection: Users can select a chapter and section from dropdown menus, providing a structured way to navigate content.
- Dynamic CSV Reading: Upon selection, the app reads data from a corresponding CSV file in the 'Text' folder, dynamically loading the content.
- Interactive Text Visibility: The application allows for controlled visibility of text within the CSV data. Initially, only the first column is displayed. Users can interact to reveal hidden text in other columns for a limited time.
- User Input: A text box is provided for user input, enabling interactions like answering questions or providing feedback.
- Control Buttons: 'Answer' and 'Clear' buttons offer control over the display, revealing answers or resetting the interface.
Explanation:
- The code defines two routes: '/' for the main page with dropdown menus and '/choose' to handle the data display based on user selection.
- Global variables store the selected chapter and section, ensuring data consistency.
- The
csvmodule efficiently reads and parses data from the selected CSV file. - The
render_templatefunction renders the 'index.html' template, passing necessary data for dynamic content display. - The implementation of interactive text visibility and button functionality would be handled using HTML, CSS, and JavaScript within the 'index.html' template, enhancing user experience.
Note: This code snippet focuses on the backend logic. Frontend development (HTML, CSS, JavaScript) is crucial for creating the interactive elements and visual presentation of the application.
原文地址: https://www.cveoy.top/t/topic/fw4r 著作权归作者所有。请勿转载和采集!