Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run isort and black into the codebase #101

Merged
merged 12 commits into from
Mar 17, 2024
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
35 changes: 35 additions & 0 deletions .github/workflows/backend-black.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Backend Run Black style

on:
pull_request:
branches:
- 'master'
- 'master-*'
jobs:

run_tests:
runs-on: ubuntu-22.04
steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Set up Python 3.10
uses: actions/setup-python@v3
with:
python-version: "3.10"
architecture: "x64"
env:
AGENT_TOOLSDIRECTORY: /opt/hostedtoolcache

- name: Install dependencies
working-directory: Backend/
run: pip install -r requirements.txt && pip install -r requirements-test.txt && pip install -r requirements-dev.txt

- name: Run style check
working-directory: Backend/src
run: python -m black . --check

- name: Fail workflow on style check failure
if: ${{ failure() }}
run: exit 1

3 changes: 3 additions & 0 deletions Backend/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"python.analysis.typeCheckingMode": "basic",
"flake8.args": [
"--max-line-length=88"
],
}
18 changes: 9 additions & 9 deletions Backend/src/database/Database.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import logging
import os

from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
import os
import logging

formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
logging.basicConfig(level=logging.WARNING)

""" Singleton instance of the MongoDb connection """
Expand All @@ -30,8 +31,8 @@ def __call__(cls, *args, **kwargs):


class Database(metaclass=DatabaseMeta):
"""Direct connection to the MongoDB client"""

""" Direct connection to the MongoDB client """
connection = None
""" Connection to the list database """
list_collection = None
Expand All @@ -42,14 +43,13 @@ def __init__(self):
if Database.connection is None:
try:
uri = os.getenv("MONGO_URI")
Database.connection = MongoClient(uri, server_api=ServerApi('1'))[
"SpotifyElectron"]
Database.connection = MongoClient(uri, server_api=ServerApi("1"))[
"SpotifyElectron"
]
Database.list_collection = Database.connection["playlist"]
Database.song_collection = Database.connection["song"]

except Exception as error:
logging.critical(
"Error: Connection not established {}".format(error))
logging.critical("Error: Connection not established {}".format(error))
else:
logging.info("Connection established")

