问题出在 pandas 的 DataFrame 对象不再支持 append 方法。从 pandas 1.4.0 版本开始,append 方法已被弃用,推荐使用 concat 方法来合并 DataFrame。
from flask import Flask, render_template, request, redirect, url_for, flash
import pandas as pd
import os
import loggingapp = Flask(__name__)
app.secret_key = 'your_secret_key' # 用于 flash 消息
CSV_FILE = 'data.csv'# 设置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)# 初始化 CSV 文件
def init_csv():columns = ['日期', '每日涨停数', '每日交易量(万亿)', '上涨比率', '最高连板', '最高板大面数', '其他']df = pd.DataFrame(columns=columns)df.to_csv(CSV_FILE, index=False, encoding='utf-8')# 检查 CSV 文件是否存在,如果不存在则创建
try:pd.read_csv(CSV_FILE)
except FileNotFoundError:init_csv()@app.route('/')
def index():try:df = pd.read_csv(CSV_FILE)# 按日期降序排列df = df.sort_values(by='日期', ascending=False)return render_template('index.html', data=df.to_dict(orient='records'))except Exception as e:logger.error(f'读取 CSV 文件时出错: {e}')flash(f'读取 CSV 文件时出错: {e}')return render_template('index.html', data=[])@app.route('/add', methods=['POST'])
def add_data():try:new_row = {'日期': request.form['日期'],'每日涨停数': int(request.form['每日涨停数']),'每日交易量(万亿)': float(request.form['每日交易量(万亿)']),'上涨比率': float(request.form['上涨比率']),'最高连板': int(request.form['最高连板']),'最高板大面数': int(request.form['最高板大面数']),'其他': request.form['其他']}logger.debug(f'接收到的新数据: {new_row}')# 检查文件是否存在if not os.path.exists(CSV_FILE):init_csv()df = pd.read_csv(CSV_FILE)# 使用 pd.concat 替代 appendnew_df = pd.DataFrame([new_row])df = pd.concat([df, new_df], ignore_index=True)# 保存到 CSV 文件df.to_csv(CSV_FILE, index=False, encoding='utf-8')logger.debug(f'数据已成功添加到 CSV 文件: {new_row}')flash('数据添加成功')except ValueError as ve:logger.error(f'数据类型错误: {ve}')flash(f'数据类型错误: {ve}')except Exception as e:logger.error(f'添加数据时出错: {e}')flash(f'添加数据时出错: {e}')return redirect(url_for('index'))@app.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit_data(id):try:df = pd.read_csv(CSV_FILE)if request.method == 'POST':edited_row = {'日期': request.form['日期'],'每日涨停数': int(request.form['每日涨停数']),'每日交易量(万亿)': float(request.form['每日交易量(万亿)']),'上涨比率': float(request.form['上涨比率']),'最高连板': int(request.form['最高连板']),'最高板大面数': int(request.form['最高板大面数']),'其他': request.form['其他']}df.loc[id] = edited_rowdf.to_csv(CSV_FILE, index=False, encoding='utf-8')flash('数据编辑成功')return redirect(url_for('index'))else:row = df.iloc[id].to_dict()return render_template('edit.html', row=row, id=id)except Exception as e:logger.error(f'编辑数据时出错: {e}')flash(f'编辑数据时出错: {e}')return redirect(url_for('index'))if __name__ == '__main__':app.run(debug=True)