Ejemplo n.º 1
0
def get_wms_response(query_string, base_url, out_format, layers):
    group = 'raster_layers'
    layer_names = []
    for layer in layers:
        name = layer.get('name')
        if name:
            layer_names.append(name)
    req = get_wms_request(query_string=query_string, layer_names=layer_names)
    src_map = get_map(base_url=base_url,
                      out_format=out_format,
                      layers=layers,
                      group=group)
    # raise ValueError(src_map.outputformat.imagemode, mapscript.MS_IMAGEMODE_INT16)
    mapscript.msIO_installStdoutToBuffer()
    try:
        src_map.OWSDispatch(req)
        error = False
    except mapscript.MapServerError:
        error = True
    content_type = mapscript.msIO_stripStdoutBufferContentType()
    content = mapscript.msIO_getStdoutBufferBytes()
    mapscript.msIO_resetHandlers()

    # if content_type == 'vnd.ogc.se_xml':
    #     content_type = 'text/xml'
    return content, content_type, error
    def render(self, extent, size):
        message = ""
        mapObj = self.getMapObj()

        mapObj.setConfigOption("MS_ERRORFILE", "stdout")
        mapObj.debug = 5

        mapObj.setExtent(extent.xMinimum(), extent.yMinimum(), extent.xMaximum(), extent.yMaximum())
        mapObj.setSize(int(size[0]), int(size[1]))
        message += "Rendering %s" % extent.toString()

        data = ""
        try:
            mapscript.msIO_installStdoutToBuffer()
            mapImage = mapObj.draw()  # = mapscript.imageObj(int(size[0]), int(size[1]), self.mime_type)
            data = mapImage.getBytes()
            message += "Image size: %s" % str(len(data))

            out = mapscript.msIO_getStdoutBufferString()
            mapscript.msIO_resetHandlers()
            message += out
        except mapscript.MapServerError as err:
            message += str(err)

        return data, message
Ejemplo n.º 3
0
  def render(self, extent, size):
    message = ""
    mapObj = self.getMapObj()

    mapObj.setConfigOption("MS_ERRORFILE", "stdout")
    mapObj.debug = 5

    mapObj.setExtent(extent.xMinimum(), extent.yMinimum(), extent.xMaximum(), extent.yMaximum())
    mapObj.setSize(int(size[0]), int(size[1]))
    message += "Rendering %s" % extent.toString()

    data = ''
    try:
      mapscript.msIO_installStdoutToBuffer()
      mapImage = mapObj.draw() #= mapscript.imageObj(int(size[0]), int(size[1]), self.mime_type)
      data = mapImage.getBytes()
      message += "Image size: %s" % str(len(data))

      out = mapscript.msIO_getStdoutBufferString()
      mapscript.msIO_resetHandlers()
      message += out
    except mapscript.MapServerError as err:
      message += str(err)

    return data, message