2 changes: 1 addition & 1 deletion Backend/src/generate-docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@
"""

if __name__ == "__main__":
with open(f"api-docs-spotify-electron.html", "w") as fd:
with open("api-docs-spotify-electron.html", "w") as fd:
print(HTML_TEMPLATE % json.dumps(app.openapi()), file=fd)
38 changes: 27 additions & 11 deletions Backend/src/main.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,41 @@
from fastapi import FastAPI, Request, Response
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from routers import playlists, canciones, generos, usuarios, artistas, login , search
from services.security_service import check_jwt_is_valid
from middleware.middleware import CheckJwtAuth
from routers import (
artistas,
canciones,
generos,
login,
playlists,
search,
usuarios,
)

app = FastAPI(title="SpotifyElectronAPI",
description="API created with FastAPI Python to serve as backend for SpotifyElectron App",
version="0.0.1"
)
app = FastAPI(
title="SpotifyElectronAPI",
description="API created with FastAPI Python to manage backend for \
Spotify Electron App https://github.com/AntonioMrtz/SpotifyElectron",
version="0.0.1",
)

""" Cors disabled """
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost/", "http://localhost:1212", "https://localhost:1212/",
"https://localhost", "https://localhost:1212", "https://localhost:1212/", "http://127.0.0.1:8000/", "http://127.0.0.1:8000", "http://127.0.0.1:8000/usuarios/prueba"],
allow_origins=[
"http://localhost/",
"http://localhost:1212",
"https://localhost:1212/",
"https://localhost",
"https://localhost:1212",
"https://localhost:1212/",
"http://127.0.0.1:8000/",
"http://127.0.0.1:8000",
"http://127.0.0.1:8000/usuarios/",
],
allow_credentials=True,
allow_methods=["POST", "GET", "PUT", "DELETE", "PATCH"],
max_age=3600,
# You can restrict this to specific headers if needed
allow_headers=["*"],

)

app.add_middleware(CheckJwtAuth)
Expand Down
32 changes: 23 additions & 9 deletions Backend/src/middleware/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,46 @@


class CheckJwtAuth(BaseHTTPMiddleware):

bypass_urls = {

"GET": ["/usuarios/whoami", "/usuarios/whoami/", "/docs", "/docs/", "/openapi.json"],
"POST": ["/usuarios/", "/usuarios", "/login/", "/login", "/artistas/", "/artistas"],
"GET": [
"/usuarios/whoami",
"/usuarios/whoami/",
"/docs",
"/docs/",
"/openapi.json",
],
"POST": [
"/usuarios/",
"/usuarios",
"/login/",
"/login",
"/artistas/",
"/artistas",
],
}

bypass_methods = ["DELETE"]

def bypass_request(self, request: Request):
""" print(request.method)
"""print(request.method)
print(request.url.path)
print(request.headers) """
print(request.headers)"""
""" print(f"COOKIES = \n {request.cookies}")
print(f"HEADERS = \n {request.headers}") """

if request.method in self.bypass_methods:
return True
elif request.method in self.bypass_urls.keys() and request.url.path in self.bypass_urls[request.method]:
elif (
request.method in self.bypass_urls.keys()
and request.url.path in self.bypass_urls[request.method]
):
return True
else:
return False

async def dispatch(self, request: Request, call_next):
""" response = await call_next(request)
return response """
"""response = await call_next(request)
return response"""
try:
if self.bypass_request(request):
response = await call_next(request)
Expand Down
7 changes: 3 additions & 4 deletions Backend/src/model/Artist.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import json
from dataclasses import dataclass

from model.User import User
import json


@dataclass
class Artist(User):

uploaded_songs: list

def get_json(self) -> json:

def get_json(self) -> str:
user_json = super().get_json()
data = json.loads(user_json)

Expand Down
11 changes: 3 additions & 8 deletions Backend/src/model/DTO/PlaylistDTO.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
from dataclasses import dataclass
from datetime import date
import services.song_service as song_service
import json
from dataclasses import dataclass


@dataclass
class PlaylistDTO:

name: str
photo: str
description: str
upload_date: str
owner : str
owner: str
song_names: list

def add_songs(self, song_names: str) -> None:

self.song_names.extends(song_names)

def get_json(self) -> json:

def get_json(self) -> str:
playlist_dict = self.__dict__

playlist_json = json.dumps(playlist_dict)
Expand Down
6 changes: 3 additions & 3 deletions Backend/src/model/DTO/SongDTO.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import json
from dataclasses import dataclass

from model.Genre import Genre
import json


@dataclass
class SongDTO:

name: str
artist: str
photo: str
Expand All @@ -14,6 +14,6 @@ class SongDTO:
genre: Genre
number_of_plays: int

def get_json(self) -> json:
def get_json(self) -> str:
song_json = json.dumps(self.__dict__)
return song_json
11 changes: 6 additions & 5 deletions Backend/src/model/Genre.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from enum import Enum


class Genre(Enum):
POP = "Pop"
ROCK = "Rock"
Expand Down Expand Up @@ -30,14 +31,14 @@ class Genre(Enum):
SKA = "Ska"
GRUNGE = "Grunge"
TRAP = "Trap"
REGGAETON="Reggaeton"
REGGAETON = "Reggaeton"

def checkValidGenre(genre : str) -> bool:
""" Checks if the genre is valid """
def checkValidGenre(genre: str) -> bool:
"""Checks if the genre is valid"""
if Genre(genre) is None:
return False
return True

def getGenre(genre : str) -> str:
""" Returns genre string """
def getGenre(genre: str) -> str:
"""Returns genre string"""
return str(genre.value)
18 changes: 8 additions & 10 deletions Backend/src/model/Playlist.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import json
from dataclasses import dataclass
from datetime import datetime

import services.song_service as song_service
import json


@dataclass
class Playlist:

name: str
photo: str
description: str
Expand All @@ -15,12 +15,9 @@ class Playlist:
songs: list

def add_songs(self, song_names: str) -> None:
[songs.append(song_service.get_song(song_name)) for song_name in song_names]

[songs.append(song_service.get_song(song_name))
for song_name in song_names]

def get_json(self) -> json:

def get_json(self) -> str:
playlist_dict = self.__dict__

songs_json = []
Expand All @@ -29,10 +26,11 @@ def get_json(self) -> json:
song_json = song.get_json()
songs_json.append(song_json)

# Eliminar el atributo song_names del diccionario , hay que serializar song primero
playlist_dict.pop('songs', None)
# Eliminar el atributo song_names del diccionario ,
# hay que serializar song primero
playlist_dict.pop("songs", None)
# Convertir el diccionario en una cadena JSON
playlist_dict['songs'] = songs_json
playlist_dict["songs"] = songs_json
playlist_json = json.dumps(playlist_dict)

return playlist_json
6 changes: 3 additions & 3 deletions Backend/src/model/Song.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import json
from dataclasses import dataclass

from model.Genre import Genre
import json


@dataclass
class Song:

name: str
artist: str
photo: str
Expand All @@ -14,6 +14,6 @@ class Song:
url: str
number_of_plays: int

def get_json(self) -> json:
def get_json(self) -> str:
song_json = json.dumps(self.__dict__)
return song_json
10 changes: 5 additions & 5 deletions Backend/src/model/TokenData.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from dataclasses import dataclass
import json
from dataclasses import dataclass


@dataclass
class TokenData():
class TokenData:
username: str
role: str
token_type : str

def get_json(self) -> json:
token_type: str

def get_json(self) -> str:
token_data_json = json.dumps(self.__dict__)
return token_data_json
Loading
Loading