Skip to content

Commit

Permalink
Merge pull 33-mant/adicionar-swagger-a-todos-os-endpoints
Browse files Browse the repository at this point in the history
33 mant/adicionar swagger a todos os endpoints
  • Loading branch information
b4hia authored Oct 20, 2024
2 parents 23020fa + 7050a5d commit 81171c2
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 24 deletions.
9 changes: 7 additions & 2 deletions src/tupan/alertas/serializers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
from rest_framework import serializers
from .models import Alerta
from .models import Alerta, Medicao

class AlertaSerializer(serializers.ModelSerializer):
class Meta:
model = Alerta
fields = ('id', 'nome', 'condicao', 'estacao_parametro', 'criado', 'modificado', 'ativo')
read_only_fields = ['estacao_parametro']
read_only_fields = ['estacao_parametro']

class MedicaoSerializer(serializers.ModelSerializer):
class Meta:
model = Medicao
fields = ('id', 'timestamp', 'timestamp_convertido', 'dados', 'estacao_parametro')
25 changes: 13 additions & 12 deletions src/tupan/alertas/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from django.http import JsonResponse
import json
from estacoes.models import EstacaoParametro
from .serializers import AlertaSerializer
from .serializers import AlertaSerializer, MedicaoSerializer
from .models import Alerta, HistoricoAlerta, Medicao
from django.core.exceptions import ValidationError

