Example #1
0
class FilterPolygonsAPIView(APIView):
    schema = AutoSchema(
        manual_fields=[
            coreapi.Field(
                "latitude",
                required=True,
                schema=coreschema.Number(),
                description='Please provide latitude for filter'
            ),
            coreapi.Field(
                "longitude",
                required=True,
                schema=coreschema.Number(),
                description='Please provide longitude for filter'
            ),
        ]
    )
    serializer_class = FilterPolygonsSerializer

    def get(self, request):

        serializer = self.serializer_class(data=request.query_params)

        serializer.is_valid(raise_exception=True)
        response = serializer.filter_polygons(serializer.validated_data)

        return Response(response, status=status.HTTP_200_OK)
Example #2
0
class ServiceAreaViewSet(viewsets.ModelViewSet):
    permission_classes = (ServiceAreaPermissions, )
    queryset = ServiceArea.objects
    instance_class = ServiceArea
    lookup_field = '_id'

    schema = MongoSchema(manual_fields=[
        MethodField(
            "body",
            required=True,
            location="body",
            schema=coreschema.Object(),
            methods=['POST', 'PUT', 'PATCH'],
        ),
        MethodField(
            "lat",
            required=False,
            location="query",
            schema=coreschema.Number(),
            methods=['GET'],
        ),
        MethodField(
            "lng",
            required=False,
            location="query",
            schema=coreschema.Number(),
            methods=['GET'],
        ),
    ])

    def filter_queryset(self, queryset):
        if 'lat' in self.request.query_params and 'lng' in self.request.query_params:
            lat = float(self.request.query_params['lat'])
            lng = float(self.request.query_params['lng'])

            return queryset.raw({
                'geometry': {
                    '$geoIntersects': {
                        '$geometry': {
                            'type': 'Point',
                            'coordinates': [lat, lng]
                        }
                    }
                }
            })
        else:
            return queryset

    def perform_create(self, instance):
        instance.user_id = self.request.user.pk
        super(ServiceAreaViewSet, self).perform_create(instance)
Example #3
0
def _annotated_type_to_coreschema(
        annotated_type: type) -> coreschema.schemas.Schema:
    if annotated_type is bool or issubclass(annotated_type, schema.Boolean):
        return coreschema.Boolean()
    elif annotated_type is int or issubclass(annotated_type, schema.Integer):
        return coreschema.Integer()
    elif annotated_type is float or issubclass(annotated_type, schema.Number):
        return coreschema.Number()

    return coreschema.String()
Example #4
0
def get_param_schema(annotated_type: typing.Type) -> coreschema.schemas.Schema:
    if issubclass(annotated_type, (bool, typesystem.Boolean)):
        return coreschema.Boolean()
    elif issubclass(annotated_type, int):
        return coreschema.Integer()
    elif issubclass(annotated_type, float):
        return coreschema.Number()
    elif issubclass(annotated_type, typesystem.Enum):
        enum = typing.cast(typing.Type[typesystem.Enum], annotated_type)
        return coreschema.Enum(enum=enum.enum)
    return coreschema.String()
Example #5
0
def get_param_schema(annotated_type: typing.Type) -> coreschema.schemas.Schema:
    schema_kwargs = {'description': getattr(annotated_type, 'description', '')}

    if issubclass(annotated_type, (bool, typesystem.Boolean)):
        return coreschema.Boolean(**schema_kwargs)
    elif issubclass(annotated_type, int):
        return coreschema.Integer(**schema_kwargs)
    elif issubclass(annotated_type, float):
        return coreschema.Number(**schema_kwargs)
    elif issubclass(annotated_type, typesystem.Enum):
        enum = typing.cast(typing.Type[typesystem.Enum], annotated_type)
        return coreschema.Enum(enum=enum.enum, **schema_kwargs)
    return coreschema.String(**schema_kwargs)
Example #6
0
def _annotated_type_to_coreschema(
        annotated_type: type) -> coreschema.schemas.Schema:
    if annotated_type is bool or issubclass(annotated_type, schema.Boolean):
        return coreschema.Boolean()
    elif annotated_type is int or issubclass(annotated_type, schema.Integer):
        return coreschema.Integer()
    elif annotated_type is float or issubclass(annotated_type, schema.Number):
        return coreschema.Number()
    elif issubclass(annotated_type, schema.Enum):
        enum = cast(Type[schema.Enum], annotated_type)
        return coreschema.Enum(enum=enum.enum)

    return coreschema.String()