Ejemplo n.º 4
0
    def render(self):
        """ Render this map object

            This will inspect the OWS request type, and render the correct image
            for the request.

            Known supported OWS REQUEST values:

            * GetLegendGraphic: Will render the legend for the OWS request
            * GetMap: Will render the map tile for the OWS request
        """

        log = logging.getLogger(__name__)

        content = None          # the bytes of the rendered image
        content_type = None     # the image mimetype
        retval = None           # the OWS return value, useful for debugging

        with self.__class__.MAPSCRIPT_RLOCK:
            try:
                ows_request_type = self.ows_request.getValueByName('REQUEST')

                if (ows_request_type == 'GetLegendGraphic'):
                    # Draw the legend for the map
                    retval = self.loadOWSParameters(self.ows_request)
                    image = self.drawLegend()
                    content = image.getBytes()
                    content_type = image.format.mimetype
                elif (ows_request_type == 'GetMap'):
                    # Draw the map (tiles)
                    retval = self.loadOWSParameters(self.ows_request)
                    image = self.draw()
                    content = image.getBytes()
                    content_type = image.format.mimetype
                else:
                    # Unexpected OWS request. Do our best to support it by
                    # falling back to using the OWS Dispatch

                    # Tell mapscript to start capturing the stdout in a buffer
                    mapscript.msIO_installStdoutToBuffer()
                    # dispatch the OWS request
                    retval = self.OWSDispatch(self.ows_request)
                    # Get the content type of the return value
                    content_type = mapscript.msIO_stripStdoutBufferContentType()
                    # Get the content of the resulting image
                    content = mapscript.msIO_getStdoutBufferBytes()

                if retval != mapscript.MS_SUCCESS:
                    # Failed to render the desired image
                    raise RuntimeError("Failed to render map OWS request")

            except:
                log.error("Error while trying to render map: %s", sys.exc_info()[0])
                raise
            finally:
                # Reset the mapscript I/O pointers back to where they should be
                mapscript.msIO_resetHandlers()

        return content, content_type, retval
    def application(self, env, start_response):
        q_str = {
            my.split("=")[0].upper(): my.split("=")[1]
            for my in env['QUERY_STRING'].split('&') if "=" in my
        }
        serv_ver = [q_str.get('SERVICE', False), q_str.get('VERSION', False)]

        print "-" * 30
        for key in self.MAPSERV_ENV:
            if key in env:
                os.environ[key] = env[key]
                print "{0}='{1}'".format(key, env[key])
            else:
                os.unsetenv(key)
        print "QUERY_STRING=("
        for key in q_str:
            print "    {0}={1},".format(key, q_str[key])
        print ")"
        print "-" * 30

        request = mapscript.OWSRequest()
        mapscript.msIO_installStdoutToBuffer()
        request.loadParamsFromURL(env['QUERY_STRING'])
        rec_obj = self.mapscript_obj.clone()

        try:
            status_id = rec_obj.OWSDispatch(request)
        except Exception as err:
            print "OWSDispatch Error: {}".format(err)
            err_def = unicode(err).split(':')[0]
            status_id = None

        content_type = mapscript.msIO_stripStdoutBufferContentType()
        result = mapscript.msIO_getStdoutBufferBytes()
        mapscript.msIO_resetHandlers()

        # status:
        if status_id == mapscript.MS_SUCCESS:
            status = '200 OK'
        elif status_id == mapscript.MS_FAILURE:
            status = '400 Bad request'
            if serv_ver == ['WFS', '2.0.0']:
                result = '\n'.join(result.split('\n')[2:])
        elif status_id is None:
            if serv_ver[0] == "WMS" and err_def == "msPostGISLayerGetExtent()":
                status = '200 OK'
            elif serv_ver == ['WFS', '1.0.0'
                              ] and err_def == "msWFSGetFeature()":
                status = '400 Bad request'
            else:
                status = '500 Server Error'

        start_response(status, [('Content-type', str(content_type))])
        return [result]
Ejemplo n.º 6
0
 def request_mapscript(self, env, mapdata, que=None):
     """
     render on mapserver mapscript request
     """
     q_str = {
         my.split("=")[0].upper(): my.split("=")[1]
         for my 
         in env['QUERY_STRING'].split('&')
         if "=" in my
     }
     serv_ver = [q_str.get('SERVICE', False), q_str.get('VERSION', False)]
     request = mapscript.OWSRequest()
     mapscript.msIO_installStdoutToBuffer()
     request.loadParamsFromURL(env['QUERY_STRING'])
     rec_obj = mapdata.clone()
 
     try:
         status_id = rec_obj.OWSDispatch(request)
     except Exception as err:
         print "OWSDispatch Error: {}".format(err)
         err_def = unicode(err).split(':')[0]
         status_id = None
 
     content_type = mapscript.msIO_stripStdoutBufferContentType()
     content = mapscript.msIO_getStdoutBufferBytes()
     mapscript.msIO_resetHandlers()
     
     # status:
     if status_id == mapscript.MS_SUCCESS:
         status = 200
     elif status_id == mapscript.MS_FAILURE:
         status = 400
         if serv_ver == ['WFS', '2.0.0']:
             content = '\n'.join(content.split('\n')[2:])
     elif status_id is None:
         if serv_ver[0] == "WMS" and err_def == "msPostGISLayerGetExtent()":
             status = 200
         elif serv_ver == ['WFS', '1.0.0'] and err_def == "msWFSGetFeature()":
             status = 400
         else:
             status = 500
     else:
         status = 500
     
     out_response = (
         status, 
         content_type, 
         content
     )
     if que is None:
         return out_response
     else:
         que.put(out_response)
    def render(self, extent, size):
        mapObj = mapscript.mapObj(self.mapfile)

        mapObj.setConfigOption("MS_ERRORFILE", "stdout")
        mapObj.debug = 5

        mapObj.setExtent(extent.xMinimum(), extent.yMinimum(), extent.xMaximum(), extent.yMaximum())
        mapObj.setSize(int(size[0]), int(size[1]))
        self.messageTextEdit.append("Rendering " + extent.toString())

        mapscript.msIO_installStdoutToBuffer()

        mapImage = mapObj.draw()  # = mapscript.imageObj(int(size[0]), int(size[1]), self.mime_type)
        data = mapImage.getBytes()

        out = mapscript.msIO_getStdoutBufferString()
        mapscript.msIO_resetHandlers()
        self.messageTextEdit.append(out)

        return data
