def decorate(cls): for detail in swagger_details: method_name, op_id, op_decsr, tags, params = detail swagger_decorator = swagger_auto_schema( operation_id=op_id, operation_description=op_decsr, tags=tags, manual_parameters=params) dec = method_decorator(decorator=swagger_decorator, name=method_name) cls = dec(cls) return cls
def decorated_create_process_view(plugin_name, slug): # get process model proxy class cls = plugin_registry[plugin_name]._process_registry[slug] prefixed_slug = f"{plugin_name}.{slug}" """ Decorate the `create_process_endpoint` view with swagger schema properties defined by the plugin author """ @community_middleware @api_view(["POST"]) def create_process(request): # Look up plugin instance (throws if plugin is not installed for this community) # TODO(#50): change this to support multiple plugin instances of the same type plugin = get_plugin_instance(plugin_name, request.community) payload = JSONParser().parse(request) callback_url = payload.pop("callback_url", None) # pop to remove it # Start a new process process = plugin.start_process(slug, callback_url, **payload) # Return 202 with resource location in header response = HttpResponse(status=HTTPStatus.ACCEPTED) response[ "Location"] = f"/{utils.construct_process_url(plugin_name, slug)}/{process.pk}" return response request_body_schema = MetagovSchemas.json_schema_to_openapi_object( cls.input_schema) if cls.input_schema else {} return swagger_auto_schema( method="post", responses={ 202: "Process successfully started. Use the URL from the `Location` header in the response to get the status and outcome of the process." }, operation_id=f"Start {prefixed_slug}", tags=[Tags.GOVERNANCE_PROCESS], operation_description= f"Start a new governance process of type '{prefixed_slug}'", manual_parameters=[MetagovSchemas.community_header], request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ "callback_url": openapi.Schema( type=openapi.TYPE_STRING, description= "URL to POST outcome to when process is completed"), **request_body_schema.get("properties", {}), }, required=request_body_schema.get("required", []), ), )(create_process)
def get_other_trucks_auto_schema(): return swagger_auto_schema( operation_id="get_other_trucks", operation_summary="Lists other trucks", operation_description= "Lists all other trucks available in this test-project", responses={ "200": get_trucks_200_response(), "400": generic_error_response("Bad input. Error: {e}."), "401": generic_error_response("Bad credentials. Error: {e}."), "500": generic_error_response("Unexpected error raised when ..."), }, )
def decorator(klass): klass = method_decorator(name='list', decorator=swagger_auto_schema( operation_description="List all available finished tasks." " As a lecturer, you'll get finished tasks of all users, who has " "access to the same courses as you. " "As a student, you will get your finished tasks.", responses={200: 'All available finished tasks returned'}) )(klass) klass = method_decorator(name='retrieve', decorator=swagger_auto_schema( operation_description="Retrieve available finished task.", responses={ 200: 'Finished task retrieved.', 404: 'Could not retrieve available finished task by id provided.'}) )(klass) klass = method_decorator(name='partial_update', decorator=swagger_auto_schema( operation_description="Update available finished task. " "You can only set result as a lecturer", responses={ 200: 'Result updated.', 403: 'You are not allowed to modify finished tasks.', 404: 'Could not update available finished task by id provided.'}) )(klass) klass = method_decorator(name='update', decorator=swagger_auto_schema( operation_description="PUT method is not allowed.", responses={ 402: 'PUT is not allowed'}) )(klass) klass = method_decorator(name='destroy', decorator=swagger_auto_schema( operation_description="Delete available finished task." " Only students can delete their finished tasks", responses={ 204: 'Finished task deleted.', 403: 'You are not allowed to delete finished tasks.', 404: 'Could not delete available finished task by id provided.'}) )(klass) klass.get_queryset = _suppress_swagger_attribute_error(klass.get_queryset, model) klass.process_child = _copy_func(klass.process_child) klass.process_child = finished_tasks_comments_api_description(klass.process_child) return klass
class MyFollowing(generics.ListAPIView): serializer_class = FollowerSerializer def get_queryset(self): return Follower.objects.filter(is_followed_by=self.request.user).exclude(user=self.request.user) @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="Displays the users the current user is following" )) def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) queryset_page = paginator.paginate_queryset(queryset, request) serializer = self.get_serializer(queryset_page, many=True) return paginator.get_paginated_response(serializer.data)
class ActionMethod(object): user_test_schema = swagger_auto_schema( operation_description="List User 123", responses={ "201": openapi.Response(description="Created", examples={ 'application/json': { "message": "string", 'user_id': "string", } }) })
def get_other_trucks_auto_schema(): return swagger_auto_schema( operation_id='get_other_trucks', operation_summary='Lists other trucks', operation_description= 'Lists all other trucks available in this test-project', responses={ '200': get_trucks_200_response(), '400': generic_error_response('Bad input. Error: {e}.'), '401': generic_error_response('Bad credentials. Error: {e}.'), '500': generic_error_response('Unexpected error raised when ...'), }, )
class CommentList(generics.ListAPIView): permission_classes = (permissions.AllowAny,) serializer_class = PostSerializer @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="displays the list of comments related to the selected post" )) def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) def get_queryset(self): return Post.objects.filter(in_reply_to_post = self.kwargs["pk"])
def schema(view, methods: Sequence[Tuple[str, dict]]): """ drf-yasg's documentation helper function :param view: :param methods: :return: """ for method in methods: name = method[0] if name == "update": name = "partial_update" view = method_decorator( name=name, decorator=swagger_auto_schema(**method[1]))(view) return view
class RegisterDummyUserView(GenericAPIView): serializer_class = NoneSerializer permission_classes = () @method_decorator( decorator=swagger_auto_schema(responses={200: TokenSerializer})) def post(self, request): user = User.objects.create_guest_user() user.name = 'dummy user' user.save() serializer = TokenSerializer(data={'token': gen_jwt(user)}) serializer.is_valid(raise_exception=True) return Response(serializer.data)
def viewset_swagger_helper(public_actions=None, tags: Optional[List[str]] = None, **action_summary_docs: Optional[str]) -> Callable: """ A meta-decorator to apply swagger decorators for multiple methods. This decorator simplifies applying multiple decorators by applying sane defaults for swagger decorator, and passing in the supplied values as the summary. Example: @viewset_swagger_helper( list="List Snippets", create="Create new Snippet", destroy="Delete Snippet", public_actions=["list"] ) class SnippetViewSet(ModelViewSet): ... In the above example this function will apply a decorator that will override the operation summary for `list`, `create` and `destroy` for the `SnippetViewSet`. The `public_actions` parameter specifies which actions don't need an authentication and as such won't raise an authentication/authorization error. """ decorators_to_apply = [] public_actions = [] if public_actions is None else public_actions for action in [ 'list', 'create', 'retrieve', 'update', 'partial_update', 'destroy' ]: if action in action_summary_docs: decorators_to_apply.append( method_decorator( name=action, decorator=swagger_auto_schema( operation_summary=action_summary_docs.get(action), responses=VALIDATION_RESPONSE if action in public_actions else VALIDATION_AND_AUTH_RESPONSES, tags=tags, security=[] if action in public_actions else None, ), )) def inner(viewset): """ Applies all the decorators built up in the decorator list. """ for decorator in decorators_to_apply: viewset = decorator(viewset) return viewset return inner
def schema_inner(view_func): """ Decorate a view function with the specified schema. """ docstring_summary, docstring_description = split_docstring(view_func.__doc__) final_summary = summary or docstring_summary final_description = description or docstring_description or final_summary return swagger_auto_schema( request_body=body, manual_parameters=parameters, responses=responses, operation_summary=final_summary, operation_description=final_description, )(view_func)
def decorator(klass): klass = method_decorator(name='list', decorator=swagger_auto_schema( operation_description="List all available comments.", responses={200: 'All available comments returned'}) )(klass) klass = method_decorator(name='retrieve', decorator=swagger_auto_schema( operation_description="Retrieve available comment.", responses={ 200: 'Comment retrieved.', 404: 'Could not retrieve available comment by id provided.'}) )(klass) klass = method_decorator(name='update', decorator=swagger_auto_schema( operation_description="Update available comment." " Only author of the comment can modify it", responses={ 200: 'Comment updated.', 403: 'You are not allowed to modify this comment.', 404: 'Could not update available comment by id provided.'}) )(klass) klass = method_decorator(name='partial_update', decorator=swagger_auto_schema( operation_description="Update available hometask." " Only owner of the comment can modify it", responses={ 200: 'Comment updated.', 403: 'You are not allowed to modify this comment.', 404: 'Could not update available comment by id provided.'}) )(klass) klass = method_decorator(name='destroy', decorator=swagger_auto_schema( operation_description="Delete available comment. " "Only author of the comment can delete it", responses={ 204: 'Comment deleted.', 403: 'You are not allowed to delete this comment.', 404: 'Could not delete available comment by id provided.'}) )(klass) klass.get_queryset = _suppress_swagger_attribute_error(klass.get_queryset, model) return klass
def courses_users_api_description(func): func = swagger_auto_schema( operation_description="Add user to course.", method='post', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, title='User', properties={ 'pk': openapi.Schema(type=openapi.TYPE_INTEGER, description='Id of user to add', title='id') }, required=['pk'] ), responses={ 201: 'Added user to course.', 403: 'You are not allowed to add users to courses.', 400: 'User is already the member.', 404: 'Could not add user to available course by id provided.'})(func) func = swagger_auto_schema( operation_description="Delete user from course.", method='delete', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, title='User', properties={ 'pk': openapi.Schema(type=openapi.TYPE_INTEGER, description='Id of user to delete', title='id') }, required=['pk'] ), responses={ 204: 'Deleted student from course.', 403: 'You are not allowed to delete this user.', 404: 'Could not delete user from available course by id provided.'})(func) return func
def decorator(klass): klass = method_decorator(name='list', decorator=swagger_auto_schema( operation_description="List all available hometasks.", responses={200: 'All available hometasks returned'}) )(klass) klass = method_decorator(name='retrieve', decorator=swagger_auto_schema( operation_description="Retrieve available hometask.", responses={ 200: 'Hometask retrieved.', 404: 'Could not retrieve available hometask by id provided.'}) )(klass) klass = method_decorator(name='update', decorator=swagger_auto_schema( operation_description="Update available hometask.", responses={ 200: 'Hometask updated.', 403: 'You are not allowed to modify hometasks.', 404: 'Could not update available hometask by id provided.'}) )(klass) klass = method_decorator(name='partial_update', decorator=swagger_auto_schema( operation_description="Update available hometask.", responses={ 200: 'Hometask updated.', 403: 'You are not allowed to modify hometasks.', 404: 'Could not update available hometask by id provided.'}) )(klass) klass = method_decorator(name='destroy', decorator=swagger_auto_schema( operation_description="Delete available hometask.", responses={ 204: 'Hometask deleted.', 403: 'You are not allowed to delete hometasks.', 404: 'Could not delete available hometask by id provided.'}) )(klass) klass.get_queryset = _suppress_swagger_attribute_error(klass.get_queryset, model) klass.process_child = _copy_func(klass.process_child) klass.process_child = hometasks_finished_tasks_api_description(klass.process_child) return klass
class Followers(generics.ListAPIView): serializer_class = FollowerSerializer def get_queryset(self): user = get_object_or_404(get_user_model(), pk = self.kwargs["pk"]) return Follower.objects.filter(user = user).exclude(is_followed_by = user) @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="Displays the users following the selected user" )) def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) queryset_page = paginator.paginate_queryset(queryset, request) serializer = self.get_serializer(queryset_page, many=True) return paginator.get_paginated_response(serializer.data)
class ListCourseCategory(generics.ListAPIView): permission_classes = (permissions.AllowAny, ) queryset = Category.objects.all() serializer_class = CourseCategorySerializer @method_decorator( name='list', decorator=swagger_auto_schema( operation_description= "This shows the list of all course categories on the platform")) def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) queryset_page = paginator.paginate_queryset(queryset, request) paginator.page_size = 1000000 serializer = self.get_serializer(queryset_page, many=True) return paginator.get_paginated_response(serializer.data)
def __call__(self, func): mapping = getattr(func, 'mapping', {}) if any(method in mapping for method in ['put', 'patch', 'post', 'delete']): self.swagger_schema.setdefault('request_body', self.validator or self.klass) if self.klass: self.swagger_schema.setdefault( 'responses', {self.response_status: self.klass()}) func = swagger_auto_schema(**self.swagger_schema)(func) func.serializer_class = self.klass func.validator_class = self.validator return func
def get_organization_list_schema(): operation_description = 'Get a list of organizations' manual_parameters = ([documentation.get_page_manual_parameter()]) responses = { 200: openapi.Response('A list of zero or more organizations', OrganizationSerializer(many=True)), 404: 'Invalid page', } return swagger_auto_schema( operation_description=operation_description, manual_parameters=manual_parameters, responses=responses, )
def get_related_tasks_schema(): operation_description = 'Get a list tasks related to the given task, sorted by relatedness' responses = { 200: openapi.Response( 'A list of zero or more related tasks', RelatedTaskSerializer(many=True), ), 404: 'invalid page', } return swagger_auto_schema( operation_description=operation_description, responses=responses, )
def post_vehicle_auto_schema(): return swagger_auto_schema( operation_id="create_vehicle", operation_summary="Creates a new vehicle type", operation_description="Creates a new vehicle type in the database", request_body=VehicleSerializer, responses={ "201": Schema(type=TYPE_OBJECT, properties={ "success": generic_string_schema("this is a response", "description") }), }, )
def post_vehicle_auto_schema(): return swagger_auto_schema( operation_id='create_vehicle', operation_summary='Creates a new vehicle type', operation_description='Creates a new vehicle type in the database', request_body=VehicleSerializer, responses={ '201': Schema(type=TYPE_OBJECT, properties={ 'success': generic_string_schema('this is a response', 'description') }), }, )
def decorated_enable_plugin_view(plugin_name): """ Decorate the `enable_plugin` view with swagger schema properties defined by the plugin author """ cls = plugin_registry[plugin_name] @community_middleware @api_view(["POST"]) def enable_plugin(request): plugin_config = JSONParser().parse(request) # Create or re-create the plugin (only one instance per community supported for now!) plugin, created = core_utils.create_or_update_plugin( plugin_name, plugin_config, request.community) # Serialize and return the Plugin instance serializer = PluginSerializer(plugin) resp_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK return JsonResponse(serializer.data, status=resp_status) request_body_schema = MetagovSchemas.json_schema_to_openapi_object( cls.config_schema) if cls.config_schema else {} return swagger_auto_schema( method="post", responses={ 201: openapi.Response( "Plugin enabled", PluginSerializer, ), 200: openapi.Response( "The Plugin was already enabled. Plugin was updated if the config changed.", PluginSerializer, ), }, operation_id=f"Enable {plugin_name}", tags=[Tags.COMMUNITY], operation_description=f"Enable {plugin_name} plugin.", manual_parameters=[MetagovSchemas.community_header], request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ **request_body_schema.get("properties", {}), }, required=request_body_schema.get("required", []), ), )(enable_plugin)
def get_snake_cased_response(): return swagger_auto_schema( operation_id="get_snake_cased_response", operation_summary="Returns a snake-cased response", operation_description="..", responses={ "200": Schema( title="Success", type=TYPE_OBJECT, properties={ "this_is_snake_case": generic_string_schema(example="test", description="test"), }, ), }, )
def exclude_schema(view_func): """ Decorate an API-endpoint-handling function to exclude it from the API docs. Example:: class MyView(APIView): @schema(...) def get(...): pass @exclude_schema def post(...): pass """ return swagger_auto_schema(auto_schema=None)(view_func)
class ListUser(generics.ListAPIView): permission_classes = (permissions.AllowAny,) queryset = get_user_model().objects.all() serializer_class = ListUserSerializer filter_backends = (filters.SearchFilter, filters.OrderingFilter) search_fields = ('username', 'profile__first_name', 'profile__last_name') ordering_fields = ('profile__follower_count', 'profile__following_count') @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="This shows the list of all users on the platform (lighter)" )) def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) queryset_page = paginator.paginate_queryset(queryset, request) serializer = self.get_serializer(queryset_page, many=True) return paginator.get_paginated_response(serializer.data)
class JobView(viewsets.ModelViewSet): # add this serializer_class = JobSerializer # add this queryset = Job.objects.all() # add this # ordering_fields = '__all__' @method_decorator(name='list', decorator=swagger_auto_schema( tags=TAG_NAME, responses={200: OutreachSerializer(many=True)})) @action(detail=True, methods=['get']) def outreach_list(self, request, pk=None): j = self.get_object() # retrieve an object by pk provided outreaches = Outreach.objects.filter( job=j).distinct().order_by('-created') outreaches_json = OutreachSerializer(outreaches, many=True) return Response(outreaches_json.data)
class ListCourse(generics.ListAPIView): permission_classes = (permissions.AllowAny, ) queryset = Course.objects.all() serializer_class = CourseSerializer filter_backends = (filters.SearchFilter, filters.OrderingFilter) search_fields = ('title', 'overview', 'category__title') ordering_fields = ('title', 'created') @method_decorator(name='list', decorator=swagger_auto_schema( operation_description= "This shows the list of all courses on the platform") ) def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) queryset_page = paginator.paginate_queryset(queryset, request) serializer = self.get_serializer(queryset_page, many=True) return paginator.get_paginated_response(serializer.data)
class RegisterUserView(GenericAPIView): serializer_class = UserSignUpSerializer permission_classes = () @method_decorator( decorator=swagger_auto_schema(responses={200: TokenSerializer})) def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = User.objects.create_user( email=serializer.validated_data["email"], password=serializer.validated_data["password"]) user.save() serializer = TokenSerializer(data={'token': gen_jwt(user)}) serializer.is_valid(raise_exception=True) return Response(serializer.data)
class UserPasswordView(GenericAPIView): serializer_class = UserPasswordSerializer @method_decorator( decorator=swagger_auto_schema(responses={200: TokenSerializer})) def put(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = self.request.user if not user.check_password(serializer.validated_data["password"]): return Response({"passowrd": "password not matched"}) user.set_password(serializer.validated_data["new_password"]) user.save() return Response({"token": gen_jwt(user)})
@method_decorator(name='list', decorator=swagger_auto_schema( operation_description="Return list of projects based on given query string", manual_parameters=[ openapi.Parameter( name='id', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="Id of a project", ), openapi.Parameter( name='published', in_=openapi.IN_QUERY, type=openapi.TYPE_BOOLEAN, description="Published status of a project", ), openapi.Parameter( name='lang', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="A language slug", ), openapi.Parameter( name='version', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="A version slug", ), openapi.Parameter( name='book', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="A book slug", ), openapi.Parameter( name='mode', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="A mode slug", ), openapi.Parameter( name='anth', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="An anthology slug", ), ] ))
from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from django.core.exceptions import SuspiciousOperation @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="Return list of books based on given query string", manual_parameters=[ openapi.Parameter( name='id', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="Id of a book", ), openapi.Parameter( name='slug', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="A book slug", ), openapi.Parameter( name='anth', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="An anthology slug", ), openapi.Parameter( name='num', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="A book number", ), ] )) class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,)
from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import viewsets @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="Return list of file names with md5 hash value based on given query string", manual_parameters=[ openapi.Parameter( name='lang', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="A language slug", ), openapi.Parameter( name='anth', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="A anthology slug", ), openapi.Parameter( name='version', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="A version slug", ), openapi.Parameter( name='book', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="A book slug", ) ] )) class ExcludeFilesViewSet(viewsets.ReadOnlyModelViewSet): queryset = Take.objects.all() serializer_class = ExcludeFilesSerializer def build_params_filter(self, query):
from rest_framework.permissions import IsAuthenticated @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="Return list of takes based on given query string", manual_parameters=[ openapi.Parameter( name='id', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="Id of a take", ), openapi.Parameter( name='published', in_=openapi.IN_QUERY, type=openapi.TYPE_BOOLEAN, description="Published status of a take", ), openapi.Parameter( name='project_id', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="Id of a project", ), openapi.Parameter( name='chapter_id', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="Id of a chapter", ), openapi.Parameter( name='chunk_id', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="Id of a chunk", ) ] )) @method_decorator(name='partial_update', decorator=swagger_auto_schema( operation_description='This end point is used for updating rating or published status of a take', request_body=openapi.Schema(
from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import viewsets from api.serializers import ModeSerializer from django.core.exceptions import SuspiciousOperation from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="Return list of modes based on given query string", manual_parameters=[ openapi.Parameter( name='id', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="Id of a mode", ), openapi.Parameter( name='slug', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="A mode slug", ) ] )) class ModeViewSet(viewsets.ModelViewSet): queryset = Mode.objects.all() serializer_class = ModeSerializer permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) def build_params_filter(self, query): pk = query.get("id", None) slug = query.get("slug", None)
from drf_yasg.utils import swagger_auto_schema from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from django.core.exceptions import SuspiciousOperation @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="Return list of chunks based on given query string", manual_parameters=[ openapi.Parameter( name='id', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="Id of a chunk", ), openapi.Parameter( name='project_id', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="Id of a project", ), openapi.Parameter( name='chapter_id', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="Id of a chapter", ) ] )) class ChunkViewSet(viewsets.ModelViewSet): queryset = Chunk.objects.all() serializer_class = ChunkSerializer permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) def build_params_filter(self, query):
from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response @method_decorator(name='retrieve', decorator=swagger_auto_schema( operation_description="Downloads the project based on given project id and file format", manual_parameters=[ openapi.Parameter( name='id', in_=openapi.IN_PATH, type=openapi.TYPE_INTEGER, description="Id of a project", ), openapi.Parameter( name='chapters', in_=openapi.IN_PATH, type=openapi.TYPE_ARRAY, items=openapi.Items(type=openapi.TYPE_INTEGER), description="Filter by chapters", ), openapi.Parameter( name='file_format', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="It can be 'mp3' or 'wav'", ) ] )) class ExportViewSet(viewsets.ReadOnlyModelViewSet): queryset = Take.objects.all() serializer_class = TakeForZipSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,)
from rest_framework import viewsets from api.serializers import TakeForZipSerializer from api.file_transfer.ArchiveIt import ArchiveIt from api.file_transfer.AudioUtility import AudioUtility from api.file_transfer.Download import Download from api.file_transfer.FileUtility import FileUtility from rest_framework.response import Response @method_decorator(name='retrieve', decorator=swagger_auto_schema( operation_description="Downloads a source project based on given project id", manual_parameters=[ openapi.Parameter( name='id', in_=openapi.IN_PATH, type=openapi.TYPE_INTEGER, description="Id of a project", ) ] )) class TrViewSet(viewsets.ReadOnlyModelViewSet): queryset = Take.objects.all() serializer_class = TakeForZipSerializer def retrieve(self, request, *args, **kwargs): return self.list(self, request, *args, **kwargs) def list(self, request, *args, **kwargs): id = self.request.query_params.get('id') if id is None: id = kwargs.get("pk", None)
from rest_framework.response import Response from api.permissions import CanCreateOrDestroyOrReadonly from api.models.user import User from api.serializers import UserSerializer @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="Return list of users based on given query string", manual_parameters=[ openapi.Parameter( name='id', in_=openapi.IN_QUERY, type=openapi.TYPE_INTEGER, description="Id of a user", ), openapi.Parameter( name='icon_hash', in_=openapi.IN_QUERY, type=openapi.TYPE_STRING, description="Icon hash of a user", ), openapi.Parameter( name='is_social', in_=openapi.IN_QUERY, type=openapi.TYPE_BOOLEAN, description="Social status of a user. Whether a user was created via social media or identicon.", ) ] )) class UserViewSet(viewsets.ModelViewSet): """This class handles the http GET, PUT, PATCH, POST and DELETE requests.""" queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (CanCreateOrDestroyOrReadonly,) authentication_classes = (TokenAuthentication,)