Example #7
0
    def get_coreschema_field(self, field):
        description = six.text_type(field.extra.get('help_text', ''))

        if isinstance(field, filters.NumberFilter):
            return coreschema.Number(description=description)
        elif isinstance(field, filters.MultipleChoiceFilter):
            return coreschema.Array(
                items=coreschema.Enum(enum=[c[0]
                                            for c in field.field.choices]),
                description=description,
                unique_items=True,
            )
        elif isinstance(field, filters.ChoiceFilter):
            return coreschema.Enum(enum=[c[0] for c in field.field.choices],
                                   description=description)
        else:
            return coreschema.String(description=description)
Example #8
0
    def get_schema(self):
        if self.dtype == str:
            return coreschema.String(description=self.description)

        elif self.dtype == bool:
            return coreschema.Boolean(description=self.description)

        elif self.dtype == int:
            return coreschema.Integer(description=self.description)
        elif self.dtype == float:
            return coreschema.Number(description=self.description)

        elif self.dtype == list:
            return coreschema.Array(description=self.description)

        else:
            raise TypeError("Parameter must have type.")
Example #9
0
    def field_to_schema(self, field):
        import coreschema
        import django.forms as django_forms
        from django.utils.encoding import force_str
        title = force_str(field.label) if field.label else ''
        description = force_str(field.help_text) if field.help_text else ''

        schema = None

        if isinstance(field, django_forms.MultipleChoiceField):
            schema = coreschema.Array(
                items=coreschema.Enum(enum=list(field.choices)),
                title=title,
                description=description)
        elif isinstance(field, django_forms.ChoiceField) and not isinstance(
                field, django_forms.ModelChoiceField):
            choices = list(
                map(
                    lambda choice: choice[0]
                    if isinstance(choice, tuple) else choice, field.choices))
            choices.remove('')
            schema = coreschema.Enum(enum=choices,
                                     title=title,
                                     description=description)
        elif isinstance(field, django_forms.BooleanField):
            schema = coreschema.Boolean(title=title, description=description)
        elif isinstance(field,
                        (django_forms.DecimalField, django_forms.FloatField)):
            schema = coreschema.Number(title=title, description=description)
        elif isinstance(field, django_forms.IntegerField):
            schema = coreschema.Integer(title=title, description=description)
        elif isinstance(field, django_forms.DateField):
            schema = coreschema.String(title=title,
                                       description=description,
                                       format='date')
        elif isinstance(field, django_forms.DateTimeField):
            schema = coreschema.String(title=title,
                                       description=description,
                                       format='date-time')
        elif isinstance(field, django_forms.JSONField):
            schema = coreschema.Object(title=title, description=description)

        return schema or coreschema.String(title=title,
                                           description=description)
