refactor: split into two stacks - searchFilms/ (NL) and app/ (RU)
This commit is contained in:
parent
6ef3a10d0d
commit
51348a9d23
36 changed files with 326 additions and 1271 deletions
19
searchFilms/tmdb-proxy/Dockerfile
Normal file
19
searchFilms/tmdb-proxy/Dockerfile
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Копируем requirements
|
||||
COPY requirements.txt .
|
||||
|
||||
# Устанавливаем зависимости
|
||||
RUN pip install --no-cache-dir fastapi uvicorn httpx
|
||||
|
||||
# Копируем прокси-сервис
|
||||
COPY tmdb_proxy.py .
|
||||
|
||||
# Открываем порт
|
||||
EXPOSE 8001
|
||||
|
||||
# Запускаем сервис
|
||||
CMD ["python", "tmdb_proxy.py"]
|
||||
|
||||
24
searchFilms/tmdb-proxy/README.md
Normal file
24
searchFilms/tmdb-proxy/README.md
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# TMDB Proxy Service
|
||||
|
||||
Прокси-сервис для TMDB API, который работает на хосте без VPN.
|
||||
|
||||
## Запуск
|
||||
|
||||
```bash
|
||||
docker-compose up -d --build
|
||||
```
|
||||
|
||||
Сервис будет доступен на порту `8001`.
|
||||
|
||||
## Использование
|
||||
|
||||
Основной сервис должен обращаться к этому прокси по адресу:
|
||||
- Если на том же хосте: `http://localhost:8001`
|
||||
- Если на другом хосте: `http://<IP_ХОСТА>:8001`
|
||||
|
||||
## API Endpoints
|
||||
|
||||
- `GET /search/movie?query=<название>` - поиск фильмов
|
||||
- `GET /movie/{movie_id}` - детали фильма
|
||||
- `GET /health` - проверка работоспособности
|
||||
|
||||
14
searchFilms/tmdb-proxy/docker-compose.yml
Normal file
14
searchFilms/tmdb-proxy/docker-compose.yml
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
services:
|
||||
tmdb-proxy:
|
||||
build: .
|
||||
container_name: tmdb-proxy
|
||||
environment:
|
||||
- TMDB_API_KEY=6d58225585fb77af5945a964de41849f
|
||||
- PORT=8001
|
||||
ports:
|
||||
- "0.0.0.0:8001:8001"
|
||||
restart: unless-stopped
|
||||
dns:
|
||||
- 8.8.8.8
|
||||
- 8.8.4.4
|
||||
|
||||
4
searchFilms/tmdb-proxy/requirements.txt
Normal file
4
searchFilms/tmdb-proxy/requirements.txt
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
fastapi==0.115.0
|
||||
uvicorn[standard]==0.30.6
|
||||
httpx>=0.25.2,<0.28.0
|
||||
|
||||
144
searchFilms/tmdb-proxy/tmdb_proxy.py
Normal file
144
searchFilms/tmdb-proxy/tmdb_proxy.py
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
TMDB API Proxy Service
|
||||
Прокси-сервис для TMDB API, который работает на хосте без VPN
|
||||
"""
|
||||
|
||||
import os
|
||||
import logging
|
||||
import httpx
|
||||
from fastapi import FastAPI, HTTPException, Query
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
# Настройка логирования
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI(title="TMDB API Proxy", version="1.0.0")
|
||||
|
||||
# Настройка CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# API ключ TMDB (прописываем прямо здесь)
|
||||
TMDB_API_KEY = os.getenv("TMDB_API_KEY", "6d58225585fb77af5945a964de41849f")
|
||||
TMDB_BASE_URL = "https://api.themoviedb.org/3"
|
||||
|
||||
|
||||
@app.get("/search/movie")
|
||||
async def search_movies(
|
||||
query: str = Query(..., description="Поисковый запрос"),
|
||||
language: str = Query("ru-RU", description="Язык"),
|
||||
include_adult: bool = Query(False, description="Включать взрослый контент"),
|
||||
page: int = Query(1, description="Номер страницы")
|
||||
):
|
||||
"""Прокси для поиска фильмов через TMDB API"""
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
try:
|
||||
logger.info(f"Searching TMDB for query: {query}")
|
||||
response = await client.get(
|
||||
f"{TMDB_BASE_URL}/search/movie",
|
||||
params={
|
||||
"api_key": TMDB_API_KEY,
|
||||
"query": query,
|
||||
"language": language,
|
||||
"include_adult": include_adult,
|
||||
"page": page
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
logger.info(f"TMDB search successful, found {data.get('total_results', 0)} results")
|
||||
return data
|
||||
except httpx.ConnectError as e:
|
||||
logger.error(f"Connection error to TMDB API: {e}")
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail=f"Cannot connect to TMDB API. Check network connectivity and DNS. Error: {str(e)}"
|
||||
)
|
||||
except httpx.TimeoutException as e:
|
||||
logger.error(f"Timeout connecting to TMDB API: {e}")
|
||||
raise HTTPException(
|
||||
status_code=504,
|
||||
detail=f"Timeout connecting to TMDB API: {str(e)}"
|
||||
)
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"TMDB API returned error status {e.response.status_code}: {e.response.text}")
|
||||
raise HTTPException(
|
||||
status_code=e.response.status_code,
|
||||
detail=f"TMDB API error (status {e.response.status_code}): {e.response.text[:200]}"
|
||||
)
|
||||
except httpx.HTTPError as e:
|
||||
logger.error(f"HTTP error: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"TMDB API error: {str(e)}")
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")
|
||||
|
||||
|
||||
@app.get("/movie/{movie_id}")
|
||||
async def get_movie_details(
|
||||
movie_id: int,
|
||||
language: str = Query("ru-RU", description="Язык"),
|
||||
append_to_response: str = Query(None, description="Дополнительные данные")
|
||||
):
|
||||
"""Прокси для получения детальной информации о фильме из TMDB"""
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
try:
|
||||
logger.info(f"Fetching TMDB movie details for ID: {movie_id}")
|
||||
params = {
|
||||
"api_key": TMDB_API_KEY,
|
||||
"language": language
|
||||
}
|
||||
if append_to_response:
|
||||
params["append_to_response"] = append_to_response
|
||||
|
||||
response = await client.get(
|
||||
f"{TMDB_BASE_URL}/movie/{movie_id}",
|
||||
params=params
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except httpx.ConnectError as e:
|
||||
logger.error(f"Connection error to TMDB API: {e}")
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail=f"Cannot connect to TMDB API. Check network connectivity and DNS. Error: {str(e)}"
|
||||
)
|
||||
except httpx.TimeoutException as e:
|
||||
logger.error(f"Timeout connecting to TMDB API: {e}")
|
||||
raise HTTPException(
|
||||
status_code=504,
|
||||
detail=f"Timeout connecting to TMDB API: {str(e)}"
|
||||
)
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"TMDB API returned error status {e.response.status_code}: {e.response.text}")
|
||||
raise HTTPException(
|
||||
status_code=e.response.status_code,
|
||||
detail=f"TMDB API error (status {e.response.status_code}): {e.response.text[:200]}"
|
||||
)
|
||||
except httpx.HTTPError as e:
|
||||
logger.error(f"HTTP error: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"TMDB API error: {str(e)}")
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
"""Проверка работоспособности сервиса"""
|
||||
return {"status": "ok", "service": "tmdb-proxy"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
port = int(os.getenv("PORT", "8001"))
|
||||
print(f"Starting TMDB Proxy on 0.0.0.0:{port}")
|
||||
uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue