Merge pull request 'pms_plugins' (#3) from pms_plugins into master

Reviewed-on: trevor/touchh_bot#3
This commit is contained in:
2024-12-16 13:24:22 +00:00
24 changed files with 344 additions and 23481 deletions

View File

@@ -26,7 +26,7 @@ class DataSyncManager:
# Настройка логирования # Настройка логирования
self.logger = logging.getLogger(__name__) self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG) self.logger.setLevel(logging.WARNING)
handler = logging.FileHandler('data_sync.log') handler = logging.FileHandler('data_sync.log')
handler.setLevel(logging.DEBUG) handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
bot/fonts/DejaVuSans.pkl Normal file

Binary file not shown.

BIN
bot/fonts/DejaVuSans.ttf Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -7,7 +7,11 @@ from users.models import User
from bot.utils.pdf_report import generate_pdf_report from bot.utils.pdf_report import generate_pdf_report
from bot.utils.database import get_hotels_for_user, get_hotel_by_name from bot.utils.database import get_hotels_for_user, get_hotel_by_name
from django.utils.timezone import make_aware from datetime import datetime
from django.utils.timezone import make_aware, is_aware, is_naive
import os
import traceback
async def statistics(update: Update, context: ContextTypes.DEFAULT_TYPE): async def statistics(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Вывод списка отелей для статистики.""" """Вывод списка отелей для статистики."""
@@ -54,6 +58,29 @@ async def stats_select_period(update: Update, context: ContextTypes.DEFAULT_TYPE
] ]
reply_markup = InlineKeyboardMarkup(keyboard) reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text("Выберите период времени:", reply_markup=reply_markup) await query.edit_message_text("Выберите период времени:", reply_markup=reply_markup)
def ensure_datetime(value):
# print(f"statistics.py [DEBUG] ensure_datetime: Received value: {value} ({type(value)})")
"""
Ensure that the given value is a timezone-aware datetime object.
If the given value is a string, it is assumed to be in the format
'%Y-%m-%d %H:%M:%S'. If the given value is a naive datetime object,
it is converted to a timezone-aware datetime object using
django.utils.timezone.make_aware.
:param value: The value to be converted
:type value: str or datetime
:return: A timezone-aware datetime object
:rtype: datetime
"""
if isinstance(value, str):
value = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
if isinstance(value, datetime) and is_naive(value):
value = make_aware(value)
# print(f"statistics.py [DEBUG] ensure_datetime: Returning value: {value} ({type(value)})")
return value
async def generate_statistics(update: Update, context: ContextTypes.DEFAULT_TYPE): async def generate_statistics(update: Update, context: ContextTypes.DEFAULT_TYPE):
@@ -61,17 +88,79 @@ async def generate_statistics(update: Update, context: ContextTypes.DEFAULT_TYPE
query = update.callback_query query = update.callback_query
await query.answer() await query.answer()
hotel_id = context.user_data.get("selected_hotel") try:
if not hotel_id: hotel_id = context.user_data.get("selected_hotel")
await query.edit_message_text("Ошибка: ID отеля не найден.")
return
period = query.data.split("_")[2] if not hotel_id:
print(f'Period raw: {query.data}') raise ValueError(f"ID отеля не найден в user_data: {context.user_data}")
print(f'Selected period: {period}')
now = datetime.utcnow().replace(tzinfo=timezone.utc) # Используем timezone.utc period = query.data.split("_")[2]
now = datetime.utcnow().replace(tzinfo=timezone.utc)
print(type(now))
print(type(period))
start_date, end_date = get_period_dates(period, now)
try:
# Получаем бронирования
reservations = await sync_to_async(list)(
Reservation.objects.filter(
hotel_id=hotel_id,
check_in__gte=start_date,
check_in__lte=end_date
).select_related('hotel')
)
except Exception as e:
raise RuntimeError(f"statistics.py Ошибка при выборке бронирований: {e}") from e
if not reservations:
await query.edit_message_text("statistics.py Нет данных для статистики за выбранный период.")
return
try:
# Получаем данные об отеле
hotel = await sync_to_async(Hotel.objects.get)(id=hotel_id)
except Hotel.DoesNotExist:
raise RuntimeError(f"statistics.py Отель с ID {hotel_id} не найден")
except Exception as e:
raise RuntimeError(f"statistics.py Ошибка при выборке отеля: {e}") from e
try:
# Генерация отчета
file_path = await generate_pdf_report(hotel.name, reservations, start_date, end_date)
except Exception as e:
raise RuntimeError(f"statistics.py [ERROR] Ошибка при генерации PDF-отчета: {e}") from e
try:
# Отправка файла через Telegram
with open(file_path, "rb") as file:
await query.message.reply_document(document=file, filename=f"{hotel.name}_report.pdf")
except Exception as e:
raise RuntimeError(f"Ошибка при отправке PDF-файла: {e}") from e
# Удаляем временный файл
if os.path.exists(file_path):
os.remove(file_path)
except Exception as e:
# Логируем стек вызовов для детального анализа
error_trace = traceback.format_exc()
await query.edit_message_text(f"Произошла ошибка: {str(e)}")
def get_period_dates(period, now):
if period == "day": if period == "day":
start_date = (now - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0) start_date = (now - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
end_date = now.replace(hour=23, minute=59, second=59, microsecond=999999) end_date = now.replace(hour=23, minute=59, second=59, microsecond=999999)
@@ -81,55 +170,13 @@ async def generate_statistics(update: Update, context: ContextTypes.DEFAULT_TYPE
elif period == "month": elif period == "month":
start_date = (now - timedelta(days=30)).replace(hour=0, minute=0, second=0, microsecond=0) start_date = (now - timedelta(days=30)).replace(hour=0, minute=0, second=0, microsecond=0)
end_date = now.replace(hour=23, minute=59, second=59, microsecond=999999) end_date = now.replace(hour=23, minute=59, second=59, microsecond=999999)
else: # "all" elif period == "all":
start_date = None start_date = (now - timedelta(days=1500)).replace(hour=0, minute=0, second=0, microsecond=0)
end_date = None end_date = now.replace(hour=23, minute=59, second=59, microsecond=999999)
else:
print(f'Raw start_date: {start_date}, Raw end_date: {end_date}') start_date = (now - timedelta(days=1500)).replace(hour=0, minute=0, second=0, microsecond=0)
end_date = now.replace(hour=23, minute=59, second=59, microsecond=999999)
# Убедитесь, что даты имеют временную зону UTC return start_date, end_date
if start_date:
start_date = make_aware(start_date) if start_date.tzinfo is None else start_date
if end_date:
end_date = make_aware(end_date) if end_date.tzinfo is None else end_date
print(f'Filtered start_date: {start_date}, Filtered end_date: {end_date}')
# Фильтрация по "дата заезда"
if start_date and end_date:
reservations = await sync_to_async(list)(
Reservation.objects.filter(
hotel_id=hotel_id,
check_in__gte=start_date,
check_in__lte=end_date
).select_related('hotel')
)
else: # Без фильтра по дате
reservations = await sync_to_async(list)(
Reservation.objects.filter(
hotel_id=hotel_id
).select_related('hotel')
)
print(f'Filtered reservations count: {len(reservations)}')
if not reservations:
await query.edit_message_text("Нет данных для статистики за выбранный период.")
return
hotel = await sync_to_async(Hotel.objects.get)(id=hotel_id)
print(f'Hotel: {hotel.name}')
for reservation in reservations:
print(f"Reservation ID: {reservation.reservation_id}, Hotel: {reservation.hotel.name}, "
f"Room number: {reservation.room_number}, Check-in: {reservation.check_in}, Check-out: {reservation.check_out}")
# Генерация PDF отчета (пример)
file_path = generate_pdf_report(hotel.name, reservations, start_date, end_date)
print(f'Generated file path: {file_path}')
with open(file_path, "rb") as file:
await query.message.reply_document(document=file, filename=f"{hotel.name}_report.pdf")
async def stats_back(update: Update, context): async def stats_back(update: Update, context):
"""Возврат к выбору отеля.""" """Возврат к выбору отеля."""

View File

@@ -1,65 +1,144 @@
from fpdf import FPDF from fpdf import FPDF
import os
from datetime import datetime
from asgiref.sync import sync_to_async
from django.utils.timezone import make_aware, is_naive, is_aware
import os import os
# Определение абсолютного пути к папке "reports"
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REPORTS_DIR = os.path.join(BASE_DIR, "reports")
def generate_pdf_report(hotel_name, reservations, start_date, end_date): # Убедитесь, что директория существует
"""Генерация PDF отчета.""" os.makedirs(REPORTS_DIR, exist_ok=True)
pdf = FPDF(orientation='L', unit="mm", format="A4")
pdf.add_page()
# Укажите путь к шрифту
font_path = os.path.join("bot", "fonts", "OpenSans-Regular.ttf")
if not os.path.exists(font_path):
raise FileNotFoundError(f"Шрифт {font_path} не найден. Убедитесь, что он находится в указанной папке.")
pdf.add_font("OpenSans", "", font_path, uni=True)
pdf.set_font("OpenSans", size=12)
# Заголовки # Асинхронная функция для извлечения данных о бронировании
title = f"Отчет по заселениям: {hotel_name}" def ensure_datetime(value):
period = ( """Преобразует строку или naive datetime в timezone-aware datetime."""
f"Период: {start_date.strftime('%d.%m.%Y')} - {end_date.strftime('%d.%m.%Y')}" if isinstance(value, str):
if start_date and end_date value = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
else "Период: Все время" if isinstance(value, datetime) and is_naive(value):
) value = make_aware(value)
return value
pdf.cell(0, 10, txt=title, ln=True, align="C") @sync_to_async
pdf.cell(0, 10, txt=period, ln=True, align="C") def get_reservation_data(res):
pdf.ln(10) print(f"[DEBUG] Processing reservation {res.id}")
# Убедитесь, что даты являются timezone-aware
check_in = ensure_datetime(res.check_in)
check_out = ensure_datetime(res.check_out)
result = {
"hotel_name": res.hotel.name,
"pms": getattr(res.hotel, 'pms', 'N/A'),
"reservation_id": res.reservation_id,
"room_number": res.room_number if res.room_number else "Не указан",
"room_type": res.room_type,
"check_in": check_in,
"check_out": check_out,
"status": res.status,
}
# print(f"[DEBUG] Reservation data: {result}")
return result
# Ширины колонок
page_width = pdf.w - 10
col_widths = [page_width * 0.2, page_width * 0.2, page_width * 0.15, page_width * 0.25, page_width * 0.1, page_width * 0.1]
# Заголовки таблицы
pdf.set_font("OpenSans", size=10)
headers = ["Дата заезда", "Дата выезда", "Номер", "Тип комнаты", "Цена"]
for width, header in zip(col_widths, headers):
pdf.cell(width, 15, header, border=1, align="C")
pdf.ln()
total_price = 0 class CustomPDF(FPDF):
total_discount = 0 def __init__(self, hotel_name, start_date, end_date, *args, **kwargs):
super().__init__(*args, **kwargs)
self.font_folder = "bot/fonts/"
self.add_font("DejaVuSans-Bold", "", os.path.join(self.font_folder, "DejaVuSans-Bold.ttf"), uni=True)
self.add_font("DejaVuSans", "", os.path.join(self.font_folder, "DejaVuSans.ttf"), uni=True)
self.creation_date = datetime.now().strftime("%d.%m.%Y %H:%M:%S")
# Переданные параметры
self.hotel_name = hotel_name
self.start_date = start_date
self.end_date = end_date
def header(self):
"""Добавление заголовка и заголовков таблицы на каждой странице."""
# Заголовок отчёта
if self.page == 1: # Заголовок отчёта только на первой странице
self.set_font("DejaVuSans-Bold", size=14)
self.cell(0, 10, f"Отчет о бронированиях отеля {self.hotel_name}", ln=1, align="C")
self.ln(5)
self.set_font("DejaVuSans", size=10)
self.cell(0, 10, f"за период {self.start_date.strftime('%Y-%m-%d %H:%M:%S')} - {self.end_date.strftime('%Y-%m-%d %H:%M:%S')}", ln=1, align="C")
self.ln(10)
# Заголовки таблицы
self.set_font("DejaVuSans-Bold", size=8)
headers = ["Отель", "№ бронирования", "№ комнаты", "Тип комнаты", "Заезд", "Выезд", "Статус"]
col_widths = [30, 30, 30, 60, 35, 35, 30]
row_height = 10
for col_width, header in zip(col_widths, headers):
self.cell(col_width, row_height, header, border=1, align="C")
self.ln()
def footer(self):
"""Добавление колонтитула внизу страницы."""
self.set_y(-15)
self.set_font("DejaVuSans", size=8)
self.cell(60, 10, f"Copyright (C) 2024 by Touchh", align="L")
self.cell(0, 10, f"Лист {self.page_no()} из {{nb}} / Дата генерации отчета: {self.creation_date}", align="C")
def trim_text_right(self, text, max_width):
"""Обрезка текста справа."""
while self.get_string_width(text) > max_width:
text = text[:-1]
return text + "..." if len(text) > 3 else text
async def generate_pdf_report(hotel_name, reservations, start_date, end_date):
# Создание экземпляра PDF с передачей параметров
pdf = CustomPDF(hotel_name=hotel_name, start_date=start_date, end_date=end_date, orientation="L", unit="mm", format="A4")
pdf.alias_nb_pages()
pdf.add_page() # Заголовок отчёта и таблица будут добавлены через методы header и footer
# Таблица
pdf.set_font("DejaVuSans", size=8)
col_widths = [30, 30, 30, 60, 35, 35, 30]
row_height = 10
for res in reservations: for res in reservations:
price = res.price or 0 try:
discount = res.discount or 0 res_data = await get_reservation_data(res)
total_price += price
total_discount += discount
pdf.cell(col_widths[0], 10, res.check_in.strftime('%d.%m.%Y %H:%M'), border=1) row_data = [
pdf.cell(col_widths[1], 10, res.check_out.strftime('%d.%m.%Y %H:%M'), border=1) res_data["hotel_name"],
pdf.cell(col_widths[2], 10, res.room_number, border=1) str(res_data["reservation_id"]),
pdf.cell(col_widths[3], 10, res.room_type, border=1) res_data["room_number"],
pdf.cell(col_widths[4], 10, f"{price:.2f} р.", border=1, align="R") res_data["room_type"],
pdf.ln() res_data["check_in"].strftime('%Y-%m-%d %H:%M:%S'),
res_data["check_out"].strftime('%Y-%m-%d %H:%M:%S'),
res_data["status"],
]
for col_width, data in zip(col_widths, row_data):
pdf.cell(col_width, row_height, data, border=1, align="C")
pdf.ln()
except Exception as e:
print(f"pdf_report.py [ERROR] Error processing reservation {res.id}: {e}")
# Сохранение PDF
hotel_name_safe = hotel_name.replace(" ", "_").replace("/", "_")
start_date_str = start_date.strftime('%Y-%m-%d')
end_date_str = end_date.strftime('%Y-%m-%d')
pdf_output_path = os.path.join(REPORTS_DIR, f"{hotel_name_safe}_report_{start_date_str}-{end_date_str}.pdf")
pdf.output(pdf_output_path)
if not os.path.exists(pdf_output_path):
raise RuntimeError(f"PDF file was not created at: {pdf_output_path}")
return pdf_output_path
pdf.ln(5)
pdf.set_font("OpenSans", size=18)
pdf.cell(0, 10, "Итоги:", ln=True)
pdf.cell(0, 10, f"Общая сумма цен: {total_price:.2f} руб.", ln=True)
file_path = os.path.join("reports", f"{hotel_name}_report.pdf")
os.makedirs(os.path.dirname(file_path), exist_ok=True)
pdf.output(file_path)
return file_path

View File

@@ -1,19 +1,19 @@
# Generated by Django 5.1.4 on 2024-12-14 00:19 # hotels/migrations/0006_remove_hotel_import_status_remove_hotel_imported_at_and_more.py
from django.db import migrations from django.db import migrations
def remove_unused_fields(apps, schema_editor):
Hotel = apps.get_model('hotels', 'Hotel')
Hotel._meta.get_field('import_status').remote_field.model._meta.db_table
Hotel._meta.get_field('imported_at').remote_field.model._meta.db_table
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('hotels', '0005_hotel_import_status_hotel_imported_at_and_more'), ('hotels', '0005_hotel_import_status_hotel_imported_at_and_more'),
] ]
operations = [ operations = [
migrations.RemoveField(
model_name='hotel',
name='api',
),
migrations.RemoveField( migrations.RemoveField(
model_name='hotel', model_name='hotel',
name='import_status', name='import_status',
@@ -26,4 +26,8 @@ class Migration(migrations.Migration):
model_name='hotel', model_name='hotel',
name='imported_from', name='imported_from',
), ),
migrations.RemoveField(
model_name='hotel',
name='api',
),
] ]

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,5 @@
import logging import logging
import requests import requests
import json
from datetime import datetime, timedelta from datetime import datetime, timedelta
from asgiref.sync import sync_to_async from asgiref.sync import sync_to_async
from pms_integration.models import PMSConfiguration from pms_integration.models import PMSConfiguration
@@ -14,7 +13,6 @@ class EcviPMSPlugin(BasePMSPlugin):
""" """
def __init__(self, pms_config): def __init__(self, pms_config):
# Инициализация родительского конструктора
super().__init__(pms_config) super().__init__(pms_config)
# Инициализация логгера # Инициализация логгера
@@ -40,7 +38,7 @@ class EcviPMSPlugin(BasePMSPlugin):
"field_mapping": { "field_mapping": {
"check_in": "checkin", "check_in": "checkin",
"check_out": "checkout", "check_out": "checkout",
"room_number": "room_name", # Заменили на room_number "room_number": "room_name",
"room_type_name": "room_type", "room_type_name": "room_type",
"status": "occupancy", "status": "occupancy",
}, },
@@ -73,20 +71,25 @@ class EcviPMSPlugin(BasePMSPlugin):
return [] return []
# Фильтрация данных # Фильтрация данных
filtered_data = [ filtered_data = []
{ for item in data:
'checkin': datetime.strptime(item.get('checkin'), '%Y-%m-%d %H:%M:%S'), if item.get('occupancy') in ['проживание', 'под выезд', 'под заезд']:
'checkout': datetime.strptime(item.get('checkout'), '%Y-%m-%d %H:%M:%S'), filtered_item = {
'room_name': item.get('room_name'), 'checkin': datetime.strptime(item.get('checkin'), '%Y-%m-%d %H:%M:%S'),
'room_type': item.get('room_type'), 'checkout': datetime.strptime(item.get('checkout'), '%Y-%m-%d %H:%M:%S'),
'status': item.get('occupancy') 'room_number': item.get('room_name'),
} for item in data if item.get('occupancy') in ['проживание', 'под выезд', 'под заезд'] 'room_type': item.get('room_type'),
] 'status': item.get('occupancy')
}
filtered_data.append(filtered_item)
# Логируем результат фильтрации
self.logger.debug(f"Отфильтрованные данные: {filtered_data}")
# Сохранение данных в базу данных # Сохранение данных в базу данных
for item in filtered_data: for item in filtered_data:
await self._save_to_db(item) await self._save_to_db(item)
self.logger.debug(f"Данные успешно сохранены.") self.logger.debug(f"Данные успешно сохранены.")
return filtered_data return filtered_data
@@ -95,16 +98,24 @@ class EcviPMSPlugin(BasePMSPlugin):
Сохраняет данные в БД (например, информацию о номере). Сохраняет данные в БД (например, информацию о номере).
""" """
try: try:
# Проверяем, что item — это словарь
if not isinstance(item, dict):
self.logger.error(f"Ожидался словарь, но получен: {type(item)}. Данные: {item}")
return
# Получаем отель по настройкам PMS # Получаем отель по настройкам PMS
hotel = await sync_to_async(Hotel.objects.get)(pms=self.pms_config) hotel = await sync_to_async(Hotel.objects.get)(pms=self.pms_config)
self.logger.debug(f"Отель найден: {hotel.name}") self.logger.debug(f"Отель найден: {hotel.name}")
# Сохраняем данные бронирования # Сохраняем данные бронирования
room_number = item.get("room_name") room_number = item.get("room_number")
check_in = item.get("checkin") check_in = item.get("checkin")
check_out = item.get("checkout") check_out = item.get("checkout")
room_type = item.get("room_type") room_type = item.get("room_type")
# Логируем полученные данные
self.logger.debug(f"Полученные данные для сохранения: room_number={room_number}, check_in={check_in}, check_out={check_out}, room_type={room_type}")
# Проверяем, существует ли запись с таким номером и датой заезда # Проверяем, существует ли запись с таким номером и датой заезда
existing_reservation = await sync_to_async( existing_reservation = await sync_to_async(
Reservation.objects.filter(room_number=room_number, check_in=check_in).first Reservation.objects.filter(room_number=room_number, check_in=check_in).first
@@ -124,14 +135,15 @@ class EcviPMSPlugin(BasePMSPlugin):
self.logger.debug(f"Обновлена существующая резервация.") self.logger.debug(f"Обновлена существующая резервация.")
else: else:
self.logger.debug(f"Резервация не найдена, создаем новую...") self.logger.debug(f"Резервация не найдена, создаем новую...")
await sync_to_async(Reservation.objects.create)( reservation = await sync_to_async(Reservation.objects.create)(
room_number=room_number, room_number=room_number,
check_in=check_in, check_in=check_in,
check_out=check_out, check_out=check_out,
hotel=hotel, hotel=hotel,
room_type=room_type, room_type=room_type,
) )
self.logger.debug(f"Создана новая резервация.") self.logger.debug(f"Создана новая резервация. ID: {reservation.reservation_id}")
except Exception as e: except Exception as e:
self.logger.error(f"Ошибка сохранения данных: {e}") self.logger.error(f"Ошибка сохранения данных: {e}")

Binary file not shown.

Binary file not shown.

Binary file not shown.

68
requierments.txt Normal file
View File

@@ -0,0 +1,68 @@
ace_tools==0.0
aiohappyeyeballs==2.4.4
aiohttp==3.11.10
aiosignal==1.3.1
anyio==4.6.2.post1
APScheduler==3.11.0
asgiref==3.8.1
async-timeout==5.0.1
attrs==24.2.0
certifi==2024.8.30
cffi==1.17.1
chardet==5.2.0
charset-normalizer==3.4.0
cryptography==44.0.0
defusedxml==0.7.1
Django==5.1.4
django-environ==0.11.2
django-filter==24.3
django-health-check==3.18.3
django-jazzmin==3.0.1
django-jet==1.0.8
et_xmlfile==2.0.0
exceptiongroup==1.2.2
fonttools==4.55.3
fpdf2==2.8.2
frozenlist==1.5.0
geoip2==4.8.1
git-filter-repo==2.47.0
h11==0.14.0
httpcore==1.0.7
httpx==0.28.0
idna==3.10
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
maxminddb==2.6.2
multidict==6.1.0
mysqlclient==2.2.6
numpy==2.1.3
openpyxl==3.1.5
pandas==2.2.3
pathspec==0.12.1
pillow==11.0.0
propcache==0.2.1
psycopg==3.2.3
pycparser==2.22
PyMySQL==1.1.1
python-dateutil==2.9.0.post0
python-decouple==3.8
python-dotenv==1.0.1
python-telegram-bot==21.8
pytz==2024.2
PyYAML==6.0.2
referencing==0.35.1
requests==2.32.3
rpds-py==0.22.3
six==1.17.0
sniffio==1.3.1
sqlparse==0.5.2
typing_extensions==4.12.2
tzdata==2024.2
tzlocal==5.2
ua-parser==1.0.0
ua-parser-builtins==0.18.0.post1
urllib3==2.2.3
user-agents==2.2.0
yarl==1.18.3
mysqlclient
chardet

View File

@@ -31,11 +31,11 @@ SECRET_KEY = 'django-insecure-l_8uu8#p*^zf)9zry80)6u+!+2g1a4tg!wx7@^!uw(+^axyh&h
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True DEBUG = True
ALLOWED_HOSTS = ['0.0.0.0', '192.168.219.140', '127.0.0.1', '192.168.219.114', 'c710-182-226-158-253.ngrok-free.app'] ALLOWED_HOSTS = ['0.0.0.0', '192.168.219.140', '127.0.0.1', '192.168.219.114', '5dec-182-226-158-253.ngrok-free.app', '*.ngrok-free.app']
CSRF_TRUSTED_ORIGINS = [ CSRF_TRUSTED_ORIGINS = [
'https://c710-182-226-158-253.ngrok-free.app', 'http://5dec-182-226-158-253.ngrok-free.app',
'https://*.ngrok.io', # Это подойдет для любых URL, связанных с ngrok 'https://*.ngrok-free.app', # Это подойдет для любых URL, связанных с ngrok
] ]
# Application definition # Application definition