Example #10
0
expected = Schema(url='/schema/', content={
    'list_todo': Link(
        url='/todo/',
        action='GET',
        description='list_todo description',
        fields=[Field(name='search', location='query', required=False, schema=coreschema.String())]
    ),
    'add_todo': Link(
        url='/todo/',
        action='POST',
        description='add_todo description\nMultiple indented lines',
        fields=[
            Field(name='id', required=False, location='form', schema=coreschema.Integer()),
            Field(name='text', required=False, location='form', schema=coreschema.String()),
            Field(name='complete', required=False, location='form', schema=coreschema.Boolean()),
            Field(name='percent_complete', required=False, location='form', schema=coreschema.Number()),
            Field(name='category', required=False, location='form', schema=coreschema.Enum(enum=['shop', 'chore']))
        ]
    ),
    'show_todo': Link(
        url='/todo/{ident}/',
        action='GET',
        fields=[Field(name='ident', location='path', required=True, schema=coreschema.Integer())]
    ),
    'set_complete': Link(
        url='/todo/{ident}/',
        action='PUT',
        fields=[
            Field(name='ident', location='path', required=True, schema=coreschema.Integer()),
            Field(name='complete', location='query', required=False, schema=coreschema.Boolean())
        ]
Example #11
0
# Data filter
date_gte_filter = Filter(
    name="date_gte",
    query_filter="date_created__gte",
    schema=coreschema.String(title="Start date", description="Start date."),
)

date_lte_filter = Filter(
    name="date_lte",
    query_filter="date_created__lte",
    schema=coreschema.String(title="End date", description="End date."),
)

date_filter = FiltersGroup(date_gte_filter, date_lte_filter)

# Amount filter
amount_gte_filter = Filter(
    name="amount_gte",
    query_filter="amount__gte",
    schema=coreschema.String(title="Min amount", description="Min amount."),
)

amount_lte_filter = Filter(
    name="amount_lte",
    query_filter="amount__lte",
    schema=coreschema.Number(title="Max amount", description="Max amount."),
)

amount_filter = FiltersGroup(date_gte_filter, date_lte_filter)
Example #12
0
class ApiItems(generics.ListAPIView):
    """
        Return a list of items filtered by given parameter.
    """
    schema = schemas.AutoSchema(manual_fields=[
        coreapi.Field(
            "search-token",
            required=False,
            location="query",
            schema=coreschema.String(
                description='Search for the token in each title of an item'),
        ),
        coreapi.Field(
            "type",
            required=False,
            location="query",
            schema=coreschema.Integer(
                description='int value that represents the type'),
        ),
        coreapi.Field(
            "lender",
            required=False,
            location="query",
            schema=coreschema.String(description='array of lender ids'),
        ),
        coreapi.Field(
            "min-amount",
            required=False,
            location="query",
            schema=coreschema.Integer(
                description='minimal amount of an object item'),
        ),
        coreapi.Field(
            "max-weight",
            required=False,
            location="query",
            schema=coreschema.Number(
                description='max weight of an object item in kg', ),
        ),
        coreapi.Field(
            "categories",
            required=False,
            location="query",
            schema=coreschema.String(description='array of category ids', ),
        ),
        coreapi.Field(
            "max-caution",
            required=False,
            location="query",
            schema=coreschema.Number(description='maximal caution in €', ),
        ),
        coreapi.Field(
            "max-single-rent",
            required=False,
            location="query",
            schema=coreschema.Number(description='maximal single rent in €', ),
        ),
        coreapi.Field(
            "max-rental-fee-costs",
            required=False,
            location="query",
            schema=coreschema.Number(
                description='maximal rental fee costs in €', ),
        ),
        coreapi.Field(
            "rental-fee-interval",
            required=False,
            location="query",
            schema=coreschema.Number(
                description='int representation of an rental fee interval', ),
        ),
        coreapi.Field(
            "min-height",
            required=False,
            location="query",
            schema=coreschema.Number(
                description='min height of an object or location item in meter',
            ),
        ),
        coreapi.Field(
            "max-height",
            required=False,
            location="query",
            schema=coreschema.Number(
                description='max height of an object or location item in meter',
            ),
        ),
        coreapi.Field(
            "min-width",
            required=False,
            location="query",
            schema=coreschema.Number(
                description='min width of an object or location item in meter',
            ),
        ),
        coreapi.Field(
            "max-width",
            required=False,
            location="query",
            schema=coreschema.Number(
                description='max width of an object or location item in meter',
            ),
        ),
        coreapi.Field(
            "min-depth",
            required=False,
            location="query",
            schema=coreschema.Number(
                description='min depth of an object or location item in meter',
            ),
        ),
        coreapi.Field(
            "max-depth",
            required=False,
            location="query",
            schema=coreschema.Number(
                description='max depth of an object or location item in meter',
            ),
        ),
        coreapi.Field(
            "start-date",
            required=False,
            location="query",
            schema=coreschema.String(
                description=
                'needed for occupancy search. format = %Y-%m-%d. Requires: end-date field',
            ),
        ),
        coreapi.Field(
            "end-date",
            required=False,
            location="query",
            schema=coreschema.String(
                description=
                'needed for occupancy search. format = %Y-%m-%d. Requires: start-date field',
            ),
        ),
        coreapi.Field(
            "house-number",
            required=False,
            location="query",
            schema=coreschema.Integer(
                description=
                'needed for bounding box search. Requires: street, city, distance field',
            ),
        ),
        coreapi.Field(
            "street",
            required=False,
            location="query",
            schema=coreschema.String(
                description=
                'needed for bounding box search. Requires: house-number, city, distance field',
            ),
        ),
        coreapi.Field(
            "city",
            required=False,
            location="query",
            schema=coreschema.String(
                description=
                'needed for radius based search. Requires: house-number, street, distance field',
            ),
        ),
        coreapi.Field(
            "distance",
            required=False,
            location="query",
            schema=coreschema.String(
                description=
                'needed for radius based search. Requires: house-number, street, city field',
            ),
        ),
    ])

    def get_serializer_class(self):
        type = self.request.query_params.get('data-type')
        if type == 'map':
            return ExtendedItemSerializer
        return MinimalItemSerializer

    def get_queryset(self):
        queryset = Item.objects.all()
        search_token = self.request.query_params.get('search-token')
        if search_token:
            queryset = queryset.filter(title__icontains=search_token)
        type = self.request.query_params.get('type')
        if type:
            queryset = queryset.filter(type=type)
        lenders = self.request.query_params.getlist('lender')
        if lenders:
            queryset = queryset.filter(lender__in=lenders)
        min_amount = self.request.query_params.get('min-amount')
        if min_amount:
            queryset = queryset.filter(amount__gte=min_amount)
        max_weight = self.request.query_params.get('max-weight')
        if max_weight:
            queryset = queryset.filter(weight__lte=max_weight)
        categories = self.request.query_params.getlist('categories')
        if categories:
            for category in categories:
                queryset = queryset.filter(categories__id=category)

        max_caution = self.request.query_params.get('max-caution')
        max_single_rent = self.request.query_params.get('max-single-rent')
        max_rental_fee_costs = self.request.query_params.get(
            'max-rental-fee-costs')
        rental_fee_interval = self.request.query_params.get(
            'rental-fee-interval')
        if max_caution:
            queryset = queryset.filter(loan__caution__lte=max_caution)
        if max_single_rent:
            queryset = queryset.filter(loan__single_rent__lte=max_single_rent)
        if max_rental_fee_costs:
            queryset = queryset.filter(
                loan__rental_fee__costs__lte=max_rental_fee_costs)
        if rental_fee_interval:
            queryset = queryset.filter(
                loan__rental_fee__interval_unit=int(rental_fee_interval))

        min_height = self.request.query_params.get('min-height')
        max_height = self.request.query_params.get('max-height')
        min_width = self.request.query_params.get('min-width')
        max_width = self.request.query_params.get('max-width')
        min_depth = self.request.query_params.get('min-depth')
        max_depth = self.request.query_params.get('max-depth')
        if max_height:
            queryset = queryset.filter(dimension__height__lte=max_height)
        if max_width:
            queryset = queryset.filter(dimension__width__lte=max_width)
        if max_depth:
            queryset = queryset.filter(dimension__depth__lte=max_depth)

        if min_height:
            queryset = queryset.filter(dimension__height__gte=min_height)
        if min_width:
            queryset = queryset.filter(dimension__width__gte=min_width)
        if min_depth:
            queryset = queryset.filter(dimension__depth__gte=min_depth)

        start_date = self.request.query_params.get('start-date')
        end_date = self.request.query_params.get('end-date')

        if start_date and end_date:
            start_date_obj = datetime.strptime(start_date,
                                               '%Y-%m-%d').replace(hour=23,
                                                                   minute=59)
            end_date_obj = datetime.strptime(end_date,
                                             '%Y-%m-%d').replace(hour=23,
                                                                 minute=59)
            queryset = queryset.filter(
                (Q(occupancies__start_time__gt=start_date_obj)
                 & Q(occupancies__start_time__gt=end_date_obj))
                | (Q(occupancies__end_time__lt=start_date_obj)
                   & Q(occupancies__end_time__lt=end_date_obj))).distinct()

        house_number = self.request.query_params.get('house-number')
        street = self.request.query_params.get('street')
        city = self.request.query_params.get('city')
        distance = self.request.query_params.get('distance')
        if all([house_number, street, city, distance]):
            latitude, longitude = geocoding.getGeoCode(
                house_number=house_number, street=street, city=city)
            if latitude and longitude:
                min_latitude, max_latitude, min_longitude, max_longitude = geocoding.getBoundingBox(
                    latitude, longitude, distance)
                queryset = queryset.filter(
                    location__latitude__gt=min_latitude,
                    location__latitude__lt=max_latitude,
                    location__longitude__gt=min_longitude,
                    location__longitude__lt=max_longitude)
        return queryset

    def list(self, request, *args, **kwargs):
        items = self.get_queryset()
        categories = Category.objects.filter(item__in=items).distinct()
        item_serializer = self.get_serializer(items, many=True)
        category_serializer = CategorySerializer(categories, many=True)
        return Response({
            "categories": category_serializer.data,
            "items": item_serializer.data,
        })
Example #13
0
    def get_serializer_fields(self, path, method):
        fields = []
        if method == 'POST':
            fields = [
                coreapi.Field(name="group_id",
                              required=True,
                              location="form",
                              schema=coreschema.Integer(
                                  title="group", description="Id группы"),
                              description='group_id'),
                coreapi.Field(
                    name="title",
                    required=True,
                    location="form",
                    schema=coreschema.String(title="title",
                                             description="Название покупки"),
                    description='Название покупки',
                ),
                coreapi.Field(
                    name="price",
                    required=True,
                    location="form",
                    schema=coreschema.Number(title="price",
                                             description="Цена"),
                    description='Цена',
                ),
                coreapi.Field(
                    name="comment",
                    required=True,
                    location="form",
                    schema=coreschema.String(title="comment",
                                             description="Комментарий"),
                    description='Комментарий',
                ),
                coreapi.Field(
                    name="user",
                    required=True,
                    location="form",
                    schema=coreschema.Array(title="user",
                                            description="Юзеры в покупке"),
                    description='Юзеры в покупке',
                ),
            ]
        if method == 'PUT':
            fields = [
                coreapi.Field(name="done",
                              required=True,
                              location="form",
                              schema=coreschema.Boolean(
                                  title="done", description="Завершено"),
                              description='Завершено'),
                coreapi.Field(
                    name="title",
                    required=True,
                    location="form",
                    schema=coreschema.String(title="title",
                                             description="Название покупки"),
                    description='Название покупки',
                ),
                coreapi.Field(
                    name="price",
                    required=True,
                    location="form",
                    schema=coreschema.Number(title="price",
                                             description="Цена"),
                    description='Цена',
                ),
                coreapi.Field(
                    name="comment",
                    required=True,
                    location="form",
                    schema=coreschema.String(title="comment",
                                             description="Комментарий"),
                    description='Комментарий',
                ),
                coreapi.Field(
                    name="user",
                    required=True,
                    location="form",
                    schema=coreschema.Array(title="user",
                                            description="Юзеры в покупке"),
                    description='Юзеры в покупке',
                ),
            ]

        return fields
Example #14
0
 coreschema.String(),
 "description":
 coreschema.String(),
 "default":
 coreschema.Anything(),
 "definitions":
 coreschema.Ref("SchemaMap"),
 # Type
 "type":
 coreschema.Ref("SimpleTypes")
 | coreschema.Array(items=coreschema.Ref("SimpleTypes"),
                    min_items=1,
                    unique_items=True),
 # Number validators
 "minimum":
 coreschema.Number(),
 "maximum":
 coreschema.Number(),
 "exclusiveMinimum":
 coreschema.Boolean(default=False),
 "exclusiveMaximum":
 coreschema.Boolean(default=False),
 "multipleOf":
 coreschema.Number(minimum=0, exclusive_minimum=True),
 # String validators
 "minLength":
 coreschema.Integer(minimum=0, default=0),
 "maxLength":
 coreschema.Integer(minimum=0),
 "pattern":
 coreschema.String(format="regex"),
Example #15
0
class EditMovieView(CustomView):
    authentication_classes = (
        SessionAuthentication,
        TokenAuthentication,
    )
    permission_classes = (
        IsAuthenticated,
        IsAdminUser,
    )
    required_params = [
        'id', 'name', 'imdb_score', '99popularity', 'ratings', 'delete_genre',
        'add_genre', 'delete_movie_person', 'edit_person_role', 'add_person'
    ]
    schema = AutoSchema(manual_fields=[
        coreapi.Field(
            "id", required=True, location="form", schema=coreschema.Integer()),
        coreapi.Field(
            "name", required=True, location="form",
            schema=coreschema.String()),
        coreapi.Field("imdb_score",
                      required=True,
                      location="form",
                      schema=coreschema.Number()),
        coreapi.Field("99popularity",
                      required=True,
                      location="form",
                      schema=coreschema.Number()),
        coreapi.Field(
            "delete_movie_person",
            required=False,
            location="form",
            schema=coreschema.Array(),
            description="""[{'id':'abc','role':'actor'},...]""",
        ),
        coreapi.Field(
            "edit_person_role",
            required=False,
            location="form",
            schema=coreschema.Array(),
            description="""[{'name':'abc','prev_role':'actor'},...]""",
        ),
        coreapi.Field(
            "add_person",
            required=False,
            location="form",
            schema=coreschema.Array(coreschema.Array()),
            description="""[{'name':'abc','prev_role':'actor'},...]""",
        ),
        coreapi.Field(
            "delete_genre",
            required=True,
            location="form",
            schema=coreschema.Array(),
            description="['horror','Adventure']",
        ),
        coreapi.Field(
            "add_genre",
            required=True,
            location="form",
            schema=coreschema.Array(),
            description="['horror','Adventure']",
        ),
        coreapi.Field(
            "director",
            required=False,
            location="form",
            schema=coreschema.String(),
        ),
    ])

    def post(self, request, format=None):
        try:
            data = request.data
            movie = Movie.objects.get(id=data['id'])
            movie.name = data['name']
            movie.imdb_score = data['imdb_score']
            movie.popularity99 = data['99popularity']
            for tag in data["delete_genre"]:
                genre = Genre.objects.filter(name=tag)
                if genre:
                    genre = genre.first()
                    if genre in movie.genre.all():
                        movie.genre.remove(genre)

            for tag in data["add_genre"]:
                genre = Genre.objects.get_or_create(name=tag)[0]
                if genre not in movie.genre.all():
                    movie.genre.add(genre)
            for movieperson in data["delete_movie_person"]:
                if 'id' in movieperson.keys():
                    person = Person.objects.filter(id=int(movieperson["id"]))
                    if person:
                        person = person.first()
                        if 'role' in movieperson.keys():
                            role = MovieRole.objects.filter(
                                name=movieperson["role"])
                            if role:
                                role = role.first()
                                MoviePersonRoles.objects.filter(
                                    person=person, role=role,
                                    movie=movie).delete()
                        else:
                            MoviePersonRoles.objects.filter(
                                person=person, movie=movie).delete()
                else:
                    if 'name' in movieperson.keys():
                        person = Person.objects.filter(
                            name=movieperson["name"])
                        if person:
                            person = person.first()
                            if 'role' in movieperson.keys():
                                role = MovieRole.objects.filter(
                                    name=movieperson["role"])
                                if role:
                                    role = role.first()
                                    MoviePersonRoles.objects.filter(
                                        person=person, role=role,
                                        movie=movie).delete()
                            else:
                                MoviePersonRoles.objects.filter(
                                    person=person, movie=movie).delete()

            for movieperson in data['edit_person']:
                person = None
                if 'id' in movieperson.keys():
                    person = Person.objects.filter(id=int(movieperson['id']))
                    if person:
                        person.first()
                else:
                    if 'name' in movieperson.keys():
                        person = Person.objects.filter(
                            name=movieperson['name'])
                        if person:
                            person.first()
                if person:
                    if 'prev_role' in movieperson.keys():
                        prev_role = MovieRole.objects.filter(
                            name=movieperson["prev_role"])
                        if prev_role:
                            prev_role = prev_role.first()
                            if 'new_role' in movieperson.keys():
                                new_role = MovieRole.objects.get_or_create(
                                    name=movieperson['new_role'])[0]
                                moviepersonrole = MoviePersonRoles.objects.filter(
                                    movie=movie, person=person, role=prev_role)
                                if moviepersonrole and not MoviePersonRoles.objects.filter(
                                        movie=movie, person=person,
                                        role=new_role).exists():
                                    moviepersonrole = moviepersonrole.first()
                                    moviepersonrole.role = new_role
                                    moviepersonrole.save()

            for movieperson in data['add_person']:
                person = None
                if 'id' in movieperson.keys():
                    person = Person.objects.filter(id=int(movieperson['id']))
                    if person:
                        person.first()
                else:
                    if 'name' in movieperson.keys():
                        person = Person.objects.filter(
                            name=movieperson['name'])
                        if person:
                            person.first()
                if 'role' in movieperson.keys():
                    role = MovieRole.objects.get_or_create(
                        name=movieperson['role'])[0]
                    if not MoviePersonRoles.objects.filter(
                            movie=movie, person=person, role=role).exists():
                        MoviePersonRoles(movie=movie, person=person,
                                         role=role).save()

            movie.save()
            return Response({'message': 'success'})
        except Exception as e:
            return Response({"error": str(e)},
                            status=status.HTTP_400_BAD_REQUEST)
Example #16
0

jsonschema = coreschema.RefSpace({
    'Schema': coreschema.Object(
        properties={
            # Meta
            'id': coreschema.String(format='uri'),
            '$schema': coreschema.String(format='uri'),
            'title': coreschema.String(),
            'description': coreschema.String(),
            'default': coreschema.Anything(),
            'definitions': coreschema.Ref('SchemaMap'),
            # Type
            'type': coreschema.Ref('SimpleTypes') | coreschema.Array(items=coreschema.Ref('SimpleTypes'), min_items=1, unique_items=True),
            # Number validators
            'minimum': coreschema.Number(),
            'maximum': coreschema.Number(),
            'exclusiveMinimum': coreschema.Boolean(default=False),
            'exclusiveMaximum': coreschema.Boolean(default=False),
            'multipleOf': coreschema.Number(minimum=0, exclusive_minimum=True),
            # String validators
            'minLength': coreschema.Integer(minimum=0, default=0),
            'maxLength': coreschema.Integer(minimum=0),
            'pattern': coreschema.String(format='regex'),
            'format': coreschema.String(),
            # Array validators
            'items': coreschema.Ref('Schema') | coreschema.Ref('SchemaArray'), # TODO: default={}
            'additionalItems': coreschema.Boolean() | coreschema.Ref('Schema'),  # TODO: default={}
            'minItems': coreschema.Integer(minimum=0, default=0),
            'maxItems': coreschema.Integer(minimum=0),
            'uniqueItems': coreschema.Boolean(default=False),
Example #17
0
     ),
     coreapi.Field(
         name='ascending',
         location='query',
         schema=coreschema.String(
             title='ascending',
             description='順逆排,asc/desc',
             default='desc',
         ),
     ),
     coreapi.Field(
         name='limit',
         location='query',
         schema=coreschema.Number(
             title='limit',
             description='單頁回傳筆數',
             default=10,
         ),
     ),
     coreapi.Field(
         name='page',
         location='query',
         schema=coreschema.Number(
             title='page',
             description='回傳第幾頁結果',
             default=1,
         ),
     ),
 ],
 description=
 'Custom API for vuetable-2 server-side datable, See: https://www.vuetable.com/',
Example #18
0
                    location='query',
                    required=False,
                    schema=coreschema.Boolean())
          ]),
     'set_percent_complete':
     Link(url='/todo/{ident}/percent_complete',
          action='PUT',
          fields=[
              Field(name='ident',
                    location='path',
                    required=True,
                    schema=coreschema.Integer()),
              Field(name='percent_complete',
                    location='query',
                    required=False,
                    schema=coreschema.Number())
          ]),
     'set_category':
     Link(url='/todo/{ident}/category',
          action='PUT',
          fields=[
              Field(name='ident',
                    location='path',
                    required=True,
                    schema=coreschema.Integer()),
              Field(name='category',
                    location='query',
                    required=False,
                    schema=coreschema.Enum(enum=['shop', 'chore']))
          ])
 })
