Skip to content
Open

1 #9

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
venv/
__pycache__/
.git/
.env
*.pyc
17 changes: 13 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -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"]
# 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"]
12 changes: 12 additions & 0 deletions Dockerfile.python
Original file line number Diff line number Diff line change
@@ -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"]
42 changes: 42 additions & 0 deletions compose.yaml
Original file line number Diff line number Diff line change
@@ -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
19 changes: 19 additions & 0 deletions dockerignore
Original file line number Diff line number Diff line change
@@ -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
16 changes: 12 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,29 @@
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):
# Код, который выполнится перед запуском приложения
print("Приложение запускается...")
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)
)
"""
cursor.execute(create_table_query)
db.commit()
print("Соединение с БД установлено и таблица 'requests' готова к работе.")
# ### <--- ИЗМЕНЕНО: Вывод в лог актуального имени таблицы
print(f"Соединение с БД установлено и таблица '{table_name}' готова к работе.")
cursor.close()
except mysql.connector.Error as err:
print(f"Ошибка при подключении к БД или создании таблицы: {err}")
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down