-
Notifications
You must be signed in to change notification settings - Fork 10
feat: Cria endpoint para criar Article a partir de PidProviderXML #1445
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
base: main
Are you sure you want to change the base?
Changes from 6 commits
d7d8adf
62edbcb
64165c3
77df7fc
20960e3
82e16b0
c9f8426
c1e81fd
b5b8dd1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,29 +1,32 @@ | ||
| import os | ||
| import logging | ||
| import os | ||
| import sys | ||
| from io import BytesIO | ||
| from zipfile import ZipFile | ||
|
|
||
| from tempfile import NamedTemporaryFile, TemporaryDirectory | ||
| from config.settings.base import TASK_EXPIRES, TASK_TIMEOUT, RUN_ASYNC | ||
|
|
||
| from article.models import Article | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @samuelveigarangel não ocorre dependÊncia circular? |
||
| from article.sources.xmlsps import load_article | ||
| from celery.exceptions import TimeoutError | ||
| from config.settings.base import RUN_ASYNC, TASK_EXPIRES, TASK_TIMEOUT | ||
| from core.utils.profiling_tools import ( | ||
| profile_endpoint, | ||
| profile_method, | ||
| ) # ajuste o import conforme sua estrutura | ||
| from django.utils import timezone | ||
| from pid_provider.models import PidProviderXML | ||
| from pid_provider.provider import PidProvider | ||
| from pid_provider.tasks import ( | ||
| task_delete_provide_pid_tmp_zip, | ||
| task_provide_pid_for_xml_zip, | ||
| ) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @samuelveigarangel fora do estilo recomendado de 3 blocos de import: nativas, externas, internas. |
||
| from rest_framework import serializers | ||
| from rest_framework import status as rest_framework_status | ||
| from rest_framework.mixins import CreateModelMixin | ||
| from rest_framework.parsers import FileUploadParser | ||
| from rest_framework.permissions import IsAuthenticated | ||
| from rest_framework.response import Response | ||
| from rest_framework.viewsets import GenericViewSet | ||
|
|
||
| from core.utils.profiling_tools import profile_endpoint, profile_method # ajuste o import conforme sua estrutura | ||
| from pid_provider.provider import PidProvider | ||
| from pid_provider.tasks import ( | ||
| task_delete_provide_pid_tmp_zip, | ||
| task_provide_pid_for_xml_zip, | ||
| ) | ||
| from tracker.models import UnexpectedEvent | ||
|
|
||
|
|
||
| STATUS_MAPPING = { | ||
| "created": rest_framework_status.HTTP_201_CREATED, | ||
| "updated": rest_framework_status.HTTP_200_OK, | ||
|
|
@@ -36,6 +39,15 @@ | |
| # TASK_QUEUE = "pid_provider" | ||
|
|
||
|
|
||
| class PublishedArticleRegistrationSerializer(serializers.Serializer): | ||
| pid_v3 = serializers.CharField( | ||
| required=True, allow_blank=False, max_length=23, min_length=23 | ||
| ) | ||
| sps_pkg_name = serializers.CharField( | ||
| required=True, allow_blank=False, max_length=100 | ||
| ) | ||
|
|
||
|
|
||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @samuelveigarangel manter o padrão, isso fica no arquiv serializers.py |
||
| class PidProviderViewSet( | ||
| GenericViewSet, # generic view functionality | ||
| CreateModelMixin, # handles POSTs | ||
|
|
@@ -294,3 +306,105 @@ def create(self, request): | |
| {"error_type": str(type(e)), "error_message": str(e)}, | ||
| status=rest_framework_status.HTTP_400_BAD_REQUEST, | ||
| ) | ||
|
|
||
|
|
||
| class PublishedArticleRegistrationViewSet(GenericViewSet): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @samuelveigarangel Era esperado que o código do endpoint fosse feito em article/api/v1/views. Além disso, não seria necessário criar uma nova classe. Pode usar a ArticleViewSet. Veja o exemplo hipotético. Por outro lado, se realmente ficar grande no @action(
detail=False,
methods=["post"],
permission_classes=[IsAuthenticated],
url_path="publish"
)
def publish_article(self, request):
"""
Busca o XML no pid_provider e realiza a publicação do Article.
URL: POST /api/v1/article/publish/
"""
serializer = PublishedArticleRegistrationSerializer(data=request.data)
if not serializer.is_valid():
return Response(serializer.errors, status=rest_framework_status.HTTP_400_BAD_REQUEST)
identifiers = serializer.validated_data
# 1. Busca o XML no pid_provider
try:
pp_xml = PidProviderXML.objects.select_related("current_version").get(
v3=identifiers["pid_v3"],
pkg_name=identifiers["sps_pkg_name"],
)
except PidProviderXML.DoesNotExist:
return Response({
"error": "PidProviderXML not found",
"pid_v3": identifiers["pid_v3"],
"sps_pkg_name": identifiers["sps_pkg_name"],
}, status=rest_framework_status.HTTP_404_NOT_FOUND)
# 2. Executa as regras de negócio de publicação do Article
try:
operation = (
"updated"
if models.Article.get_by_pid_v3_or_by_sps_pkg_name(
pid_v3=pp_xml.v3, sps_pkg_name=pp_xml.pkg_name
).exists()
else "created"
)
# Carrega, salva e valida a disponibilidade do artigo
article = load_article(request.user, pp_xml=pp_xml)
pp_xml.collections.set(article.collections)
article.check_availability(request.user)
except Exception as e:
logging.error(f"Erro ao publicar artigo: {e}", exc_info=True)
return Response(
{"error_type": str(type(e)), "error_message": str(e)},
status=rest_framework_status.HTTP_400_BAD_REQUEST
)
# 3. Log e Retorno
timestamp = timezone.now().isoformat()
logging.info(f"Article published: id={article.id} operation={operation} user={request.user.username}")
response_status = (
rest_framework_status.HTTP_201_CREATED
if operation == "created"
else rest_framework_status.HTTP_200_OK
)
return Response({
"article_id": article.id,
"pid_v3": article.pid_v3,
"sps_pkg_name": article.sps_pkg_name,
"operation": operation,
"data_status": article.data_status,
"is_public": article.is_public,
"timestamp": timestamp
}, status=response_status) |
||
| http_method_names = [ | ||
| "post", | ||
| ] | ||
| permission_classes = [IsAuthenticated] | ||
| serializer_class = PublishedArticleRegistrationSerializer | ||
|
|
||
| def create(self, request, *args, **kwargs): | ||
| serializer = self.get_serializer(data=request.data) | ||
| if not serializer.is_valid(): | ||
| return self.build_response(serializer.errors) | ||
|
|
||
| identifiers = serializer.validated_data | ||
| pp_xml = self.get_pid_provider_xml(identifiers) | ||
| if pp_xml is None: | ||
| return self.build_response( | ||
| data={ | ||
| "error": "PidProviderXML not found", | ||
| "pid_v3": identifiers["pid_v3"], | ||
| "sps_pkg_name": identifiers["sps_pkg_name"], | ||
| }, | ||
| status=rest_framework_status.HTTP_404_NOT_FOUND, | ||
| ) | ||
|
|
||
| try: | ||
| result = self.register_published_article_from_pid_provider_xml( | ||
| request.user, pp_xml | ||
| ) | ||
| except Exception as e: | ||
| logging.error( | ||
| f"Erro ao registrar artigo. Identificadores: {identifiers}. Exceção: {type(e).__name__}: {e}", | ||
| exc_info=True, | ||
| ) | ||
| return self.build_response( | ||
| { | ||
| "error_type": str(type(e)), | ||
| "error_message": str(e), | ||
| }, | ||
| ) | ||
|
|
||
| timestamp = timezone.now().isoformat() | ||
| logging.info( | ||
| f"Published article registration operation={result['operation']} " | ||
| f"pid_v3={identifiers['pid_v3']} " | ||
| f"sps_pkg_name={identifiers['sps_pkg_name']} " | ||
| f"article_id={result['article_id']} " | ||
| f"user={request.user.username} timestamp={timestamp}" | ||
| ) | ||
| return self.build_response( | ||
| data=self.build_response_data(result, timestamp), | ||
| status=self.get_response_status(result), | ||
| ) | ||
|
|
||
| def get_pid_provider_xml(self, identifiers): | ||
| try: | ||
| return PidProviderXML.objects.select_related("current_version").get( | ||
| v3=identifiers["pid_v3"], | ||
| pkg_name=identifiers["sps_pkg_name"], | ||
| ) | ||
| except PidProviderXML.DoesNotExist: | ||
| return None | ||
|
|
||
| def build_response(self, data, status=rest_framework_status.HTTP_400_BAD_REQUEST): | ||
| return Response(data, status=status) | ||
|
|
||
| def get_response_status(self, result): | ||
| if result["operation"] == "created": | ||
| return rest_framework_status.HTTP_201_CREATED | ||
| return rest_framework_status.HTTP_200_OK | ||
|
|
||
| def build_response_data(self, result, timestamp): | ||
| return {key: value for key, value in result.items() if key != "article"} | { | ||
| "timestamp": timestamp, | ||
| } | ||
|
|
||
| def register_published_article_from_pid_provider_xml(self, user, pp_xml): | ||
| pid_v3 = pp_xml.v3 | ||
| sps_pkg_name = pp_xml.pkg_name | ||
| operation = ( | ||
| "updated" | ||
| if Article.get_by_pid_v3_or_by_sps_pkg_name( | ||
| pid_v3=pid_v3, | ||
| sps_pkg_name=sps_pkg_name, | ||
| ).exists() | ||
| else "created" | ||
| ) | ||
| article = load_article(user, pp_xml=pp_xml) | ||
| pp_xml.collections.set(article.collections) | ||
|
|
||
| article.check_availability(user) | ||
|
|
||
| return { | ||
| "article": article, | ||
| "article_id": article.id, | ||
| "pid_v3": article.pid_v3, | ||
| "sps_pkg_name": article.sps_pkg_name, | ||
| "operation": operation, | ||
| "data_status": article.data_status, | ||
| "is_public": article.is_public, | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@samuelveigarangel troque published_article para publish_article, pois está fazendo uma ação e não uma obtenção de dado