def post_item_auto_schema(): return swagger_auto_schema( operation_id="create_item", operation_summary="Creates a new item type", operation_description="Creates a new item type in the database", request_body=Schema(type=TYPE_OBJECT, properties={ "itemType": generic_string_schema("truck", "type of item") }), responses={ "201": Schema( type=TYPE_OBJECT, properties={ "success": Schema( type=TYPE_OBJECT, properties={ "id": generic_string_schema( "14082c78-7a4d-451e-b41f-3ff8ab176939", "unique id"), "itemType": generic_string_schema("truck", "description"), }, ) }, ), }, )
def animals_auto_schema(): return swagger_auto_schema( operation_id="get_animals", operation_summary="List animals", operation_description="Lists all animals", responses={ "200": Schema( title="Success", type=TYPE_ARRAY, items=Schema( title="Success", type=TYPE_OBJECT, properties={ "test": generic_string_schema(example="test", description="test"), "test2": generic_string_schema(example="test2", description="test2"), }, ), ), "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 get_trucks_200_response() -> Schema: return Schema( title="Success", type=TYPE_ARRAY, items=Schema( title="Success", type=TYPE_OBJECT, properties={ "name": generic_string_schema(example="Saab", description="A swedish truck?"), "color": generic_string_schema(example="Yellow", description="The color of the truck."), "height": generic_string_schema(example="Medium height", description="How tall the truck is."), "width": generic_string_schema(example="Very wide", description="How wide the truck is."), "length": generic_string_schema(example="2 meters", description="How long the truck is."), }, ), )
def _build_ultimate_submission_result_schema(): ultimate_submission_schema = Schema( type='object', properties=copy.deepcopy(AGModelSchemaBuilder.get().get_schema( ag_models.Submission).properties)) assert (ultimate_submission_schema.properties is not AGModelSchemaBuilder.get().get_schema( ag_models.Submission).properties) ultimate_submission_schema.properties['results'] = Schema( type='object', properties=OrderedDict([ ('total_points', Schema(type='string(float)')), ('total_points_possible', Schema(type='string(float)')), ('ag_test_suite_results', Schema(type='AGTestSuiteResultFeedback', description='Only included if full_results is true.')), ('student_test_suite_results', Schema(type='StudentTestSuiteResultFeedback', description='Only included if full_results is true.')) ])) ultimate_submission_schema.properties.move_to_end('results', last=False) return Schema(type='object', properties=OrderedDict([ ('username', Schema(type='string')), ('group', AGModelSchemaBuilder.get().get_schema(ag_models.Group)), ('ultimate_submission', ultimate_submission_schema) ]))
def sample_move_substep_body(): return Schema( type='object', properties={ "sub": Schema(type='integer'), "new_position": Schema(type='integer') } )
def sample_switch_substeps_body(): return Schema( type='object', properties={ "sub1": Schema(type='integer'), "sub2": Schema(type='integer') } )
def sample_address_schema(): return Schema(type='object', properties={ 'city': Schema(type='string', default='Warszawa'), 'street': Schema(type='string', default='Miodowa'), 'street_number': Schema(type='integer', default='1'), 'postal_code': Schema(type='string', default='00-000') }, required=['city', 'street', 'street_number', 'postal_code'])
def sample_comment_request(required=True): return Schema(type='object', properties={ 'content': Schema(type='string', format='byte', default='base64-encoded-html-string') }, required=['content'] if required else [])
class FindView(APIView): """A view to find submissions or transcriptions by their URL.""" @csrf_exempt @swagger_auto_schema( manual_parameters=[ Parameter( "url", "query", type="string", description="The URL to find the object of. " "Can be a submission URL, a ToR submission URL or a transcription URL.", required=True, ), ], required=["url"], responses={ 200: DocResponse( "The URL has been found!", schema=Schema( type="object", # TODO: Use the schemas of the corresponding models properties={ "submission": Schema(type="object"), "author": Schema(type="object"), "transcription": Schema(type="object"), "ocr": Schema(type="object"), }, ), ), 400: "The given URL has an invalid format.", 404: "The corresponding submission/transcription could not be found.", }, ) def get(self, request: Request) -> Response: """Find the submission/transcription corresponding to the URL.""" url = request.query_params.get("url") normalized_url = normalize_url(url) if normalized_url is None: return Response(data="Invalid URL.", status=status.HTTP_400_BAD_REQUEST,) data = find_by_url(normalized_url) if data is None: return Response( data="No submission or transcription found for the given URL.", status=status.HTTP_404_NOT_FOUND, ) return Response( data=FindResponseSerializer(data, context={"request": request}).data, status=status.HTTP_200_OK, )
def resolve_schema(self, schema: Schema): if not (isinstance(schema, (Schema, SchemaRef)) or type(schema) == OrderedDict): return schema if isinstance(schema, SchemaRef): schema = schema.resolve(self.components) self.resolve_schema(schema) for key, value in schema.items(): if isinstance(value, Schema) or type(value) == OrderedDict: self.resolve_schema(value) elif isinstance(value, SchemaRef): schema[key] = value.resolve(self.components) self.resolve_schema(schema[key]) return schema
def sample_token_data_response(): return Schema( type='object', properties={ 'expiry': Schema(type='string', default='2020-05-19T00:19:35.265288+02:00'), 'token': Schema( type='string', default= '7ecb5e73d94f8a77e8f7bce87a777e459502709a59e2a35c27148fc16c23c3ds' ) })
def sample_login_response(account_type): response = Schema(properties={ 'expiry': Schema(type='string', default='2020-05-14T08:10:46.354741+02:00'), 'token': Schema( type='string', default= 'e9127a24c2e1300acb0afd8f4776343c59f2b9450369317086f421ce6c897ed6' ), 'type': Schema(type='string', default=account_type) }, type='object') return response
class SecondCategoryAPIView(APIView): permission_classes = [AllowAny] serializer_class = SecondCategoryPostSerializer @swagger_auto_schema( operation_description="post description override", request_body=SecondCategoryPostSerializer, responses={status.HTTP_200_OK: Schema(type=TYPE_OBJECT)}) def post(self, request): logger.info('First Category request data:{}'.format(request.data)) serializer = self.serializer_class(data=request.data) if serializer.is_valid(raise_exception=True): if Second_Category.objects.filter( name=serializer.validated_data['name'], firstcategory=serializer.validated_data['firstcategory'] ).exists(): return Response( { 'message': 'Name and Category already exist!', 'error': serializer.errors, }, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response( { 'message': 'An error occurred while processing yur request', 'error': serializer.errors, }, status=status.HTTP_400_BAD_REQUEST)
def _buid_minimal_handgrading_resuit_schema(): group_with_handgrading_result_schema = Schema( type='object', properties=copy.deepcopy(AGModelSchemaBuilder.get().get_schema(ag_models.Group).properties) ) assert (group_with_handgrading_result_schema.properties is not AGModelSchemaBuilder.get().get_schema(ag_models.Group).properties) group_with_handgrading_result_schema.properties['handgrading_result'] = Schema( title='MinimalHandgradingResult', type='object', description=('When this value is null, indicates that ' 'handgrading has not started for this group.'), properties=OrderedDict([ ('finished_grading', Schema( type='boolean', description="Indicates whether a human grader " "has finished grading this group's code.", )), ('total_points', Schema( type='float', )), ('total_points_possible', Schema( type='float', )), ]) ) return group_with_handgrading_result_schema
class VoivodeshipsEnumView(views.APIView): permission_classes = [AllowAny] @swagger_auto_schema( responses={ '200': Schema(type='object', properties={ "voivodeships": Schema(type='array', items=Schema(type='string', default=['w1', 'w2', '...'])) }) }, operation_description="Zwraca listę województw", ) def get(self, request): response = {"voivodeships": Voivodeships().getKeys()} return Response(response, status=status.HTTP_200_OK)
class PingView(APIView): """View to check whether the service is responsive.""" permission_classes = (AllowAny,) @csrf_exempt @swagger_auto_schema( responses={ 200: DocResponse( "Successful pong", schema=Schema( type="object", properties={"ping!": Schema(type="string")} ), ) } ) def get(self, request: Request, *args: object, **kwargs: object) -> Response: """Ping the server.""" return Response({"ping?!": "PONG"}, status=status.HTTP_200_OK)
def generic_error_response(error_description) -> Schema: return Schema( title="Error", type=TYPE_OBJECT, properties={ "error": generic_string_schema( error_description, "Generic Error response for all API endpoints") }, )
def post_item_auto_schema(): return swagger_auto_schema( operation_id='create_item', operation_summary='Creates a new item type', operation_description='Creates a new item type in the database', request_body=Schema(type=TYPE_OBJECT, properties={ 'itemType': generic_string_schema('truck', 'type of item') }), responses={ '201': Schema(type=TYPE_OBJECT, properties={ 'success': generic_string_schema('this is a response', 'description') }), }, )
class JobOfferTypesListView(views.APIView): permission_classes = [AllowAny] @swagger_auto_schema(responses={ '200': Schema(type='object', properties={ "offer_types": Schema(type='array', items=Schema(type='string', default=['t1', 't2', '...'])) }) }, operation_description="Zwraca listę wszystkich typów") def get(self, request): response = { "offer_types": list(JobOfferType.objects.values_list('name', flat=True)) } return Response(response, status=status.HTTP_200_OK)
class IncidentAPIView(APIView): """ APIView for creating Incident as a POST Request """ permission_classes = [AllowAny] serializer_class = IncidentPostSerializer @swagger_auto_schema( operation_description="partial_update description override", request_body=IncidentPostSerializer, responses={status.HTTP_200_OK: Schema(type=TYPE_OBJECT)}) def post(self, request): logger.info('Incident request data:{}'.format(request.data)) serializer = self.serializer_class(data=request.data) if serializer.is_valid(raise_exception=True): try: print('user Ip address a:' + request.META.get('HTTP_X_REAL_IP')) except: pass try: print('user Ip address b:' + request.headers['X-Real-IP']) except: pass client_ip_x = request.META['REMOTE_ADDR'] print('user Ip address:' + client_ip_x) client_ip = get_client_ip(request) geo_location_response = geolocation.geolocationClient.get_location( client_ip) print(geo_location_response) logger.info('geo_location_response response:{}'.format( geo_location_response)) data = serializer.validated_data if geo_location_response is not None: serializer.save( ip_address=client_ip, latitude=geo_location_response['latitude'], longitude=geo_location_response['longitude'], country_name=geo_location_response['country_name'], country_code=geo_location_response['country_code'], city=geo_location_response['city'], region=geo_location_response['region']) response = { 'status': '00', 'message': "Incident was created successfully " } logger.info('incident was created successfully') return Response(response, status=status.HTTP_200_OK) return Response( { 'message': 'An error occurred while processing yur request', 'error': serializer.errors, }, status=status.HTTP_400_BAD_REQUEST)
class RequestViewSet(viewsets.ViewSet): serializer_class = resident.RequestSerializer permission_classes = [AllowAny] @swagger_auto_schema(request_body=resident.RequestSerializer,responses={201: Schema(type=TYPE_OBJECT,request={'status':'success'})}) def create(self,request,*args, **kwargs): serializer = self.serializer_class(data=request.data,context = {'request': self.request} ) if serializer.is_valid(): track = serializer.save() response_data = {'status':'success'} return Response(response_data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class AdminConfirmJobOfferView(views.APIView): permission_classes = [IsStaffResponsibleForJobs] @swagger_auto_schema( manual_parameters=[ Parameter('offer_id', IN_PATH, type='string', format='byte') ], request_body=Schema(type='object', properties={'confirmed': Schema(type='boolean')}), responses={ '200': sample_message_response('Ustawiono potwierdzenie oferty pracy'), '400': sample_error_response('Oferta jest usunięta'), '401': 'No authorization token', '403': sample_error_response('Brak uprawnień do tej czynności'), '404': sample_error_response('Nie znaleziono oferty') }, operation_description="Ustawianie potwierdzenia ofert pracy", ) def post(self, request, offer_id): try: instance = JobOffer.objects.get(pk=offer_id) except ObjectDoesNotExist: return ErrorResponse("Nie znaleziono oferty", status.HTTP_404_NOT_FOUND) if instance.removed: return ErrorResponse("Oferta jest usunięta", status.HTTP_400_BAD_REQUEST) if 'confirmed' in request.data: confirmed = request.data['confirmed'] instance.confirmed = confirmed instance.save() notify.send(request.user, recipient=instance.employer.user, verb=f'Twoja oferta pracy została zatwierdzona', app='job/job-offer/', object_id=instance.id) return MessageResponse("Ustawiono potwierdzenie oferty pracy") return ErrorResponse("Błędy walidacji (np. brakujące pole)", status.HTTP_400_BAD_REQUEST)
def languages_auto_schema(): return swagger_auto_schema( operation_id="list_languages", operation_summary="List languages", operation_description="Lists all supported languages", responses={ "200": Schema( title="Success", type=TYPE_OBJECT, properties={ "languages": Schema( title="Success", type=TYPE_ARRAY, items=generic_string_schema( example="French", description="French language"), ) }, ), }, )
class FibonacciView(APIView): """ get: Return a list of fibonacci numbers """ responses = { 200: SchemaResponse( "Successful request", Schema(type=TYPE_ARRAY, items=Schema(type=TYPE_INTEGER)), ), 400: SchemaResponse("Invalid request"), } @swagger_auto_schema(query_serializer=SliceSerializer, responses=responses) def get(self, request): serializer = SliceSerializer(data=request.GET) serializer.is_valid(raise_exception=True) data = serializer.validated_data start = data["from"] end = data["to"] fibonacci_list = [fibonacci(n) for n in range(start, end)] return Response(fibonacci_list)
def _build_schema(api_class: APIType): title = API_MODELS[api_class] if issubclass(api_class, DictSerializableMixin): return api_class.get_schema(API_MODELS[api_class]) properties = OrderedDict() for field_name in api_class.get_serializable_fields(): field = _get_field(field_name, api_class) properties[field_name] = _build_api_parameter(field, field_name) return Schema(title=title, type='object', properties=properties, description=api_class.__doc__)
class ChangePasswordAPIView(APIView): """ Endpoint to Modified an authorize use password. """ permission_classes = (IsAuthenticated, ) serializer_class = PasswordChangeSerializer @swagger_auto_schema( operation_description="change user password", request_body=PasswordChangeSerializer, responses={status.HTTP_200_OK: Schema(type=TYPE_OBJECT)}) def post(self, request): logger.info('Change Password request data:{}'.format(request.data)) serializer = self.serializer_class(data=request.data) if serializer.is_valid(raise_exception=True): #check user password password = serializer.validated_data['new_password'] user = request.user logger.info('Change Password request user:{}'.format(user)) if user.check_password(password): return Response( { 'message': "Validation Error", 'status': '400', 'errors': 'Current Password can not be the same as old password', 'data': 'null' }, status=status.HTTP_400_BAD_REQUEST) else: user.set_password(password) user.save() return Response( { 'message': "Password was changed Successfully", 'status': '00', 'data': 'null' }, status=status.HTTP_200_OK) else: msgdetail = serializer.errors return Response( { 'message': "Invalid credentials", 'status': '00', 'errors': f"{msgdetail}", 'data': 'null' }, status=status.HTTP_400_BAD_REQUEST)
def sample_employer_account_request_schema(): return Schema(type='object', properties={ 'email': Schema(type='string', default='*****@*****.**'), 'username': Schema(type='string', default='username'), 'last_name': Schema(type='string', default='Snow'), 'first_name': Schema(type='string', default='Jon'), 'password': Schema(type='string', default='password'), 'phone_number': Schema(type='string', default='+48123456789'), 'nip': Schema(type='string'), 'company_name': Schema(type='string'), 'company_address': sample_address_schema(), }, required=[ 'email', 'username', 'password', 'last_name', 'first_name', 'phone_number', 'nip', 'company_name', 'company_address' ])
class Meta: swagger_schema_fields = { "type": TYPE_OBJECT, #"title": "Email", "properties": { "message": Schema( title="message", type=TYPE_STRING, ), "status": Schema( title="status", type=TYPE_INTEGER, ), "data": Schema( title="data", type=TYPE_OBJECT, ), "error": Schema( title="status", type=TYPE_STRING, ) }, # "required": ["subject", "body"], }
def get_schema(cls, title) -> Schema: """ Returns a schema for this class to be used in generating API documentation. """ properties = OrderedDict() for field_name in cls.get_serializable_fields(): properties[field_name] = Parameter( field_name, 'body', description=cls.get_field_descriptions().get(field_name, ''), type=cls.get_field_type(field_name).__name__, required=cls.field_is_required(field_name), default=cls.get_field_default(field_name)) return Schema(title=title, type='object', properties=properties)
class SummaryView(APIView): """A view to request the summary of statistics.""" permission_classes = (AdminApiKeyCustomCheck,) @csrf_exempt @swagger_auto_schema( responses={ 200: DocResponse( "Successful summary provision", schema=Schema( type="object", properties={ "volunteer_count": Schema(type="int"), "transcription_count": Schema(type="int"), "days_since_inception": Schema(type="int"), }, ), ) } ) def get(self, request: Request, *args: object, **kwargs: object) -> Response: """Get a summary of statistics on volunteers and transcriptions.""" return Response(data=Summary().generate_summary(), status=status.HTTP_200_OK)