Skip to content
Merged
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
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Environment variables for PyNews Server

# API Configuration
PYTHONPATH=/server

# Add any additional environment variables your application might need
# DATABASE_URL=postgresql://user:password@localhost:5432/pynews
# DEBUG=false
# LOG_LEVEL=info
32 changes: 32 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Debug Tests",
"type": "python",
"request": "launch",
"module": "pytest",
"args": [
"tests/",
"-v",
"-s"
],
"console": "integratedTerminal",
"justMyCode": false,
},
{
"name": "Python: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": [
"app.main:app",
"--reload",
"--port",
"8010"
],
"jinja": true,
"justMyCode": false
}
]
}
10 changes: 10 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"[python]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": "explicit",
"source.organizeImports": "explicit"
},
"editor.defaultFormatter": "charliermarsh.ruff"
}
}
63 changes: 63 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
FROM python:3.13.3-slim-bookworm AS python-base

ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PIP_DISABLE_PIP_VERSION_CHECK=on \
PIP_DEFAULT_TIMEOUT=100 \
POETRY_VERSION=1.8.2 \
POETRY_HOME="/opt/poetry" \
POETRY_VIRTUALENVS_IN_PROJECT=true \
POETRY_NO_INTERACTION=1 \
PYSETUP_PATH="/opt/pysetup" \
VENV_PATH="/opt/pysetup/.venv" \
PROJECT_PATH="/server"
ENV PATH="$VENV_PATH/bin:$PATH"

FROM python-base AS builder-base

WORKDIR $PYSETUP_PATH
COPY poetry.lock pyproject.toml ./

RUN apt-get update \
&& apt-get install --no-install-recommends -y \
build-essential \
curl \
git \
libpq-dev \
libseccomp2 \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*


RUN --mount=type=cache,target=/root/.cache/pip \
pip install "poetry==$POETRY_VERSION";

RUN --mount=type=cache,target=/root/.cache/poetry \
poetry install --only main --no-root --no-interaction


FROM python-base AS production

WORKDIR $PROJECT_PATH
COPY --from=builder-base $VENV_PATH $VENV_PATH

RUN adduser --disabled-password --gecos '' appuser
COPY --chown=appuser:appuser app app
USER appuser
EXPOSE 8000

ENTRYPOINT ["uvicorn"]
CMD ["app.main:app", "--host", "0.0.0.0", "--port", "8000", "--lifespan", "on"]


FROM builder-base AS development

WORKDIR $PYSETUP_PATH

RUN poetry install --no-root --no-interaction

WORKDIR $PROJECT_PATH
COPY app app
COPY tests tests

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--lifespan", "on"]
75 changes: 75 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
.PHONY: help build up down logs test lint format clean dev prod restart health