Example #19
0
class AddMovieView(CustomView):
    authentication_classes = (
        SessionAuthentication,
        TokenAuthentication,
    )
    permission_classes = (
        IsAuthenticated,
        IsAdminUser,
    )
    required_params = ['name', 'imdb_score', '99popularity', 'people', 'genre']
    schema = AutoSchema(manual_fields=[
        coreapi.Field(
            "name", required=True, location="form",
            schema=coreschema.String()),
        coreapi.Field("imdb_score",
                      required=True,
                      location="form",
                      schema=coreschema.Number()),
        coreapi.Field("99popularity",
                      required=True,
                      location="form",
                      schema=coreschema.Number()),
        coreapi.Field(
            "people",
            required=False,
            location="form",
            schema=coreschema.Array(),
            description="""[{'name':'abc','role':'actor'},...]""",
        ),
        coreapi.Field(
            "genre",
            required=True,
            location="form",
            schema=coreschema.Array(),
            description="['horror','Adventure']",
        ),
        coreapi.Field(
            "director",
            required=False,
            location="form",
            schema=coreschema.String(),
        ),
    ])

    def post(self, request, format=None):
        data = request.data
        try:
            movie = Movie(name=data["name"],
                          imdb_score=data["imdb_score"],
                          popularity99=data['99popularity'])
            movie.save()
            if "director" in data:
                role = MovieRole.objects.get_or_create(name="director")[0]
                person_temp = Person.objects.get_or_create(
                    name=data["director"])[0]
                mov_p_roles = MoviePersonRoles(person=person_temp,
                                               movie=movie,
                                               role=role)
                mov_p_roles.save()
            for person in data["people"]:
                role = MovieRole.objects.get_or_create(name=person["role"])[0]
                person_temp = Person.objects.get_or_create(
                    name=person["name"])[0]
                mov_p_roles = MoviePersonRoles(person=person_temp,
                                               movie=movie,
                                               role=role)
                mov_p_roles.save()
            for tag in data["genre"]:
                genre = Genre.objects.get_or_create(name=tag)[0]
                movie.genre.add(genre)
            movie.save()
            return Response({'movie_id': movie.pk})
        except Exception as e:
            return Response({"error": str(e)},
                            status=status.HTTP_400_BAD_REQUEST)
