diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..5532b85a7 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +venv/ +__pycache__/ +.git/ +.env +*.pyc diff --git a/Dockerfile b/Dockerfile index d68b868d6..92d29d79d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,15 @@ -FROM python:3.12-slim +FROM python:3.12 -# Ваш код здесь # +WORKDIR /app -# Запускаем приложение с помощью uvicorn, делая его доступным по сети -CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "5000"] \ No newline at end of file +# 1. Сначала копируем файл с зависимостями +COPY requirements.txt . + +# 2. Устанавливаем зависимости +RUN pip install --no-cache-dir -r requirements.txt + +# 3. Копируем остальной код приложения +COPY . . + +# Команда запуска (пример, может отличаться у вас) +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "5000"] diff --git a/Dockerfile.python b/Dockerfile.python new file mode 100644 index 000000000..3b8a083aa --- /dev/null +++ b/Dockerfile.python @@ -0,0 +1,12 @@ +FROM python:3.12-slim + +WORKDIR /app + +COPY requirements.txt . + +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +# Запускаем приложение с помощью uvicorn, делая его доступным по сети +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "5000"] diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 000000000..3896d8254 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,42 @@ +include: + - proxy.yaml + +services: + db: + image: mysql:8 + restart: always + env_file: + - .env + environment: + MYSQL_DATABASE: ${MYSQL_DATABASE} + MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} + MYSQL_USER: ${MYSQL_USER} + MYSQL_PASSWORD: ${MYSQL_PASSWORD} + networks: + backend: + ipv4_address: 172.20.0.10 + + web: + build: + context: . + dockerfile: Dockerfile.python + restart: on-failure + env_file: + - .env + environment: + DB_HOST: db + DB_USER: ${MYSQL_USER} + DB_PASSWORD: ${MYSQL_PASSWORD} + DB_NAME: ${MYSQL_DATABASE} + networks: + backend: + ipv4_address: 172.20.0.5 + depends_on: + - db + +networks: + backend: + driver: bridge + ipam: + config: + - subnet: 172.20.0.0/24 diff --git a/dockerignore b/dockerignore new file mode 100644 index 000000000..c13c3d2b7 --- /dev/null +++ b/dockerignore @@ -0,0 +1,19 @@ +.git +.gitignore +__pycache__/ +*.pyc +*.pyo +*.pyd +.pytest_cache/ +.mypy_cache/ +.venv/ +venv/ +.env +.env.* +dist/ +build/ +*.egg-info/ +.idea/ +.vscode/ +Dockerfile* +docker-compose*.yml diff --git a/main.py b/main.py index 15f567555..c25ffdcbe 100644 --- a/main.py +++ b/main.py @@ -14,6 +14,10 @@ db_password = os.environ.get('DB_PASSWORD', 'very_strong') db_name = os.environ.get('DB_NAME', 'example') +# ### <--- ИЗМЕНЕНО: Добавляем чтение имени таблицы из ENV +table_name = os.environ.get('TABLE_NAME', 'requests') + + @asynccontextmanager async def lifespan(app: FastAPI): # Код, который выполнится перед запуском приложения @@ -21,8 +25,9 @@ async def lifespan(app: FastAPI): try: with get_db_connection() as db: cursor = db.cursor() + # ### <--- ИЗМЕНЕНО: Используем переменную table_name при создании create_table_query = f""" - CREATE TABLE IF NOT EXISTS {db_name}.requests ( + CREATE TABLE IF NOT EXISTS {db_name}.{table_name} ( id INT AUTO_INCREMENT PRIMARY KEY, request_date DATETIME, request_ip VARCHAR(255) @@ -30,7 +35,8 @@ async def lifespan(app: FastAPI): """ cursor.execute(create_table_query) db.commit() - print("Соединение с БД установлено и таблица 'requests' готова к работе.") + # ### <--- ИЗМЕНЕНО: Вывод в лог актуального имени таблицы + print(f"Соединение с БД установлено и таблица '{table_name}' готова к работе.") cursor.close() except mysql.connector.Error as err: print(f"Ошибка при подключении к БД или создании таблицы: {err}") @@ -83,7 +89,8 @@ def index(request: Request, ip_address: Optional[str] = Depends(get_client_ip)): try: with get_db_connection() as db: cursor = db.cursor() - query = "INSERT INTO requests (request_date, request_ip) VALUES (%s, %s)" + # ### <--- ИЗМЕНЕНО: Используем переменную table_name при вставке + query = f"INSERT INTO {table_name} (request_date, request_ip) VALUES (%s, %s)" values = (current_time, final_ip) cursor.execute(query, values) db.commit() @@ -120,7 +127,8 @@ def get_requests(): try: with get_db_connection() as db: cursor = db.cursor() - query = "SELECT id, request_date, request_ip FROM requests ORDER BY id DESC LIMIT 50" + # ### <--- ИЗМЕНЕНО: Используем переменную table_name при выборке + query = f"SELECT id, request_date, request_ip FROM {table_name} ORDER BY id DESC LIMIT 50" cursor.execute(query) records = cursor.fetchall() cursor.close()