# Colors for terminal output
GREEN=\033[0;32m
YELLOW=\033[1;33m
NC=\033[0m # No Color

help: ## Mostra esta mensagem de ajuda
@echo "$(YELLOW)PyNews Server - Comandos Disponíveis:$(NC)"
@echo ""
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf " $(GREEN)%-15s$(NC) %s\n", $$1, $$2}'

build: ## Constrói as imagens Docker
@echo "$(YELLOW)Construindo imagens Docker...$(NC)"
docker-compose build

up: ## Inicia os serviços
@echo "$(YELLOW)Iniciando serviços...$(NC)"
docker-compose up -d

down: ## Para os serviços
@echo "$(YELLOW)Parando serviços...$(NC)"
docker-compose down

logs: ## Mostra os logs dos serviços
docker-compose logs -f pynews-api

test: ## Executa os testes
@echo "$(YELLOW)Executando testes...$(NC)"
poetry run pytest

test-cov: ## Executa os testes com coverage
@echo "$(YELLOW)Executando testes com coverage...$(NC)"
poetry run pytest --cov=app --cov-report=html

lint: ## Verifica o código com ruff
@echo "$(YELLOW)Verificando código...$(NC)"
poetry run ruff check .

format: ## Formata o código
@echo "$(YELLOW)Formatando código...$(NC)"
poetry run ruff format .

clean: ## Remove containers, volumes e imagens
@echo "$(YELLOW)Limpando containers e volumes...$(NC)"
docker-compose down -v --remove-orphans
docker system prune -f

dev: build up ## Ambiente de desenvolvimento completo
@echo "$(GREEN)Ambiente de desenvolvimento iniciado!$(NC)"
@echo "API: http://localhost:8000"
@echo "Docs: http://localhost:8000/docs"

prod: ## Inicia em modo produção
@echo "$(YELLOW)Iniciando em modo produção...$(NC)"
docker-compose -f docker-compose.yaml up -d

restart: ## Reinicia os serviços
@echo "$(YELLOW)Reiniciando serviços...$(NC)"
docker-compose restart

health: ## Verifica o health check da API
@echo "$(YELLOW)Verificando saúde da API...$(NC)"
curl -f http://localhost:8000/api/healthcheck || echo "API não está respondendo"

install: ## Instala dependências com Poetry
@echo "$(YELLOW)Instalando dependências...$(NC)"
poetry install

shell: ## Entra no shell do container
docker-compose exec pynews-api bash

setup: install build up ## Setup completo do projeto
@echo "$(GREEN)Setup completo realizado!$(NC)"
@echo "$(GREEN)Acesse: http://localhost:8000/docs$(NC)"
162 changes: 159 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,168 @@ sequenceDiagram
```

## ⚙️ Como Rodar
[TBD]

### 📋 Pré-requisitos
- Docker e Docker Compose instalados
- Git (para clonar o repositório)

### 🚀 Início Rápido

1. **Clone o repositório:**
```bash
git clone <repository-url>
cd PyNewsServer
```

2. **Configure as variáveis de ambiente (opcional):**
```bash
cp .env.example .env
# Edite o arquivo .env conforme necessário
```

3. **Inicie o serviço:**
```bash
docker-compose up -d
```

4. **Acesse a aplicação:**
- API: http://localhost:8000
- Documentação Swagger: http://localhost:8000/docs
- Health Check: http://localhost:8000/api/healthcheck

## 🧩 Configuração Inicial

### ▶️ Guia de Execução Dev
### ▶️ Guia de Execução para Desenvolvimento

#### Usando Docker (Recomendado)
```bash
# Construir e iniciar em modo desenvolvimento
docker-compose up --build

# Ver logs em tempo real
docker-compose logs -f pynews-api

# Parar o serviço
docker-compose down
```

#### Usando Poetry (Local)
```bash
# Instalar dependências
poetry install

# Ativar ambiente virtual
poetry shell

# Rodar a aplicação
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload

# Rodar testes
poetry run pytest

# Linting
poetry run ruff check .
poetry run ruff format .
```

### ▶️ Guia de Execução para Produção

```bash
# Construir imagem para produção
docker-compose build --target production

# Iniciar em modo produção
docker-compose up -d

# Verificar status dos containers
docker-compose ps

# Ver logs
docker-compose logs pynews-api

# Atualizar aplicação
docker-compose pull
docker-compose up -d --force-recreate
```

### 🔧 Comandos Úteis

### ▶️ Guia de Execução Prod
#### Usando Makefile (Recomendado)
```bash
# Ver todos os comandos disponíveis
make help

# Setup completo do projeto
make setup

# Ambiente de desenvolvimento
make dev

# Construir e iniciar
make build
make up

# Ver logs
make logs

# Executar testes
make test
make test-cov

# Linting e formatação
make lint
make format

# Verificar saúde da API
make health

# Parar serviços
make down

# Limpeza completa
make clean
```

#### Comandos Docker Diretos
```bash
# Entrar no container
docker-compose exec pynews-api bash

# Reiniciar apenas o serviço da API
docker-compose restart pynews-api

# Verificar health check
curl http://localhost:8000/api/healthcheck

# Parar e remover todos os containers e volumes
docker-compose down -v
```

### 🛠️ Desenvolvimento

#### Estrutura de Testes
```bash
# Rodar todos os testes
poetry run pytest

# Rodar testes com coverage
poetry run pytest --cov=app

# Rodar testes específicos
poetry run pytest tests/test_auth.py
```

#### Linting e Formatação
```bash
# Verificar código
poetry run ruff check .

# Formatar código
poetry run ruff format .

# Fix automático de problemas
poetry run ruff check . --fix
```


## referencias
Expand Down
Loading