Ejemplo n.º 8
0
def process_request(django_request, map_obj):
    """Offload the processing of the OWS request to MapServer.

    :arg django_request: the request parameters
    :type django_request: HttpRequest
    :arg map_obj: the in-memory mapfile to use
    :type map_obj: mapscript.mapObj
    :return: the mapserver buffer with the output from processing the request
    """

    if django_request.method == 'GET':
        params = django_request.GET
    elif django_request.method == 'POST':
        # get the params from the XML body of the request
        raise Exception
    # build the WMS request
    wms_req = mapscript.OWSRequest()
    for k, v in params.items():
        wms_req.setParameter(k, v)

    # install a mapserver IO handler directing future stdout to a memory buffer
    output_buffer = mapscript.msIO_installStdoutToBuffer()

    # dispatch the request to mapserver
    map_obj.OWSDispatch(wms_req)

    # get back mapserver's response
    # ms_headers = mapscript.msIO_stripStdoutBufferContentHeaders()
    ms_content_type = mapscript.msIO_stripStdoutBufferContentType()
    ms_content = mapscript.msIO_getStdoutBufferBytes()
    if ms_content == 'application/vnd.ogc.se_xml':
        ms_content = 'Content-Type: text/xml\n\n{}'.format(ms_content)

    # reset the stdin/stdout handlers
    mapscript.msIO_resetHandlers()
    return ms_content, ms_content_type
  def render(self, extent, size):
    mapObj = self.getMapObj()

    mapObj.setConfigOption("MS_ERRORFILE", "stdout")
    mapObj.debug = 5

    mapObj.setExtent(extent.xMinimum(), extent.yMinimum(), extent.xMaximum(), extent.yMaximum())
    mapObj.setSize(int(size[0]), int(size[1]))
    self.messageTextEdit.append( "Rendering " + extent.toString() )

    data = ''
    try:
      mapscript.msIO_installStdoutToBuffer()
      mapImage = mapObj.draw() #= mapscript.imageObj(int(size[0]), int(size[1]), self.mime_type)
      data = mapImage.getBytes()
      self.messageTextEdit.append( "Image size: " + str(len(data)) )

      out = mapscript.msIO_getStdoutBufferString()
      mapscript.msIO_resetHandlers()
      self.messageTextEdit.append( out )
    except mapscript.MapServerError as err:
      self.messageTextEdit.append( str(err) )

    return data
Ejemplo n.º 10
0
    def render(self):
        """ Render this map object

            This will inspect the OWS request type, and render the correct image
            for the request.

            Known supported OWS REQUEST values:

            * GetLegendGraphic: Will render the legend for the OWS request
            * GetMap: Will render the map tile for the OWS request
        """

        log = logging.getLogger(__name__)

        content = None  # the bytes of the rendered image
        content_type = None  # the image mimetype
        retval = None  # the OWS return value, useful for debugging

        # TODO: do I need alock here?
        # with LockFile(self.data_file_path + '.lock'):
        if True:
            try:
                ows_request_type = self.ows_request.getValueByName('REQUEST')

                if (ows_request_type == 'GetLegendGraphic'):
                    # Draw the legend for the map
                    retval = self.loadOWSParameters(self.ows_request)
                    image = self.drawLegend()
                    content = image.getBytes()
                    content_type = image.format.mimetype
                elif (ows_request_type == 'GetMap'):
                    # Draw the map (tiles)
                    retval = self.loadOWSParameters(self.ows_request)
                    image = self.draw()
                    content = image.getBytes()
                    content_type = image.format.mimetype
                else:
                    # Unexpected OWS request. Do our best to support it by
                    # falling back to using the OWS Dispatch

                    # Tell mapscript to start capturing the stdout in a buffer
                    mapscript.msIO_installStdoutToBuffer()
                    # dispatch the OWS request
                    retval = self.OWSDispatch(self.ows_request)
                    # Get the content type of the return value
                    content_type = mapscript.msIO_stripStdoutBufferContentType(
                    )
                    # Get the content of the resulting image
                    content = mapscript.msIO_getStdoutBufferBytes()

                if retval != mapscript.MS_SUCCESS:
                    # Failed to render the desired image
                    raise RuntimeError("Failed to render map OWS request")

            except:
                log.error("Error while trying to render map: %s",
                          sys.exc_info()[0])
                raise
            finally:
                # Reset the mapscript I/O pointers back to where they should be
                mapscript.msIO_resetHandlers()

        return content, content_type, retval