Skip to content

Commit 9744390

Browse files
committed
feat: Initial project setup
0 parents  commit 9744390

14 files changed

+677
-0
lines changed

.dockerignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
venv
2+
__pycache__

.gitignore

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
# Created by https://www.toptal.com/developers/gitignore/api/python
2+
# Edit at https://www.toptal.com/developers/gitignore?templates=python
3+
4+
### Python ###
5+
# Byte-compiled / optimized / DLL files
6+
__pycache__/
7+
*.py[cod]
8+
*$py.class
9+
10+
# C extensions
11+
*.so
12+
13+
# Distribution / packaging
14+
.Python
15+
build/
16+
develop-eggs/
17+
dist/
18+
downloads/
19+
eggs/
20+
.eggs/
21+
lib/
22+
lib64/
23+
parts/
24+
sdist/
25+
var/
26+
wheels/
27+
share/python-wheels/
28+
*.egg-info/
29+
.installed.cfg
30+
*.egg
31+
MANIFEST
32+
33+
# PyInstaller
34+
# Usually these files are written by a python script from a template
35+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
36+
*.manifest
37+
*.spec
38+
39+
# Installer logs
40+
pip-log.txt
41+
pip-delete-this-directory.txt
42+
43+
# Unit test / coverage reports
44+
htmlcov/
45+
.tox/
46+
.nox/
47+
.coverage
48+
.coverage.*
49+
.cache
50+
nosetests.xml
51+
coverage.xml
52+
*.cover
53+
*.py,cover
54+
.hypothesis/
55+
.pytest_cache/
56+
cover/
57+
58+
# Translations
59+
*.mo
60+
*.pot
61+
62+
# Django stuff:
63+
*.log
64+
local_settings.py
65+
db.sqlite3
66+
db.sqlite3-journal
67+
68+
# Flask stuff:
69+
instance/
70+
.webassets-cache
71+
72+
# Scrapy stuff:
73+
.scrapy
74+
75+
# Sphinx documentation
76+
docs/_build/
77+
78+
# PyBuilder
79+
.pybuilder/
80+
target/
81+
82+
# Jupyter Notebook
83+
.ipynb_checkpoints
84+
85+
# IPython
86+
profile_default/
87+
ipython_config.py
88+
89+
# pyenv
90+
# For a library or package, you might want to ignore these files since the code is
91+
# intended to run in multiple environments; otherwise, check them in:
92+
# .python-version
93+
94+
# pipenv
95+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
97+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
98+
# install all needed dependencies.
99+
#Pipfile.lock
100+
101+
# poetry
102+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
103+
# This is especially recommended for binary packages to ensure reproducibility, and is more
104+
# commonly ignored for libraries.
105+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
106+
#poetry.lock
107+
108+
# pdm
109+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
110+
#pdm.lock
111+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
112+
# in version control.
113+
# https://pdm.fming.dev/#use-with-ide
114+
.pdm.toml
115+
116+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
117+
__pypackages__/
118+
119+
# Celery stuff
120+
celerybeat-schedule
121+
celerybeat.pid
122+
123+
# SageMath parsed files
124+
*.sage.py
125+
126+
# Environments
127+
.env
128+
.venv
129+
env/
130+
venv/
131+
ENV/
132+
env.bak/
133+
venv.bak/
134+
135+
# Spyder project settings
136+
.spyderproject
137+
.spyproject
138+
139+
# Rope project settings
140+
.ropeproject
141+
142+
# mkdocs documentation
143+
/site
144+
145+
# mypy
146+
.mypy_cache/
147+
.dmypy.json
148+
dmypy.json
149+
150+
# Pyre type checker
151+
.pyre/
152+
153+
# pytype static type analyzer
154+
.pytype/
155+
156+
# Cython debug symbols
157+
cython_debug/
158+
159+
# PyCharm
160+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
161+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
162+
# and can be added to the global gitignore or merged into this file. For a more nuclear
163+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
164+
#.idea/
165+
166+
### Python Patch ###
167+
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
168+
poetry.toml
169+
170+
# ruff
171+
.ruff_cache/
172+
173+
# LSP config files
174+
pyrightconfig.json
175+
176+
# End of https://www.toptal.com/developers/gitignore/api/python

Dockerfile

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# 1. Define a imagem base
2+
FROM python:3.13.5-alpine3.22
3+
4+
# 2. Define o diretório de trabalho dentro do contêiner
5+
WORKDIR /app
6+
7+
# 3. Copia o arquivo de dependências primeiro para aproveitar o cache do Docker
8+
# Se o requirements.txt não mudar, o Docker não reinstalará as dependências
9+
COPY requirements.txt .
10+
11+
# 4. Instala as dependências
12+
RUN pip install --no-cache-dir -r requirements.txt
13+
14+
# 5. Copia o resto do código da aplicação para o diretório de trabalho
15+
COPY . .
16+
17+
# 6. Expõe a porta que a aplicação vai rodar
18+
EXPOSE 8000
19+
20+
# 7. Define o comando para iniciar a aplicação quando o contêiner for executado
21+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]

app.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from fastapi import FastAPI
2+
from database import engine, Base
3+
from routers.alunos import alunos_router
4+
from routers.cursos import cursos_router
5+
from routers.matriculas import matriculas_router
6+
7+
8+
Base.metadata.create_all(bind=engine)
9+
10+
app = FastAPI(
11+
title="API de Gestão Escolar",
12+
description="""
13+
Esta API fornece endpoints para gerenciar alunos, cursos e turmas, em uma instituição de ensino.
14+
15+
Permite realizar diferentes operações em cada uma dessas entidades.
16+
""",
17+
version="1.0.0",
18+
)
19+
20+
app.include_router(alunos_router, tags=["alunos"])
21+
app.include_router(cursos_router, tags=["cursos"])
22+
app.include_router(matriculas_router, tags=["matriculas"])

