Ejemplo n.º 1
0
    def upload(self, request, *args, **kwargs):
        """
        Upload a geotiff file into a CaseStudyLayer object. Projection, extension and resolution should
        be the same for all layers.

        Basic usage example in python
        ```python
        import requests
        url = "https://api.tools4msp.eu/api/casestudies/{parent_lookup_casestudy__id}/layers/{id}/upload/
        input_file = "[path to the geotiff file]"

        with open(input_file, 'rb') as f:
            files = {'file': f}
            r = requests.put(url, auth=('Token', TOKEN), files=files)
        ```
        """
        if 'file' not in request.data:
            raise ParseError("Empty content")

        f = request.data['file']
        with MemoryFile(f) as memfile:
            try:
                with memfile.open() as dataset:
                    pass
            except RasterioIOError:
                raise ParseError("Unsupported raster file")

        obj = self.get_object()
        obj.file.save(f.name, f, save=True)
        return Response(status=status.HTTP_201_CREATED)
Ejemplo n.º 2
0
def download_image(url, resize, size):
    '''
    This functions downloads image from the given url and return back django image field
    instance
    '''
    absoulte_url = url.split('?')[0]
    url_schema = ["http", "https"]
    if url_schema[0] not in url:
        url = url_schema[0] + url
    try:
        r = requests.head(url)
    except:
        raise ParseError('Invalid url')
    if 'image' not in r.headers.get('content-type'):
        return ParseError('Invalid image type')
    else:
        try:
            image_file_path = absoulte_url.split('/')[-1]
            im = Image.open(requests.get(url, stream=True).raw)
            format = im.format
            if '.' not in image_file_path:
                image_file_path += "." + format
            if resize:
                return resizeImage(im, size, image_file_path, True)

            return createFieldImage(im, image_file_path, format)
        except Exception as e:
            raise ParseError('Invalid image type')
Ejemplo n.º 3
0
 def parse(self, stream, media_type=None, parser_context=None):
     parsed = super(JSONRootObjectParser,
                    self).parse(stream, media_type, parser_context)
     view = parser_context.get('view')
     try:
         # Check that the serializer for the given route matches the resource name in the parsed data
         resource_name = view.get_serializer().Meta.resource_name
     except AttributeError as exc:
         # When our serializer object has no resource name we don't know what to expect.
         raise ParseError('JSON parse error - %s' % six.text_type(exc))
     try:
         return parsed[resource_name]
     except KeyError as exc:
         # When our resource_name is defined but not found in the data, we should not try to extract it
         raise ParseError('JSON parse error - %s' % six.text_type(exc))
Ejemplo n.º 4
0
    def parse(
        self,
        stream,
        media_type: Optional[Any] = None,
        parser_context: Any = None,
    ) -> Any:
        """
        De-serializes JSON strings to Python objects.
        :param stream: A stream-like object representing the body of the request.
        :param media_type: If provided, this is the media type of the incoming
                request content specified in the `Content-Type` HTTP header.
        :param parser_context: If supplied, this argument will be a dictionary
                containing any additional context that may be required to parse
                the request content.
                By default this will include the following
                keys: view, request, args, kwargs.
        :return: Python native instance of the JSON string.
        """
        parser_context = parser_context or {}
        encoding: str = parser_context.get("encoding",
                                           settings.DEFAULT_CHARSET)

        try:
            decoded_stream = codecs.getreader(encoding)(stream)
            return orjson.loads(decoded_stream.read())
        except ValueError as exc:
            raise ParseError('JSON parse error - %s' % str(exc))
Ejemplo n.º 5
0
    def post(self,request):
        text = request.data.get('text')
        title = request.data.get('title')
        ask_with_only_experts = request.data.get('ask_with_only_experts')

        if 'file' not in request.data:
            raise ParseError("Empty content ")

        photo = request.data["file"]
        u = request.user.id

        serializer_context = {
            'request': request,
        }
        ps = serilizer.PostSerializer(data={"text":text,"title":title,"photo":photo,"ask_with_only_experts": ask_with_only_experts
                                            ,"user": u,"points":"0"},context=serializer_context)

        if ps.is_valid():
            n = ps.save()
            import json
            if n.ask_with_only_experts is not True:
                
                return HttpResponse(json.dumps({'message': "Uploaded"}), status=200)
            else :
                print('hee')
                return Response({'message': "expert_list" ,"success": "{}".format(n.id)})

        else:
            return Response(ps.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 6
0
    def parse(self, stream, media_type=None, parser_context=None):
        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)

        try:
            data = stream.read().decode(encoding)
            return underscoreize(json.loads(data))
        except Exception as e:
            raise ParseError('Error', str(e))
