Esempio n. 1
0
 def get(self, request, format=None):
     provider_data = ContentProvider \
         .objects \
         .values(IDENTIFIER, NAME, FILTER, URL)
     provider_table = {
         rec[IDENTIFIER]: (rec[NAME], rec[FILTER], rec[URL])
         for rec in provider_data
     }
     sources = get_sources('image')
     response = []
     for source in sources:
         if source in provider_table:
             display_name, _filter, provider_url = provider_table[source]
             if not _filter:
                 response.append({
                     'source_name': source,
                     'image_count': sources[source],
                     'display_name': display_name,
                     'source_url': provider_url
                 })
         else:
             msg = 'provider_identifier missing from content_provider' \
                   ' table: {}. Check for typos/omissions.'.format(source)
             log.error(msg)
     return Response(status=200, data=response)
Esempio n. 2
0
 def get(self, request, format=None):
     source_data = ContentProvider \
         .objects \
         .values(ID, CODENAME, NAME, FILTER, URL)
     source_counts = get_sources('image')
     response = []
     for source in source_data:
         source_codename = source[CODENAME]
         _id = source[ID]
         display_name = source[NAME]
         filtered = source[FILTER]
         source_url = source[URL]
         count = source_counts.get(source_codename, None)
         try:
             source_logo = SourceLogo.objects.get(source_id=_id)
             logo_path = source_logo.image.url
             full_logo_url = request.build_absolute_uri(logo_path)
         except SourceLogo.DoesNotExist:
             full_logo_url = None
         if not filtered and source_codename in source_counts:
             response.append(
                 {
                     'source_name': source_codename,
                     'image_count': count,
                     'display_name': display_name,
                     'source_url': source_url,
                     'logo_url': full_logo_url
                 }
             )
     return Response(status=200, data=response)
Esempio n. 3
0
    def validate_source(input_providers):
        allowed_providers = list(get_sources('image').keys())

        for input_provider in input_providers.split(','):
            if input_provider not in allowed_providers:
                raise serializers.ValidationError(
                    "Provider \'{}\' does not exist.".format(input_providers))
        return input_providers.lower()
Esempio n. 4
0
    def validate_source(input_sources):
        allowed_sources = list(get_sources('image').keys())

        for input_source in input_sources.split(','):
            if input_source not in allowed_sources:
                raise serializers.ValidationError(
                    f"Source \'{input_source}\' does not exist."
                )
        return input_sources.lower()
