refactor: use tempfile for import/export/stats artifacts

This commit is contained in:
Xiaolan Bot
2026-02-22 01:48:44 +08:00
parent 8601e78e17
commit 15f9ceb841

View File

@@ -4,6 +4,7 @@ import requests
import datetime import datetime
import dateparser import dateparser
import logging import logging
import tempfile
import pandas as pd import pandas as pd
import matplotlib import matplotlib
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
@@ -458,7 +459,8 @@ async def stats(update: Update, context: CallbackContext):
ax.axis('equal') ax.axis('equal')
fig.tight_layout() fig.tight_layout()
image_path = f'stats_{user_id}.png' with tempfile.NamedTemporaryFile(prefix=f'stats_{user_id}_', suffix='.png', delete=False) as tmp:
image_path = tmp.name
plt.savefig(image_path) plt.savefig(image_path)
plt.close(fig) plt.close(fig)
@@ -481,7 +483,9 @@ async def export_command(update: Update, context: CallbackContext):
await update.message.reply_text("您还没有任何订阅数据,无法导出。") await update.message.reply_text("您还没有任何订阅数据,无法导出。")
return return
export_path = f'export_{user_id}.csv' with tempfile.NamedTemporaryFile(prefix=f'export_{user_id}_', suffix='.csv', delete=False) as tmp:
export_path = tmp.name
df.to_csv(export_path, index=False, encoding='utf-8-sig') df.to_csv(export_path, index=False, encoding='utf-8-sig')
try: try:
@@ -506,7 +510,8 @@ async def import_upload_received(update: Update, context: CallbackContext):
return IMPORT_UPLOAD return IMPORT_UPLOAD
file = await update.message.document.get_file() file = await update.message.document.get_file()
file_path = f'import_{user_id}.csv' with tempfile.NamedTemporaryFile(prefix=f'import_{user_id}_', suffix='.csv', delete=False) as tmp:
file_path = tmp.name
try: try:
await file.download_to_drive(file_path) await file.download_to_drive(file_path)
df = pd.read_csv(file_path, encoding='utf-8-sig') df = pd.read_csv(file_path, encoding='utf-8-sig')