Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
@@ -114,6 +114,7 @@ def setup_routes(app: FastAPI) -> None:
|
|||||||
async def download_all(dates: DownloadRange, background_tasks: BackgroundTasks):
|
async def download_all(dates: DownloadRange, background_tasks: BackgroundTasks):
|
||||||
date_start = dates.data_start
|
date_start = dates.data_start
|
||||||
date_finish = dates.data_finish
|
date_finish = dates.data_finish
|
||||||
|
field_name = getattr(dates, 'field_name', 'status') # Поле для фильтрации (по умолчанию 'status')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
start_date = datetime.strptime(date_start, "%Y-%m-%d")
|
start_date = datetime.strptime(date_start, "%Y-%m-%d")
|
||||||
@@ -124,8 +125,17 @@ def setup_routes(app: FastAPI) -> None:
|
|||||||
if start_date > finish_date:
|
if start_date > finish_date:
|
||||||
return {"error": "Дата начала не может быть позже даты окончания"}
|
return {"error": "Дата начала не может быть позже даты окончания"}
|
||||||
|
|
||||||
all_files = []
|
# 1. Получаем список заголовков из БД
|
||||||
|
try:
|
||||||
|
titles_from_db = wp.get_articles_by_filter(field_name, date_start, date_finish)
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": f"Ошибка при получении данных из БД: {e}"}
|
||||||
|
|
||||||
|
if not titles_from_db:
|
||||||
|
return {"error": "Нет статей с выбранным фильтром за указанный период", "field_name": field_name}
|
||||||
|
|
||||||
|
# 2. Собираем все файлы .docx за период
|
||||||
|
all_files = []
|
||||||
current_date = start_date
|
current_date = start_date
|
||||||
while current_date <= finish_date:
|
while current_date <= finish_date:
|
||||||
date_path = current_date.strftime("%Y/%m/%d")
|
date_path = current_date.strftime("%Y/%m/%d")
|
||||||
@@ -134,12 +144,18 @@ def setup_routes(app: FastAPI) -> None:
|
|||||||
if os.path.exists(full_dir_path):
|
if os.path.exists(full_dir_path):
|
||||||
for file in os.listdir(full_dir_path):
|
for file in os.listdir(full_dir_path):
|
||||||
if file.endswith('.docx'):
|
if file.endswith('.docx'):
|
||||||
|
# 3. Фильтруем: добавляем только если название файла совпадает с заголовком из БД
|
||||||
|
file_title = file[:-5] # убираем расширение .docx
|
||||||
|
if file_title in titles_from_db:
|
||||||
all_files.append(os.path.join(full_dir_path, file))
|
all_files.append(os.path.join(full_dir_path, file))
|
||||||
|
|
||||||
current_date += timedelta(days=1)
|
current_date += timedelta(days=1)
|
||||||
|
|
||||||
if not all_files:
|
if not all_files:
|
||||||
return {"error": "Файлы не найдены за указанный период", "date_start": date_start, "date_finish": date_finish}
|
return {"error": "Файлы не найдены за указанный период",
|
||||||
|
"date_start": date_start,
|
||||||
|
"date_finish": date_finish,
|
||||||
|
"titles_found": len(titles_from_db)}
|
||||||
|
|
||||||
archive_name = f"documents_{date_start}_{date_finish}.zip"
|
archive_name = f"documents_{date_start}_{date_finish}.zip"
|
||||||
archive_path = os.path.join(DOCUMENTS_DIR, archive_name)
|
archive_path = os.path.join(DOCUMENTS_DIR, archive_name)
|
||||||
|
|||||||
@@ -31,3 +31,4 @@ class DownloadRange(BaseModel):
|
|||||||
"""Диапазон дат для скачивания файлов"""
|
"""Диапазон дат для скачивания файлов"""
|
||||||
data_start: str
|
data_start: str
|
||||||
data_finish: str
|
data_finish: str
|
||||||
|
field_name: str = "status"
|
||||||
|
|||||||
@@ -66,6 +66,38 @@ def save_parsed_data_to_db(data: ParsedData):
|
|||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
def get_articles_by_filter(field_name: str, start_date: str, finish_date: str):
|
||||||
|
"""
|
||||||
|
Возвращает список заголовков статей по полю и диапазону дат
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field_name: имя поля (tematik, svodka, donesenie, bilutene, status)
|
||||||
|
start_date: дата начала в формате YYYY-MM-DD
|
||||||
|
finish_date: дата окончания в формате YYYY-MM-DD
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List[str]: список заголовков (title)
|
||||||
|
"""
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
# Проверка валидности поля
|
||||||
|
allowed_fields = ['tematik', 'svodka', 'donesenie', 'bilutene', 'status']
|
||||||
|
if field_name not in allowed_fields:
|
||||||
|
raise ValueError(f"Недопустимое поле: {field_name}. Разрешено: {allowed_fields}")
|
||||||
|
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(f"""
|
||||||
|
SELECT title FROM url
|
||||||
|
WHERE {field_name} = TRUE
|
||||||
|
AND article_date BETWEEN %s AND %s
|
||||||
|
ORDER BY article_date DESC;
|
||||||
|
""", (start_date, finish_date))
|
||||||
|
|
||||||
|
rows = cur.fetchall()
|
||||||
|
return [row['title'] for row in rows]
|
||||||
|
finally:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
# Глобальное подключение к БД
|
# Глобальное подключение к БД
|
||||||
conn = None
|
conn = None
|
||||||
|
|||||||
Reference in New Issue
Block a user