Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
OscarDeBrito committed Apr 3, 2024
2 parents 260c6c8 + 230a9fb commit 069b16a
Show file tree
Hide file tree
Showing 14 changed files with 369 additions and 3 deletions.
13 changes: 10 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,14 @@ Como a versão LTS mais recente do Django (2024) é a 4.2, escolhemos configurar
Estas etapas são válidas para Linux OS e WSL.
#### Como subir o back-end:

Primeiramente, interrompa qualquer processo que use o porto 8080, 3306 e 6379.
Primeiramente, interrompa qualquer processo que use o porto 8080, 3306 e 6379. Então atualize o seu sistema:
```
sudo apt-get update
```

```
sudo apt-get upgrade
```

Em seguida, caso já não tenha instalado:

Expand Down Expand Up @@ -124,10 +131,10 @@ Em seguida, caso já não tenha instalado:

Virtualenv:
```
pip install virtualenv
sudo pip3 install virtualenv
```
Dentro da pasta raiz `api`:
Vá para dentro da pasta raiz `api`:
1. Cria o ambiente virtual e ative-o:
Expand Down
22 changes: 22 additions & 0 deletions api/places/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from django.db import models
from django.core.validators import MinValueValidator
from django.contrib.auth.models import User

class Place(models.Model):

name = models.CharField(max_length=50)
user = models.ForeignKey(User, verbose_name=("creator"), on_delete=models.CASCADE)

def __str__(self):
return self.name

class Room(models.Model):

name = models.CharField(max_length=50)
floor = models.IntegerField(default=0, validators=[MinValueValidator(0)])
place = models.ForeignKey(Place, related_name='rooms', on_delete=models.CASCADE)
systems = models.ManyToManyField('systems.System')




17 changes: 17 additions & 0 deletions api/places/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from rest_framework import serializers
from .models import Place, Room

class PlaceSerializer(serializers.ModelSerializer):
class Meta:
model = Place
fields = ['name', 'user']

class RoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
fields = ['id', 'name', 'floor', 'systems', 'place']
extra_kwargs = {
'name': {'required': True},
'floor': {'required': True},
'place_id': {'read_only': True}
}
35 changes: 35 additions & 0 deletions api/places/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from django.shortcuts import render

from rest_framework import generics
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets, mixins
from rest_framework.decorators import action
from rest_framework.response import Response

from .models import Place, Room
from .serializers import PlaceSerializer, RoomSerializer
from .permissions import IsOwnerOrReadOnly

class PlaceViewSet(viewsets.ModelViewSet):
queryset = Place.objects.all()
serializer_class = PlaceSerializer
permission_classes = []

@action(detail=True, methods=['get'])
def rooms(self, request, pk=None):
place = self.get_object()
serializer = RoomSerializer(place.rooms.all(), many=True)
return Response(serializer.data)

@action(detail=True, methods=['get'], url_path='rooms/(?P<room_pk>\d+)')
def room(self, request, pk=None, room_pk=None):
place = self.get_object()
room = get_object_or_404(place.rooms.all(), pk=room_pk)
serializer = RoomSerializer(room)
return Response(serializer.data)

class RoomViewSet(viewsets.ModelViewSet):
queryset = Room.objects.all()
serializer_class = RoomSerializer
permission_classes = []
12 changes: 12 additions & 0 deletions api/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
asgiref==3.7.2
async-timeout==4.0.3
Django==4.2
django-cors-headers==4.3.1
django-redis==5.4.0
django-redis-session-store==0.1.1
django-redis-sessions==0.6.2
djangorestframework==3.14.0
mysqlclient==2.2.4
pytz==2024.1
redis==5.0.3
sqlparse==0.4.4
123 changes: 123 additions & 0 deletions api/sigeie/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'django-insecure-vy00e(4im2%orzf_b+dv6k$6)%c$8zfjgb6vb^hd^ugxfqpk1)'

DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1', '10.0.2.2']

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'users',
'places',
'systems'
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
"corsheaders.middleware.CorsMiddleware",
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'sigeie.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'sigeie.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'root',
'NAME': 'sigeie_db',
'OPTIONS': {
'init_command': "SET sql_mode ='STRICT_TRANS_TABLES'"
}
}
}

CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://localhost:6379',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}

SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

SESSION_CACHE_ALIAS = 'default'

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': {
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
}
}

CORS_ALLOW_ALL_ORIGINS = True
27 changes: 27 additions & 0 deletions api/sigeie/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""
URL configuration for sigeie project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from places.urls import router

urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('users.urls')),
path('api/', include(router.urls)),
path('api/', include('systems.urls')),
path('auth/', include('rest_framework.urls'))
]
8 changes: 8 additions & 0 deletions api/systems/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.db import models

class System(models.Model):

name = models.CharField(max_length=50)

def __str__(self):
return self.name
7 changes: 7 additions & 0 deletions api/systems/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from rest_framework import serializers
from .models import System

class SystemSerializer(serializers.ModelSerializer):
class Meta:
model = System
fields = ['id', 'name']
8 changes: 8 additions & 0 deletions api/systems/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.urls import path, include
from .views import SystemViewDetail, SystemViewList

urlpatterns = [
path('systems/', SystemViewList.as_view()),
path('systems/<pk>/', SystemViewDetail.as_view())
]

13 changes: 13 additions & 0 deletions api/systems/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from rest_framework import viewsets, generics
from .models import System
from .serializers import SystemSerializer

class SystemViewList(generics.ListAPIView):
queryset = System.objects.all()
serializer_class = SystemSerializer
permission_classes = []

class SystemViewDetail(generics.RetrieveAPIView):
queryset = System.objects.all()
serializer_class = SystemSerializer
permission_classes = []
6 changes: 6 additions & 0 deletions api/users/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.db import models

# Create your models here



29 changes: 29 additions & 0 deletions api/users/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# serializers.py
from rest_framework import serializers, response
from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):

class Meta:
model = User
fields = ['id', 'password', 'username', 'first_name', 'email', 'is_active', 'date_joined', 'groups']
extra_kwargs = {
'password': {'write_only': True},
'first_name': {'required': True},
'email': {'required': True},
'is_active': {'read_only': True},
'date_joined': {'read_only': True},
'groups': {'read_only': True}
}

def create(self, validated_data):
user = User.objects.create_user(
username=validated_data['username'],
password=validated_data['password'],
email=validated_data.get('email') # use get se o email for opcional
)
return user

class UserSerializerP(serializers.Serializer):
username = serializers.CharField(max_length=200)
password = serializers.CharField(max_length=200)
Loading

0 comments on commit 069b16a

Please sign in to comment.