Esempio n. 5
0
class ImageSearchQueryStringSerializer(serializers.Serializer):
    """ Parse and validate search query string parameters. """
    DeprecatedParam = namedtuple('DeprecatedParam', ['original', 'successor'])
    deprecated_params = [
        DeprecatedParam('li', 'license'),
        DeprecatedParam('lt', 'license_type'),
        DeprecatedParam('pagesize', 'page_size'),
        DeprecatedParam('provider', 'source')
    ]

    q = serializers.CharField(
        label="query",
        help_text="A query string that should not exceed 200 characters in "
                  "length",
        required=False,
    )
    license = serializers.CharField(
        label="licenses",
        help_text="A comma-separated list of licenses. Example: `by,cc0`."
                  " Valid inputs: `{}`"
                  .format(list(license_helpers.LICENSE_GROUPS['all'])),
        required=False,
    )
    license_type = serializers.CharField(
        label="license type",
        help_text="A list of license types. "
                  "Valid inputs: `{}`"
                  .format((list(license_helpers.LICENSE_GROUPS.keys()))),
        required=False,
    )
    page = serializers.IntegerField(
        label="page number",
        help_text="The page number to retrieve.",
        default=1
    )
    page_size = serializers.IntegerField(
        label="page size",
        help_text="The number of results to return in the requested page. "
                  "Should be an integer between 1 and 500.",
        default=20
    )
    creator = serializers.CharField(
        label="creator",
        help_text="Search by creator only. Cannot be used with `q`.",
        required=False,
        max_length=200
    )
    tags = serializers.CharField(
        label="tags",
        help_text="Search by tag only. Cannot be used with `q`.",
        required=False,
        max_length=200
    )
    title = serializers.CharField(
        label="title",
        help_text="Search by title only. Cannot be used with `q`.",
        required=False,
        max_length=200
    )
    filter_dead = serializers.BooleanField(
        label="filter_dead",
        help_text="Control whether 404 links are filtered out.",
        required=False,
        default=True
    )
    source = serializers.CharField(
        label="provider",
        help_text="A comma separated list of data sources to search. Valid "
                  "inputs:"
                  " `{}`".format(list(get_sources('image').keys())),
        required=False
    )
    extension = serializers.CharField(
        label="extension",
        help_text="A comma separated list of desired file extensions.",
        required=False
    )
    categories = serializers.CharField(
        label="categories",
        help_text="A comma separated list of categories; available categories "
                  "include `illustration`, `photograph`, and "
                  "`digitized_artwork`.",
        required=False
    )
    aspect_ratio = serializers.CharField(
        label='aspect_ratio',
        help_text="A comma separated list of aspect ratios; available aspect "
                  "ratios include `tall`, `wide`, and `square`.",
        required=False
    )
    size = serializers.CharField(
        label='size',
        help_text="A comma separated list of image sizes; available sizes"
                  " include `small`, `medium`, or `large`.",
        required=False
    )
    mature = serializers.BooleanField(
        label='mature',
        default=False,
        required=False,
        help_text="Whether to include content for mature audiences."
    )
    qa = serializers.BooleanField(
        label='quality_assurance',
        help_text="If enabled, searches are performed against the quality"
                  " assurance index instead of production.",
        required=False,
        default=False
    )

    @staticmethod
    def validate_q(value):
        if len(value) > 200:
            return value[0:199]
        else:
            return value

    def validate_creator(self, value):
        return self.validate_q(value)

    def validate_tags(self, value):
        return self.validate_q(value)

    def validate_title(self, value):
        return self.validate_q(value)

    @staticmethod
    def validate_license(value):
        return _validate_li(value)

    @staticmethod
    def validate_license_type(value):
        """
        Resolves a list of license types to a list of licenses.
        Example: commercial -> ['BY', 'BY-SA', 'BY-ND', 'CC0', 'PDM']
        """
        return _validate_lt(value)

    @staticmethod
    def validate_page(value):
        return _validate_page(value)

    @staticmethod
    def validate_page_size(value):
        if 1 <= value <= 500:
            return value
        else:
            return 20

    @staticmethod
    def validate_source(input_sources):
        allowed_sources = list(get_sources('image').keys())

        for input_source in input_sources.split(','):
            if input_source not in allowed_sources:
                raise serializers.ValidationError(
                    f"Source \'{input_source}\' does not exist."
                )
        return input_sources.lower()

    @staticmethod
    def validate_extension(value):
        return value.lower()

    @staticmethod
    def validate_categories(value):
        valid_categories = {
            'illustration',
            'digitized_artwork',
            'photograph'
        }
        _validate_enum('category', valid_categories, value)
        return value.lower()

    @staticmethod
    def validate_aspect_ratio(value):
        valid_ratios = {'tall', 'wide', 'square'}
        _validate_enum('aspect ratio', valid_ratios, value)
        return value.lower()

    def validate(self, data):
        for deprecated in self.deprecated_params:
            param, successor = deprecated
            if param in self.initial_data:
                raise serializers.ValidationError(
                    f"Parameter '{param}' is deprecated in this release of"
                    f" the API. Use '{successor}' instead."
                )
        return data
 def validate_source(input_sources):
     allowed_sources = list(get_sources('image').keys())
     input_sources = input_sources.split(',')
     input_sources = [x for x in input_sources if x in allowed_sources]
     input_sources = ','.join(input_sources)
     return input_sources.lower()