database.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from sqlalchemy import create_engine
2+
from sqlalchemy.ext.declarative import declarative_base
3+
from sqlalchemy.orm import sessionmaker
4+
import os
5+
6+
# Caminho para o arquivo SQLite (pode ser ajustado conforme necessário)
7+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
8+
DATABASE_URL = f"sqlite:///{os.path.join(BASE_DIR, 'escola.db')}"
9+
10+
engine = create_engine(
11+
DATABASE_URL, connect_args={"check_same_thread": False}
12+
)
13+
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
14+
15+
Base = declarative_base()
16+
17+
def get_db():
18+
db = SessionLocal()
19+
try:
20+
yield db
21+
finally:
22+
db.close()
23+
24+

docker-compose.yml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
services:
2+
api:
3+
build: . # Constrói a imagem a partir do Dockerfile no diretório atual
4+
container_name: api # Nome do contêiner
5+
ports:
6+
- "8000:8000" # Mapeia a porta 8000 do contêiner para a porta 8000 do seu computador
7+
# Monta o diretório atual no contêiner para refletir as mudanças no código em tempo real
8+
# e para persistir o banco de dados SQLite (escola.db) no seu computador.
9+
volumes:
10+
- .:/app
11+

escola.db

32 KB
Binary file not shown.

models.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from sqlalchemy import Column, Integer, String, Text, ForeignKey, Table
2+
from sqlalchemy.orm import relationship
3+
from database import Base
4+
5+
class Matricula(Base):
6+
__tablename__ = "matriculas"
7+
8+
id = Column(Integer, primary_key=True, index=True)
9+
aluno_id = Column(Integer, ForeignKey("alunos.id"))
10+
curso_id = Column(Integer, ForeignKey("cursos.id"))
11+
12+
aluno = relationship("Aluno", back_populates="matriculas")
13+
curso = relationship("Curso", back_populates="matriculas")
14+
15+
class Aluno(Base):
16+
__tablename__ = "alunos"
17+
18+
id = Column(Integer, primary_key=True, index=True)
19+
nome = Column(String, nullable=False)
20+
email = Column(String, nullable=False)
21+
telefone = Column(String, nullable=False)
22+
23+
matriculas = relationship("Matricula", back_populates="aluno")
24+
25+
class Curso(Base):
26+
__tablename__ = "cursos"
27+
28+
id = Column(Integer, primary_key=True, index=True)
29+
nome = Column(String, nullable=False)
30+
codigo = Column(String, nullable=False, unique=True)
31+
descricao = Column(Text)
32+
33+
matriculas = relationship("Matricula", back_populates="curso")

readme.md

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# Imersão DevOps - Alura Google Cloud
2+
3+
Este projeto é uma API desenvolvida com FastAPI para gerenciar alunos, cursos e matrículas em uma instituição de ensino.
4+
5+
## Pré-requisitos
6+
7+
- [Python 3.10 ou superior instalado](https://www.python.org/downloads/)
8+
- [Git](https://git-scm.com/downloads)
9+
- [Docker](https://www.docker.com/get-started/)
10+
11+
## Passos para subir o projeto
12+
13+
1. **Faça o download do repositório:**
14+
[Clique aqui para realizar o download](https://github.com/guilhermeonrails/imersao-devops/archive/refs/heads/main.zip)
15+
16+
2. **Crie um ambiente virtual:**
17+
```sh
18+
python3 -m venv ./venv
19+
```
20+
21+
3. **Ative o ambiente virtual:**
22+
- No Linux/Mac:
23+
```sh
24+
source venv/bin/activate
25+
```
26+
- No Windows, abra um terminal no modo administrador e execute o comando:
27+
```sh
28+
Set-ExecutionPolicy RemoteSigned
29+
```
30+
31+
```sh
32+
venv\Scripts\activate
33+
```
34+
35+
4. **Instale as dependências:**
36+
```sh
37+
pip install -r requirements.txt
38+
```
39+
40+
5. **Execute a aplicação:**
41+
```sh
42+
uvicorn app:app --reload
43+
```
44+
45+
6. **Acesse a documentação interativa:**
46+
47+
Abra o navegador e acesse:
48+
[http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
49+
50+
Aqui você pode testar todos os endpoints da API de forma interativa.
51+
52+
---
53+
54+
## Estrutura do Projeto
55+
56+
- `app.py`: Arquivo principal da aplicação FastAPI.
57+
- `models.py`: Modelos do banco de dados (SQLAlchemy).
58+
- `schemas.py`: Schemas de validação (Pydantic).
59+
- `database.py`: Configuração do banco de dados SQLite.
60+
- `routers/`: Diretório com os arquivos de rotas (alunos, cursos, matrículas).
61+
- `requirements.txt`: Lista de dependências do projeto.
62+
63+
---
64+
65+
- O banco de dados SQLite será criado automaticamente como `escola.db` na primeira execução.
66+
- Para reiniciar o banco, basta apagar o arquivo `escola.db` (isso apagará todos os dados).
67+
68+
---

requirements.txt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
annotated-types==0.7.0
2+
anyio==4.9.0
3+
click==8.2.1
4+
dnspython==2.7.0
5+
email_validator==2.2.0
6+
fastapi==0.115.12
7+
h11==0.16.0
8+
idna==3.10
9+
pydantic==2.11.5
10+
pydantic_core==2.33.2
11+
sniffio==1.3.1
12+
SQLAlchemy==2.0.41
13+
starlette==0.46.2
14+
typing-inspection==0.4.1
15+
typing_extensions==4.13.2
16+
uvicorn==0.34.2

0 commit comments

Comments
 (0)