Skip to content

Commit

Permalink
Merge pull request #3 from fga-eps-mds/49-comentarios-videos
Browse files Browse the repository at this point in the history
49 comentarios videos
  • Loading branch information
geraldovictor authored Nov 16, 2023
2 parents 1283b53 + 7487c50 commit 762fdca
Show file tree
Hide file tree
Showing 21 changed files with 350 additions and 52 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,5 @@ cython_debug/
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
.vscode/
.vscode/
.vs/
11 changes: 6 additions & 5 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONBUFFERED 1

COPY . .
COPY requirements.txt /app/requirements.txt

ENV PYTHONPATH "/app/src"
RUN pip install -r requirements.txt
RUN pip3 install --no-cache-dir -r /app/requirements.txt

COPY . /app/

EXPOSE 8081
WORKDIR src

CMD [ "uvicorn", "src.main:app", "--host", "0.0.0.0","--port", "8081","--reload"]
CMD [ "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001", "--reload"]
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: python src/main.py ${PORT}
66 changes: 43 additions & 23 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,29 +1,49 @@
version: "3"

services:
db:
image: "postgres:alpine"
container_name: "db"
env_file:
- .env
volumes:
- postgres:/var/lib/postgresql/data
app:
build: .
ports:
- "5432:5432"

api:
- 8001:8001
volumes:
- .:/app/
env_file:
- ./.env
environment:
- POSTGRES_HOST=db
depends_on:
- db
build:
context: ./
container_name: video-service
links:
- db
ports:
- "8081:8081"
db:
condition: service_healthy
restart: always
networks:
- backend_videos

db:
image: postgres
volumes:
- ./:/app
- postgres_data:/var/lib/postgresql/data/
expose:
- 5432
environment:
- DEBUG=True
- POSTGRES_HOST=${POSTGRES_HOST}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_DB=${POSTGRES_DB}
env_file:
- ./.env
restart: always
networks:
- backend_videos
healthcheck:
test:
[
"CMD-SHELL",
"pg_isready -d ${POSTGRES_DB} -U ${POSTGRES_USER}",
]
interval: 10s
timeout: 5s
retries: 5

volumes:
postgres:
postgres_data:

networks:
backend_videos:
62 changes: 50 additions & 12 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,35 +1,73 @@
aiosmtplib==2.0.2
annotated-types==0.6.0
anyio==3.7.1
astroid==3.0.1
bcrypt==4.0.1
blinker==1.6.3
certifi==2023.7.22
cffi==1.16.0
charset-normalizer==3.3.0
click==8.1.7
coverage==7.3.2
cryptography==41.0.4
DateTime==5.2
deprecation==2.1.0
dill==0.3.7
dnspython==2.4.2
email-validator==2.1.0.post1
exceptiongroup==1.1.3
fastapi==0.104.1
docker==6.1.3
ecdsa==0.18.0
email-validator==2.0.0.post2
fastapi==0.104.0
fastapi-filter==1.0.0
fastapi-mail==1.4.1
fastapi-sso==0.7.2
greenlet==3.0.0
h11==0.14.0
httpcore==0.18.0
httptools==0.6.1
httpx==0.25.0
idna==3.4
itsdangerous==2.1.2
iniconfig==2.0.0
isort==5.12.0
Jinja2==3.1.2
MarkupSafe==2.1.3
mypy==1.6.1
mypy-extensions==1.0.0
orjson==3.9.10
mccabe==0.7.0
oauthlib==3.2.2
packaging==23.2
passlib==1.7.4
platformdirs==3.11.0
pluggy==1.3.0
psycopg2-binary==2.9.9
pyasn1==0.5.0
pycparser==2.21
pydantic==2.4.2
pydantic-extra-types==2.1.0
pydantic-settings==2.0.3
pydantic_core==2.10.1
pylint==3.0.2
PyMySQL==1.1.0
pytest==7.4.2
pytest-asyncio==0.21.1
pytest-html==4.1.1
pytest-metadata==3.0.0
pytest-mock==3.12.0
python-dotenv==1.0.0
python-jose==3.3.0
python-multipart==0.0.6
pytz==2023.3.post1
PyYAML==6.0.1
requests==2.31.0
rsa==4.9
six==1.16.0
sniffio==1.3.0
SQLAlchemy==2.0.22
starlette==0.27.0
tomli==2.0.1
testcontainers==3.7.1
tomlkit==0.12.2
typing_extensions==4.8.0
ujson==5.8.0
urllib3==2.0.7
uvicorn==0.23.2
uvloop==0.19.0
watchfiles==0.21.0
websockets==12.0
websocket-client==1.6.4
websockets==11.0.3
wrapt==1.15.0
zope.interface==6.1
1 change: 1 addition & 0 deletions runtime.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python-3.10.12
1 change: 1 addition & 0 deletions sonar-project.properties
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
sonar.projectKey=fga-eps-mds_2023.2-UnB-TV-Admin
sonar.projectKey=fga-eps-mds_2023.2-UnB-TV-VideoService
sonar.organization=fga-eps-mds-1