Ejemplo n.º 7
0
    def parse(self, stream, media_type=None, parser_context=None):
        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)

        try:
            data = stream.read().decode(encoding)
            return underscoreize(json.loads(data))
        except ValueError as exc:
            raise ParseError('JSON parse error - %s' % six.text_type(exc))
Ejemplo n.º 8
0
    def post(self, request, pk):
        recipe = get_object_or_404(self.request.user.recipes, pk=pk)
        # Read the uploaded file
        if 'file' not in request.data:
            raise ParseError("Empty content")

        file = request.data['file']
        image = RecipeImage(recipe=recipe)
        image.image.save(file.name, file, save=True)
        serializer = RecipeImageSerializer(instance=image)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
Ejemplo n.º 9
0
    def process_feature(self, data):
        del data['type']
        properties = data.pop('properties', None)

        if not isinstance(properties, dict):
            raise ParseError(
                'GeoJSON parse error - Feature "properties" must be an object (dict) not %s - %s'
                % (type(data), data))

        data.update(properties)
        return data
Ejemplo n.º 10
0
 def parse(self, stream, media_type=None, parser_context=None):
     data_and_files = super(MultiPartJSONParser,
                            self).parse(stream, media_type, parser_context)
     try:
         json_data = json.loads(data_and_files.data['data'])
     except ValueError as e:
         raise ParseError(f"JSON parse error - {e}")
     data_and_files.data = data_and_files.data.copy()
     data_and_files.data.update(json_data)
     del data_and_files.data['data']
     return data_and_files
Ejemplo n.º 11
0
    def parse(self, stream, media_type=None, parser_context=None):
        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)

        try:
            data = json.loads(stream.read().decode(encoding))
            data = data['data']
            if api_settings.CAMELIZE:
                data = underscoreize(data, **api_settings.JSON_UNDERSCOREIZE)
            return data
        except (ValueError, TypeError, KeyError) as exc:
            raise ParseError('JSON parse error - %s' % str(exc))
Ejemplo n.º 12
0
    def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as JSON and returns the resulting data.
        """
        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)

        try:
            data = stream.read().decode(encoding)
            return ujson.loads(data)
        except ValueError as exc:
            raise ParseError('JSON parse error - %s' % six.text_type(exc))
Ejemplo n.º 13
0
 def parse(self, stream, media_type=None, parser_context=None):
     parser_context = parser_context or {}
     if 'disable_camelcase' in parser_context['request'].query_params:
         return super(CamelCaseJSONParser,
                      self).parse(media_type, parser_context)
     else:
         encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
         try:
             data = stream.read().decode(encoding)
             return rename_fields(json.loads(data))
         except ValueError as exc:
             raise ParseError('JSON parse error - %s' % six.text_type(exc))
Ejemplo n.º 14
0
 def parse(self, stream, media_type=None, parser_context=None):
     parser_context = parser_context or {}
     encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
     request = parser_context.get('request')
     try:
         data = stream.read().decode(encoding)
         setattr(
             request, 'raw_body', data
         )  # setting a 'body' alike custom attr with raw POST content
         return json.loads(data)
     except ValueError as exc:
         raise ParseError('JSON parse error - %s' % six.text_type(exc))
Ejemplo n.º 15
0
    def process_object(self, data):
        try:
            obj_type = data['type']
        except KeyError:
            raise ParseError('GeoJSON parse error - No "type" found in %s' %
                             (data, ))

        valid_types = ('Point', 'LineString', 'Polygon', 'MultiPoint',
                       'MultiLineString', 'MultiPolygon', 'GeometryCollection',
                       'Feature', 'FeatureCollection')
        if obj_type not in valid_types:
            raise ParseError(
                'GeoJSON parse error - %r is not a valid object type: only %s'
                % (obj_type, ', '.join(valid_types)))

        if obj_type == 'Feature':
            data = self.process_feature(data)
        elif obj_type == 'FeatureCollection':
            data = self.process_array(data.get('features', []))

        return data
Ejemplo n.º 16
0
    def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as JSON and returns the resulting data.
        """
        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)

        try:
            decoded_stream = codecs.getreader(encoding)(stream)
            parse_constant = ujson.strict_constant if self.strict else None
            return ujson.load(decoded_stream, parse_constant=parse_constant)
        except ValueError as exc:
            raise ParseError('JSON parse error - %s' % six.text_type(exc))
Ejemplo n.º 17
0
 def put(self, request, format=None):
     if 'file' not in request.data:
         raise ParseError("Empty content")
     f = request.data['file']
     filename = f.name
     if filename.endswith('.csv'):
         file = default_storage.save(filename, f)
         r = csv_file_parser(file)
         status = 204
     else:
         status = 406
         r = "File format error"
     return Response(r, status=status)