Expand Down Expand Up @@ -141,19 +141,20 @@ def post(self, request, *args, **kwargs):
class MedicaoView(APIView):
def get(self, request, *args, **kwargs):
try:
medicoes = Medicao.objects.get()
return JsonResponse(list(medicoes), safe=False)
except:
return JsonResponse({'error': 'Erro ao buscar dados, tente novamente'}, status=500)
medicoes = Medicao.objects.all()
if not medicoes.exists():
return Response({"mensagem": "Nenhuma medição cadastrada"}, status=status.HTTP_404_NOT_FOUND)
serializer = MedicaoSerializer(medicoes, many=True)
return Response(serializer.data)
except Exception as e:
return Response({'error': f'Erro ao buscar dados, tente novamente {e}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class MedicaoDetalhesView(APIView):
def get(self, request, id, *args, **kwargs):
try:
alerta = Medicao.objects.filter(id=id, ativo=True).values().first()
if alerta:
return JsonResponse(alerta, safe=False)
else:
return JsonResponse({'error': 'Medição não encontrada ou inativa'}, status=404)
except:
return JsonResponse({'error': 'Erro ao buscar dados, tente novamente'}, status=500)
medicao = Medicao.objects.get(pk=id)
serializer = MedicaoSerializer(medicao)
return Response(serializer.data, status=status.HTTP_302_FOUND)
except Alerta.DoesNotExist:
return Response({'error': 'Erro ao buscar dados, tente novamente'}, status=status.HTTP_404_NOT_FOUND)
99 changes: 99 additions & 0 deletions src/tupan/estacoes/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,28 @@
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiResponse, OpenApiRequest, OpenApiTypes

class EstacoesView(APIView):
@extend_schema(
responses={
200: OpenApiResponse(EstacaoSerializer(many=True))
}
)
def get(self, request, *args, **kwargs):
ativo = request.query_params.get('ativo')
estacoes = Estacao.objects.all()
if (ativo):
estacoes = estacoes.filter(ativo=ativo)
serializer = EstacaoSerializer(estacoes, many=True)
return Response(serializer.data)
@extend_schema(
request=OpenApiRequest(EstacaoSerializer),
responses={
201: OpenApiResponse(EstacaoSerializer()),
400: OpenApiResponse(description="Erro na requisição")
}
)
def post(self, request, *args, **kwargs):
try:
endereco_instance = Endereco.objects.get(id=request.data["endereco"])
Expand Down Expand Up @@ -40,13 +53,29 @@ def post(self, request, *args, **kwargs):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class EstacoesDetalhesView(APIView):
@extend_schema(
responses={
200: OpenApiResponse(EstacaoSerializer()),
404: OpenApiResponse(description="Estação não encontrada")
}
)
def get(self, request, pk, *args, **kwargs):
try:
estacao = Estacao.objects.get(pk=pk)
except Estacao.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
serializer = EstacaoSerializer(estacao)
return Response(serializer.data)

@extend_schema(
request=OpenApiRequest(EstacaoSerializer()),
responses={
200: OpenApiResponse(EstacaoSerializer()),
400: OpenApiResponse(description="Erro na requisição"),
404: OpenApiResponse(description="Estação não encontrada")
}
)
def put(self, request, pk, *args, **kwargs):
try:
estacao = Estacao.objects.get(pk=pk)
Expand All @@ -65,6 +94,12 @@ def put(self, request, pk, *args, **kwargs):
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@extend_schema(
responses={
204: OpenApiResponse(description="Estação deletada com sucesso"),
404: OpenApiResponse(description="Estação não encontrada")
}
)
def delete(self, request, pk, *args, **kwargs):
try:
estacao = Estacao.objects.get(pk=pk)
Expand All @@ -75,10 +110,22 @@ def delete(self, request, pk, *args, **kwargs):
return Response(status=status.HTTP_204_NO_CONTENT)

class EnderecosView(APIView):
@extend_schema(
responses={
200: OpenApiResponse(EnderecoSerializer(many=True))
}
)
def get(self, request, *args, **kwargs):
enderecos = Endereco.objects.all()
serializer = EnderecoSerializer(enderecos, many=True)
return Response(serializer.data)
@extend_schema(
request=OpenApiRequest(EnderecoSerializer),
responses={
201: OpenApiResponse(EnderecoSerializer()),
400: OpenApiResponse(description="Erro na requisição")
}
)
def post(self, request, *args, **kwargs):
serializer = EnderecoSerializer(data=request.data)
if serializer.is_valid():
Expand All @@ -87,13 +134,27 @@ def post(self, request, *args, **kwargs):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class EnderecosDetalhesView(APIView):
@extend_schema(
responses={
200: OpenApiResponse(EnderecoSerializer()),
404: OpenApiResponse(description="Endereço não encontrado")
}
)
def get(self, request, pk, *args, **kwargs):
try:
endereco = Endereco.objects.get(pk=pk)
except Endereco.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
serializer = EnderecoSerializer(endereco)
return Response(serializer.data)
@extend_schema(
request=OpenApiRequest(EnderecoSerializer),
responses={
200: OpenApiResponse(EnderecoSerializer()),
404: OpenApiResponse(description="Endereço não encontrado"),
400: OpenApiResponse(description="Erro na requisição")
}
)
def put(self, request, pk, *args, **kwargs):
try:
endereco = Endereco.objects.get(pk=pk)
Expand All @@ -104,6 +165,12 @@ def put(self, request, pk, *args, **kwargs):
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@extend_schema(
responses={
204: OpenApiResponse(description="Endereço deletado com sucesso"),
404: OpenApiResponse(description="Endereço não encontrado")
}
)
def delete(self, request, pk, *args, **kwargs):
try:
endereco = Endereco.objects.get(pk=pk)
Expand All @@ -113,10 +180,22 @@ def delete(self, request, pk, *args, **kwargs):
return Response(status=status.HTTP_204_NO_CONTENT)

class ParametrosView(APIView):
@extend_schema(
responses={
200: OpenApiResponse(ParametroSerializer(many=True))
}
)
def get(self, request, *args, **kwargs):
parametros = Parametro.objects.all()
serializer = ParametroSerializer(parametros, many=True)
return Response(serializer.data)
@extend_schema(
request=OpenApiRequest(ParametroSerializer),
responses={
201: OpenApiResponse(ParametroSerializer()),
400: OpenApiResponse(description="Erro na requisição")
}
)
def post (self, request, *args, **kwargs):
serializer = ParametroSerializer(data=request.data)
if serializer.is_valid():
Expand All @@ -125,13 +204,27 @@ def post (self, request, *args, **kwargs):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ParametrosDetalhesView(APIView):
@extend_schema(
responses={
200: OpenApiResponse(ParametroSerializer()),
404: OpenApiResponse(description="Parâmetro não encontrado")
}
)
def get(self, request, pk, *args, **kwargs):
try:
parametro = Parametro.objects.get(pk=pk)
except Parametro.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
serializer = ParametroSerializer(parametro)
return Response(serializer.data)
@extend_schema(
request=OpenApiRequest(ParametroSerializer),
responses={
200: OpenApiResponse(ParametroSerializer()),
404: OpenApiResponse(description="Parâmetro não encontrado"),
400: OpenApiResponse(description="Erro na requisição")
}
)
def put(self, request, pk, *args, **kwargs):
try:
parametro = Parametro.objects.get(pk=pk)
Expand All @@ -142,6 +235,12 @@ def put(self, request, pk, *args, **kwargs):
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@extend_schema(
responses={
204: OpenApiResponse(description="Parâmetro deletado com sucesso"),
404: OpenApiResponse(description="Parâmetro não encontrado")
}
)
def delete(self, request, pk, *args, **kwargs):
try:
parametro = Parametro.objects.get(pk=pk)
Expand Down
4 changes: 2 additions & 2 deletions src/tupan/tupan/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
path('usuarios/', include('usuarios.urls')),
path('api-token-auth/', CustomAuthToken.as_view(), name='api_token_auth'),
path('usuarios', include('usuarios.urls')),
path('api-token-auth', CustomAuthToken.as_view(), name='api_token_auth'),
]
3 changes: 2 additions & 1 deletion src/tupan/usuarios/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
from usuarios.views import UsuarioList

urlpatterns = [
path('', UsuarioList.as_view())
path('', UsuarioList.as_view()),
path('/<int:pk>', UsuarioList.as_view())
]
40 changes: 33 additions & 7 deletions src/tupan/usuarios/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, AllowAny
from drf_spectacular.utils import extend_schema, OpenApiResponse, OpenApiParameter, OpenApiTypes

class UsuarioList(APIView):
"""
Expand All @@ -19,15 +20,27 @@ def get_permissions(self):
self.permission_classes = [IsAuthenticated]
return super().get_permissions()

@extend_schema(
description="Lista todos os usuários ativos",
responses={200: UsuarioSerializer(many=True), 404: OpenApiResponse(description="Nenhum usuário cadastrado")}
)
def get(self, request, format=None):
usuarios = Usuario.objects.all().filter(ativo=True)
if not usuarios.exists():
return Response({"mensagem": "Nenhum usuário cadastrado"}, status=status.HTTP_404_NOT_FOUND)
serializer = UsuarioSerializer(usuarios, many=True)
return Response(serializer.data)

def delete(self, request, format=None):
@extend_schema(
description="Deleta um usuário pelo seu id",
parameters=[
OpenApiParameter("pk", OpenApiTypes.INT, description="Id do usuário", required=True)
],
responses={200: UsuarioSerializer, 404: OpenApiResponse(description="Usuário não encontrado"), 400: OpenApiResponse(description="Erro na requisição")}
)
def delete(self, pk):
try:
id_usuario = request.data.get("id")
usuario = Usuario.objects.get(id=id_usuario)
usuario = Usuario.objects.get(pk=pk)
usuario.ativo = False
usuario.save()
serializer = UsuarioSerializer(usuario)
Expand All @@ -36,18 +49,31 @@ def delete(self, request, format=None):
return Response(status=status.HTTP_404_NOT_FOUND)
except Exception as e:
return Response({"message": str(e)}, status=status.HTTP_400_BAD_REQUEST)

def post(self, request, format=None):

@extend_schema(
description="Cria um novo usuário",
request=UsuarioSerializer,
responses={201: UsuarioSerializer, 400: OpenApiResponse(description="Erro na requisição")}
)
def post(self, request):
serializer = UsuarioSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def put(self, request, format=None):
@extend_schema(
description="Atualiza um usuário pelo seu id",
parameters=[
OpenApiParameter("pk", OpenApiTypes.INT, description="Id do usuário", required=True)
],
request=UsuarioSerializer,
responses={200: UsuarioSerializer, 404: OpenApiResponse(description="Usuário não encontrado"), 400: OpenApiResponse(description="Erro na requisição")}
)
def put(self, request, pk):
try:
new_data = request.data
user = Usuario.objects.get(id=new_data["id"])
user = Usuario.objects.get(pk=pk)
user.email = new_data["email"]
user.password = new_data["password"]
user.save()
Expand Down

0 comments on commit 81171c2

Please sign in to comment.