Expand Down
8 changes: 0 additions & 8 deletions src/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +0,0 @@
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
return {"message": "Hello World"}
Empty file added src/constants/__init__.py
Empty file.
6 changes: 6 additions & 0 deletions src/constants/errorMessages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
USER_ID_REQUIRED = "USER ID FIELD REQUIRED"
VIDEO_ID_REQUIRED = "VIDEO ID FIELD REQUIRED"
CONTENT_REQUIRED = "CONTENT FIELD REQUIRED"
COMMENT_NOT_FOUND = "COMMENT NOT FOUND"
MISSING_ENV_VALUES = "SOME ENVIRONMENT VALUES WERE NOT DEFINED"
INVALID_REQUEST = "INVALID_REQUEST"
Empty file added src/controller/__init__.py
Empty file.
36 changes: 36 additions & 0 deletions src/controller/commentController.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from fastapi import APIRouter, HTTPException, Response, status, Depends
from database import get_db
from sqlalchemy.orm import Session

from domain import commentSchema
from repository import commentRepository
from constants import errorMessages

comment = APIRouter(
prefix="/comments"
)

@comment.get("/{video_id}", response_model=list[commentSchema.Comment])
def read_comment(video_id: int, db: Session = Depends(get_db)):
comment = commentRepository.get_comments_by_video_id(db, video_id=video_id)
return comment

@comment.post("/", response_model=commentSchema.Comment)
def create_comment(comment: commentSchema.CommentCreate, db: Session = Depends(get_db)):
return commentRepository.create_comment(db=db, video_id=comment.video_id, user_id=comment.user_id, user_name= comment.user_name ,content=comment.content)

@comment.delete("/{id}", response_model=commentSchema.Comment)
def delete_comment(id: int, db: Session = Depends(get_db)):
comment = commentRepository.get_comment_by_id(db, id)
if not comment:
raise HTTPException(status_code=404, detail=errorMessages.COMMENT_NOT_FOUND)
commentRepository.delete_comment(db,comment)
return comment

@comment.patch("/{id}", response_model=commentSchema.Comment)
def update_comment(id: int, data: commentSchema.CommentUpdate,db: Session = Depends(get_db)):
comment = commentRepository.get_comment_by_id(db, id)
if not comment:
raise HTTPException(status_code=404, detail=errorMessages.COMMENT_NOT_FOUND)
updated_comment = commentRepository.update_comment(db,comment,data)
return updated_comment
24 changes: 24 additions & 0 deletions src/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import os, sys
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

POSTGRES_USER = os.getenv("POSTGRES_USER")
POSTGRES_PASSWORD = os.getenv("POSTGRES_PASSWORD")
POSTGRES_HOST = os.getenv("POSTGRES_HOST")
POSTGRES_DB = os.getenv("POSTGRES_DB")
POSTGRES_PORT = os.getenv("POSTGRES_PORT", default=5432)

POSTGRES_URI = f'postgresql://{POSTGRES_USER}:{POSTGRES_PASSWORD}@{POSTGRES_HOST}:{POSTGRES_PORT}/{POSTGRES_DB}'

engine = create_engine(POSTGRES_URI)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Empty file added src/domain/__init__.py
Empty file.
22 changes: 22 additions & 0 deletions src/domain/commentSchema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from datetime import date
from pydantic import BaseModel, ConfigDict

class CommentUpdate(BaseModel):
content: str | None = None

class Comment(BaseModel):
model_config = ConfigDict(from_attributes = True)
id: int
user_id: int
user_name: str
video_id: int
content: str
created_at: date

class CommentCreate(BaseModel):
model_config = ConfigDict(from_attributes = True)
user_id: int
user_name: str
video_id: int
content: str

30 changes: 27 additions & 3 deletions src/main.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,37 @@
import uvicorn
import uvicorn, sys
from fastapi import FastAPI
from dotenv import load_dotenv
from fastapi.middleware.cors import CORSMiddleware

load_dotenv()

from controller import commentController
from database import SessionLocal, engine
from model import commentModel

commentModel.Base.metadata.create_all(bind=engine)

app = FastAPI()


app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

@app.get("/")
async def root():
return {"message": "Hello from Video Service"}


if __name__ == '__main__':
uvicorn.run('main:app', reload=True)
app.include_router(prefix="/api", router=commentController.comment)

if __name__ == '__main__': # pragma: no cover
port = 8001
if (len(sys.argv) == 2):
port = sys.argv[1]

uvicorn.run('main:app', reload=True, port=int(port), host="0.0.0.0")
Empty file added src/model/__init__.py
Empty file.
19 changes: 19 additions & 0 deletions src/model/commentModel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Referencia: https://fastapi.tiangolo.com/tutorial/sql-databases/#create-the-database-models

from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, Date
from sqlalchemy.orm import relationship
from datetime import datetime

from database import Base

class Comment(Base):
__tablename__ = "comments"
__table_args__ = {'extend_existing': True}

id = Column(Integer, primary_key=True, index=True)
video_id = Column(Integer, nullable=False)
user_id = Column(Integer, nullable=False)
user_name = Column(String, nullable=False)
content = Column(String, nullable=False)
created_at = Column(Date, nullable=False, default=datetime.now())

Empty file added src/repository/__init__.py
Empty file.
Loading

0 comments on commit 762fdca

Please sign in to comment.