Ejemplo n.º 18
0
def createFieldImage(im, filename, format):
    '''
    This function takes pillow image instance and converts it into django
    image field.
    '''
    try:
        imgByteArr = io.BytesIO()
        im = im.save(imgByteArr, format=format)
        imgByteArr = imgByteArr.getvalue()
        ok = ContentFile(imgByteArr)
        return InMemoryUploadedFile(ok, None, filename, 'image/' + format,
                                    ok.tell, None)
    except:
        raise ParseError('Failed to decode Image')
    def parse(self, stream, media_type=None, parser_context=None):
        """
        Simply return a string representing the body of the request.
        """
        encoding = parser_context['request'].META.get(
            'HTTP_CONTENT_ENCODING', '')

        if encoding == 'gzip':
            raw_content = stream.read()

            try:
                uncompressed_content = gzip_decompress(raw_content)
            except IOError, e:
                raise ParseError('gzip error - {}'.format(e))

            stream = StringIO.StringIO(uncompressed_content)
Ejemplo n.º 20
0
def csv_file_parser(file):
    result_dict = {}
    with open(file) as csvfile:
        reader = csv.DictReader(csvfile)
        next(reader)
        line_count = 1
        for rows in reader:
            for key, value in rows.items():
                if not value:
                    raise ParseError(
                        'Missing value in file. Check the {} line'.format(
                            line_count))
            result_dict[line_count] = rows
            line_count += 1

    return result_dict
Ejemplo n.º 21
0
        def post(self,request):
            if 'file' not in request.data:
                
                raise ParseError("Empty content fofoff")

            photo = request.data["file"]
            u = request.user.id 
            serializer_context = {
            'request': request,
            }
            s = Profile.objects.filter(user = request.user)
            if s :
                s.delete()
            ps = serilizer.ProfileSerializer2(data={"profile_photo": photo,"user": u },context=serializer_context)
            if ps.is_valid():
                ps.save()
                import json
                #return HttpResponse(json.dumps({'message': "Uploaded"}), status=200)
                return Response({"success": "successful image upload"})
            else:
                return Response(ps.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 22
0
def resizeImage(file, size, filename, downloaded):
    '''
    This function take file and resize parameter and resize the image using 
    pillow.
    '''
    if downloaded:
        im = file
        format = im.format
    else:
        try:
            im = Image.open(file)
            im.verify()
        except:
            raise UnsupportedMediaType('Invalid Image type')
        im = Image.open(file)
        format = im.format
    try:
        width, height = size.split('x')
        im = im.resize((int(width), int(height)), PIL.Image.ANTIALIAS)
    except:
        raise ParseError('Invalid resize value')
    return createFieldImage(im, filename, format)
Ejemplo n.º 23
0
    def tupload(self, request, *args, **kwargs):
        """
        Upload a thumbnail image (eg. png) into a CaseStudyInput object.

        Basic usage example in python
        ```python
        import requests
        url = "https://api.tools4msp.eu/api/casestudies/{parent_lookup_casestudy__id}/inputs/{id}/tupload/
        input_file = "[path to the thumbnail image]"

        with open(input_file, 'rb') as f:
            files = {'file': f}
            r = requests.put(url, auth=('Token', TOKEN), files=files)
        ```
        """
        if 'file' not in request.data:
            raise ParseError("Empty content")

        f = request.data['file']

        obj = self.get_object()
        obj.thumbnail.save(f.name, f, save=True)
        return Response(status=status.HTTP_201_CREATED)
Ejemplo n.º 24
0
    def nbiot_engineering_create(self, request):
        data = JSONParser().parse(request)
        if "messages" not in data or len(
                data["messages"]) == 0 or "payload" not in data["messages"][0]:
            return JsonResponse(status=400, data={"error": "Missing payload."})
        payload_encoded = data["messages"][0]["payload"]
        payload_string = b64decode(payload_encoded).decode("utf-8")
        try:
            payload_data = json.loads(payload_string)
        except ValueError as ex:
            raise ParseError("JSON parse error - {ex}".format(ex=ex))

        serializer = MeasurementCreateSerializer(data=payload_data,
                                                 context={"request": request})
        serializer.is_valid(raise_exception=True)

        response = self.allowed_create(request, serializer.validated_data)
        if response:
            return response

        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=201, headers=headers)
Ejemplo n.º 25
0
 def create(self, request, *args, **kwargs):
     if 'file' not in request.data:
         raise ParseError("Empty content")
     file = request.data["file"]
Ejemplo n.º 26
0
 def upload_image(request):
     try:
         file = request.data['file']
     except KeyError:
         raise ParseError('Request has no resource file attached')
     subtitle = SubTitle.objects.create(image=file)