Example #20
0
 def get_schema_fields(self, view):
     return (
         Field(name='duration_min',
               required=False,
               location='query',
               schema=coreschema.Number(
                   title=_("Duration min"),
                   description=_('Set minimum duration for a trek'))),
         Field(name='duration_max',
               required=False,
               location='query',
               schema=coreschema.Number(
                   title=_("Duration max"),
                   description=_('Set maximum duration for a trek'))),
         Field(name='length_min',
               required=False,
               location='query',
               schema=coreschema.Integer(
                   title=_("Length min"),
                   description=_('Set minimum length for a trek'))),
         Field(name='length_max',
               required=False,
               location='query',
               schema=coreschema.Integer(
                   title=_("Length max"),
                   description=_('Set maximum length for a trek'))),
         Field(
             name='difficulty_min',
             required=False,
             location='query',
             schema=coreschema.Integer(
                 title=_("Difficulty min"),
                 description=
                 _('Set minimum difficulty for a trek. Difficulty usually goes from 1 (very easy) to 4 (difficult)'
                   ))),
         Field(
             name='difficulty_max',
             required=False,
             location='query',
             schema=coreschema.Integer(
                 title=_("Difficulty max"),
                 description=
                 _('Set maximum difficulty for a trek. Difficulty usually goes from 1 (very easy) to 4 (difficult)'
                   ))),
         Field(name='ascent_min',
               required=False,
               location='query',
               schema=coreschema.Integer(
                   title=_("Ascent min"),
                   description=_('Set minimum ascent for a trek'))),
         Field(name='ascent_max',
               required=False,
               location='query',
               schema=coreschema.Integer(
                   title=_("Ascent max"),
                   description=_('Set maximum ascent for a trek'))),
         Field(
             name='city',
             required=False,
             location='query',
             schema=coreschema.String(
                 title=_("City"),
                 description=
                 _('Id of a city to filter by. Can be multiple cities split by a comma. Example: 31006,31555,31017'
                   ))),
         Field(
             name='district',
             required=False,
             location='query',
             schema=coreschema.String(
                 title=_("District"),
                 description=
                 _('Id of a district to filter by. Can be multiple districts split by a comma. Example: 2273,2270'
                   ))),
         Field(name='structure',
               required=False,
               location='query',
               schema=coreschema.Integer(
                   title=_("Structure"),
                   description=_('Id of a structure to filter by'))),
         Field(
             name='accessibility',
             required=False,
             location='query',
             schema=coreschema.String(
                 title=_("Accessibility"),
                 description=
                 _('Id of the accessibilities to filter by, separated by commas. Example: 1,2'
                   ))),
         Field(
             name='theme',
             required=False,
             location='query',
             schema=coreschema.String(
                 title=_("Theme"),
                 description=
                 _('Id of the themes to filter by, separated by commas. Example: 9,14'
                   ))),
         Field(
             name='portal',
             required=False,
             location='query',
             schema=coreschema.String(
                 title=_("Portal"),
                 description=
                 _('Id of the portals to filter by, separated by commas. Example: 3,7'
                   ))),
         Field(name='route',
               required=False,
               location='query',
               schema=coreschema.Integer(
                   title=_("Route"),
                   description=_('Id of the type of route to filter by'))),
         Field(
             name='label',
             required=False,
             location='query',
             schema=coreschema.String(
                 title=_("Label"),
                 description=_(
                     'Id of the trek label to filter by, separated by commas'
                 ))),
         Field(
             name='q',
             required=False,
             location='query',
             schema=coreschema.String(
                 title=_("Query string"),
                 description=
                 _('Search field that returns treks containing data matching the string'
                   ))),
     )
 def __init__(self):
     manual_fields = [
         coreapi.Field(
             "user",
             required=True,
             location="body",
             description="Participant information",
             schema=coreschema.Ref(UserSchema()),
         ),
         coreapi.Field(
             "position",
             required=True,
             location="body",
             description="Geo Position information",
             schema=coreschema.Ref(PositionSchema()),
             example="{'longitude'': '2.7105760574340807',"
             "'latitude': '123.3' }",
         ),
         coreapi.Field(
             "type",
             required=True,
             location="formData",
             description="Type of this participant. AF - Affected, "
             "HL - Helper",
             schema=coreschema.Enum(enum=["HL", "AF", "AU", "TP"],
                                    default="AF"),
         ),
         coreapi.Field(
             "firstLineOfAddress",
             required=True,
             location="formData",
             description="First line of address",
             schema=coreschema.String(default="Goerzalle 135"),
         ),
         coreapi.Field(
             "secondLineOfAddress",
             required=True,
             location="formData",
             description="Second line of address",
             schema=coreschema.String(default=""),
         ),
         coreapi.Field(
             "postCode",
             required=True,
             location="formData",
             description="Postcode of the location",
             schema=coreschema.String(default="12207"),
         ),
         coreapi.Field(
             "city",
             required=True,
             location="formData",
             description="City Name",
             schema=coreschema.String(default="Berlin"),
         ),
         coreapi.Field(
             "country",
             required=True,
             location="formData",
             description="Country Code",
             schema=coreschema.String(default="DE"),
         ),
         coreapi.Field(
             "placeId",
             required=True,
             location="formData",
             description="Place Id from Maps App",
             schema=coreschema.String(
                 default="ChIJwyyKo7J3X0YRZ5XOMcLx3xo"),
         ),
         coreapi.Field(
             "crisis",
             required=True,
             location="formData",
             description="Crisis ID we are dealing with",
             schema=coreschema.Number(default=1),
         ),
         coreapi.Field(
             "phone",
             required=False,
             location="formData",
             description="Phone number of the participant",
             schema=coreschema.String(default="+4677777777"),
         ),
     ]
     super().__init__(fields=manual_fields, encoding="application/json")