def test_encoding():
    import os
    from ogcserver.configparser import SafeConfigParser
    from ogcserver.WMS import BaseWMSFactory
    from ogcserver.wms111 import ServiceHandler as ServiceHandler111
    from ogcserver.wms130 import ServiceHandler as ServiceHandler130

    base_path, tail = os.path.split(__file__)
    file_path = os.path.join(base_path, 'mapfile_encoding.xml')
    wms = BaseWMSFactory()
    wms.loadXML(file_path)
    wms.finalize()

    conf = SafeConfigParser()
    conf.readfp(open(os.path.join(base_path, 'ogcserver.conf')))

    wms111 = ServiceHandler111(conf, wms, "localhost")
    response = wms111.GetCapabilities({})
    # Check the response is encoded in UTF-8
    # Search for the title in the response
    if conf.get('service', 'title') not in response.content:
        raise Exception('GetCapabilities is not correctly encoded')

    wms130 = ServiceHandler130(conf, wms, "localhost")
    wms130.GetCapabilities({})

    return True
Esempio n. 2
0
 def __init__(self,
              configpath,
              fonts=None,
              home_html=None,
              **kwargs
             ):
     conf = SafeConfigParser()
     conf.readfp(open(configpath))
     # TODO - be able to supply in config as well
     self.home_html = home_html
     self.conf = conf
     if fonts:
         mapnik.register_fonts(fonts)
     if 'debug' in kwargs:
         self.debug = bool(kwargs['debug'])
     else:
         self.debug = False
     if self.debug:
         self.debug=1
     else:
         self.debug=0
     if 'maxage' in kwargs:
         self.max_age = 'max-age=%d' % kwargs.get('maxage')
     else:
         self.max_age = None
Esempio n. 3
0
def test_encoding():
    import os
    from ogcserver.configparser import SafeConfigParser
    from ogcserver.WMS import BaseWMSFactory
    from ogcserver.wms111 import ServiceHandler as ServiceHandler111
    from ogcserver.wms130 import ServiceHandler as ServiceHandler130

    base_path, tail = os.path.split(__file__)
    file_path = os.path.join(base_path, 'mapfile_encoding.xml')
    wms = BaseWMSFactory() 
    wms.loadXML(file_path)
    wms.finalize()

    conf = SafeConfigParser()
    conf.readfp(open(os.path.join(base_path, 'ogcserver.conf')))

    wms111 = ServiceHandler111(conf, wms, "localhost")
    response = wms111.GetCapabilities({})
    # Check the response is encoded in UTF-8
    # Search for the title in the response
    if conf.get('service', 'title') not in response.content:
        raise Exception('GetCapabilities is not correctly encoded')
    
    wms130 = ServiceHandler130(conf, wms, "localhost")
    wms130.GetCapabilities({})

    return True
Esempio n. 4
0
def ogc_response(request, mapfactory):

    conf = SafeConfigParser()
    conf.readfp(open(base_path + "/ogcserver.conf"))

    reqparams = lowerparams(request.GET)
    if 'srs' in reqparams:
        reqparams['srs'] = str(reqparams['srs'])
    if 'styles' not in reqparams:
        reqparams['styles'] = ''

    onlineresource = 'http://%s%s?' % (request.META['HTTP_HOST'],
                                       request.META['PATH_INFO'])

    if not reqparams.has_key('request'):
        raise OGCException('Missing request parameter.')
    req = reqparams['request']
    del reqparams['request']
    if req == 'GetCapabilities' and not reqparams.has_key('service'):
        raise OGCException('Missing service parameter.')
    if req in ['GetMap', 'GetFeatureInfo']:
        service = 'WMS'
    else:
        service = reqparams['service']
    if reqparams.has_key('service'):
        del reqparams['service']
    try:
        ogcserver = __import__('ogcserver.' + service)
    except:
        raise OGCException('Unsupported service "%s".' % service)
    ServiceHandlerFactory = getattr(ogcserver, service).ServiceHandlerFactory
    servicehandler = ServiceHandlerFactory(conf, mapfactory, onlineresource,
                                           reqparams.get('version', None))
    if reqparams.has_key('version'):
        del reqparams['version']
    if req not in servicehandler.SERVICE_PARAMS.keys():
        raise OGCException('Operation "%s" not supported.' % request,
                           'OperationNotSupported')
    ogcparams = servicehandler.processParameters(req, reqparams)
    try:
        requesthandler = getattr(servicehandler, req)
    except:
        raise OGCException('Operation "%s" not supported.' % req,
                           'OperationNotSupported')

    # stick the user agent in the request params
    # so that we can add ugly hacks for specific buggy clients
    ogcparams['HTTP_USER_AGENT'] = request.META['HTTP_USER_AGENT']

    wms_resp = requesthandler(ogcparams)

    response = HttpResponse()
    response['Content-length'] = str(len(wms_resp.content))
    response['Content-Type'] = wms_resp.content_type
    response.write(wms_resp.content)

    return response
Esempio n. 5
0
 def __init__(self):
     self.conf = SafeConfigParser()
     self.conf.add_section('service')
     self.conf.add_section('contact')
     self.conf.set('service', 'allowedepsgcodes', '900913')
     self.conf.set('service', 'maxwidth', '4326')
     self.conf.set('service', 'maxheight', '4326')
     self.mapfactory = WMSFactory()
     self.debug = True
     self.max_age = None
     self.home_html = None
     self.fonts = None
Esempio n. 6
0
def ogc_response(request, mapfactory):
    
    conf = SafeConfigParser()
    conf.readfp(open(base_path+"/ogcserver.conf"))
    
    reqparams = lowerparams(request.GET)
    if 'srs' in reqparams:
        reqparams['srs'] = str(reqparams['srs'])
    if 'styles' not in reqparams:
        reqparams['styles'] = ''

    onlineresource = 'http://%s%s?' % (request.META['HTTP_HOST'], request.META['PATH_INFO'])

    if not reqparams.has_key('request'):
        raise OGCException('Missing request parameter.')
    req = reqparams['request']
    del reqparams['request']
    if req == 'GetCapabilities' and not reqparams.has_key('service'):
        raise OGCException('Missing service parameter.')
    if req in ['GetMap', 'GetFeatureInfo']:
        service = 'WMS'
    else:
        service = reqparams['service']
    if reqparams.has_key('service'):
        del reqparams['service']
    try:
        ogcserver = __import__('ogcserver.' + service)
    except:
        raise OGCException('Unsupported service "%s".' % service)
    ServiceHandlerFactory = getattr(ogcserver, service).ServiceHandlerFactory
    servicehandler = ServiceHandlerFactory(conf, mapfactory, onlineresource, reqparams.get('version', None))
    if reqparams.has_key('version'):
        del reqparams['version']
    if req not in servicehandler.SERVICE_PARAMS.keys():
        raise OGCException('Operation "%s" not supported.' % request, 'OperationNotSupported')
    ogcparams = servicehandler.processParameters(req, reqparams)
    try:
        requesthandler = getattr(servicehandler, req)
    except:
        raise OGCException('Operation "%s" not supported.' % req, 'OperationNotSupported')

    # stick the user agent in the request params
    # so that we can add ugly hacks for specific buggy clients
    ogcparams['HTTP_USER_AGENT'] = request.META['HTTP_USER_AGENT']

    wms_resp = requesthandler(ogcparams)    

    response = HttpResponse()
    response['Content-length'] = str(len(wms_resp.content))
    response['Content-Type'] = wms_resp.content_type
    response.write(wms_resp.content)
        
    return response
Esempio n. 7
0
 def __init__(self, configpath, mapfile=None,fonts=None,home_html=None):
     conf = SafeConfigParser()
     conf.readfp(open(configpath))
     # TODO - be able to supply in config as well
     self.home_html = home_html
     self.conf = conf
     if fonts:
         mapnik.register_fonts(fonts)
     if mapfile:
         wms_factory = BaseWMSFactory(configpath)
         # TODO - add support for Cascadenik MML
         wms_factory.loadXML(mapfile)
         wms_factory.finalize()
         self.mapfactory = wms_factory
     else:
         if not conf.has_option_with_value('server', 'module'):
             raise ServerConfigurationError('The factory module is not defined in the configuration file.')
         try:
             mapfactorymodule = do_import(conf.get('server', 'module'))
         except ImportError:
             raise ServerConfigurationError('The factory module could not be loaded.')
         if hasattr(mapfactorymodule, 'WMSFactory'):
             self.mapfactory = getattr(mapfactorymodule, 'WMSFactory')()
         else:
             raise ServerConfigurationError('The factory module does not have a WMSFactory class.')
     if conf.has_option('server', 'debug'):
         self.debug = int(conf.get('server', 'debug'))
     else:
         self.debug = 0
     if self.conf.has_option_with_value('server', 'maxage'):
         self.max_age = 'max-age=%d' % self.conf.get('server', 'maxage')
     else:
         self.max_age = None
Esempio n. 8
0
 def __init__(self, configpath):
     conf = SafeConfigParser()
     conf.readfp(open(configpath))
     self.conf = conf
     if not conf.has_option_with_value('server', 'module'):
         raise ServerConfigurationError(
             'The factory module is not defined in the configuration file.')
     try:
         mapfactorymodule = __import__(conf.get('server', 'module'))
     except ImportError:
         raise ServerConfigurationError(
             'The factory module could not be loaded.')
     if hasattr(mapfactorymodule, 'WMSFactory'):
         self.mapfactory = getattr(mapfactorymodule, 'WMSFactory')()
     else:
         raise ServerConfigurationError(
             'The factory module does not have a WMSFactory class.')
     if conf.has_option('server', 'debug'):
         self.debug = int(conf.get('server', 'debug'))
     else:
         self.debug = 0
     if self.conf.has_option_with_value('server', 'maxage'):
         self.max_age = 'max-age=%d' % self.conf.get('server', 'maxage')
     else:
         self.max_age = None
Esempio n. 9
0
def _wms_services(mapfile):
    base_path, tail = os.path.split(__file__)
    file_path = os.path.join(base_path, mapfile)
    wms = BaseWMSFactory()

    # Layer 'awkward-layer' contains a regular style named 'default', which will
    # be hidden by OGCServer's auto-generated 'default' style. A warning message
    # is written to sys.stderr in loadXML.
    # Since we don't want to see this several times while unit testing (nose only
    # redirects sys.stdout), we redirect sys.stderr here into a StringIO buffer
    # temporarily.
    # As a side effect, we can as well search for the warning message and fail the
    # test, if it occurs zero or more than one times per loadXML invocation. However,
    # this test highly depends on the warning message text.
    stderr = sys.stderr
    errbuf = StringIO.StringIO()
    sys.stderr = errbuf

    wms.loadXML(file_path)

    sys.stderr = stderr
    errbuf.seek(0)
    warnings = 0
    for line in errbuf:
        if line.strip('\r\n') == multi_style_err_text:
            warnings += 1
        else:
            sys.stderr.write(line)
    errbuf.close()

    if warnings == 0:
        raise Exception(
            'Expected warning message for layer \'awkward-layer\' not found in stderr stream.'
        )
    elif warnings > 1:
        raise Exception(
            'Expected warning message for layer \'awkward-layer\' occurred several times (%d) in stderr stream.'
            % warnings)

    wms.finalize()

    conf = SafeConfigParser()
    conf.readfp(open(os.path.join(base_path, 'ogcserver.conf')))

    wms111 = ServiceHandler111(conf, wms, "localhost")
    wms130 = ServiceHandler130(conf, wms, "localhost")

    return (conf, {'1.1.1': wms111, '1.3.0': wms130})
Esempio n. 10
0
def _wms_capabilities():
    base_path, tail = os.path.split(__file__)
    file_path = os.path.join(base_path, 'mapfile_encoding.xml')
    wms = BaseWMSFactory() 
    wms.loadXML(file_path)
    wms.finalize()

    conf = SafeConfigParser()
    conf.readfp(open(os.path.join(base_path, 'ogcserver.conf')))

    wms111 = ServiceHandler111(conf, wms, "localhost")
    wms130 = ServiceHandler130(conf, wms, "localhost")

    return (conf, {
        '1.1.1': wms111.GetCapabilities({}),
        '1.3.0': wms130.GetCapabilities({})
    })
Esempio n. 11
0
def _wms_capabilities():
    base_path, tail = os.path.split(__file__)
    file_path = os.path.join(base_path, 'mapfile_encoding.xml')
    wms = BaseWMSFactory()
    wms.loadXML(file_path)
    wms.finalize()

    conf = SafeConfigParser()
    conf.readfp(open(os.path.join(base_path, 'ogcserver.conf')))

    wms111 = ServiceHandler111(conf, wms, "localhost")
    wms130 = ServiceHandler130(conf, wms, "localhost")

    return (conf, {
        '1.1.1': wms111.GetCapabilities({}),
        '1.3.0': wms130.GetCapabilities({})
    })
Esempio n. 12
0
def _wms_services(mapfile):
    base_path, tail = os.path.split(__file__)
    file_path = os.path.join(base_path, mapfile)
    wms = BaseWMSFactory() 
    wms.loadXML(file_path)
    wms.finalize()

    conf = SafeConfigParser()
    conf.readfp(open(os.path.join(base_path, 'ogcserver.conf')))

    wms111 = ServiceHandler111(conf, wms, "localhost")
    wms130 = ServiceHandler130(conf, wms, "localhost")

    return (conf, {
        '1.1.1': wms111,
        '1.3.0': wms130
    })
Esempio n. 13
0
 def __init__(self):
     self.conf = SafeConfigParser()
     self.conf.add_section('service')
     self.conf.add_section('contact')
     self.conf.set('service','allowedepsgcodes', '900913')
     self.conf.set('service','maxwidth', '4326')
     self.conf.set('service','maxheight', '4326')
     self.mapfactory = WMSFactory()
     self.debug = True
     self.max_age = None
     self.home_html = None
     self.fonts = None
Esempio n. 14
0
 def __init__(self, url, logging, config=''):
     
     self.url = url 
     self.home_html = None
     self.logging = logging
     self.proto_schema = {
         "xml": {
             "test": self.is_xml,
             "get": self.get_mapnik,
             "request": self.request_mapnik,
             "metadata": self.get_metadata,
             "enable": True,
             },
     }
     # Load OGCServver config
     self.ogcserver = importlib.import_module('ogcserver')
     if os.path.isfile(config):
         self.ogc_configfile = config
     else:
         self.ogc_configfile = resource_filename(
             self.ogcserver.__name__, 'default.conf'
         )
     ogcconf = SafeConfigParser()
     ogcconf.readfp(open(self.ogc_configfile))
     self.ogcconf = ogcconf
     if ogcconf.has_option('server', 'debug'):
         self.debug = int(ogcconf.get('server', 'debug'))
     else:
         self.debug = 0
     self.mapnik_ver = mapnik_version()
Esempio n. 15
0
def test_encoding():
    import os
    from ogcserver.configparser import SafeConfigParser
    from ogcserver.WMS import BaseWMSFactory
    from ogcserver.wms111 import ServiceHandler as ServiceHandler111
    from ogcserver.wms130 import ServiceHandler as ServiceHandler130

    base_path, tail = os.path.split(__file__)
    file_path = os.path.join(base_path, 'shape_encoding.xml')
    wms = BaseWMSFactory() 
    wms.loadXML(file_path)
    wms.finalize()

    conf = SafeConfigParser()
    conf.readfp(open(os.path.join(base_path, 'ogcserver.conf')))

# srs = EPSG:4326
# 3.00 , 42,35 - 3.15 , 42.51
# x = 5 , y = 6
    params = {}
    params['srs'] = 'epsg:4326'
    params['x'] = 5
    params['y'] = 5
    params['bbox'] = [3.00,42.35,3.15,42.51]
    params['height'] = 10
    params['width'] = 10
    params['layers'] = ['row']
    params['styles'] = ''
    params['query_layers'] = ['row']

    for format in ['text/plain', 'text/xml']:
        params['info_format'] = format
        wms111 = ServiceHandler111(conf, wms, "localhost")
        result = wms111.GetFeatureInfo(params)
        
        wms130 = ServiceHandler130(conf, wms, "localhost")
        wms130.GetCapabilities({})


    return True
Esempio n. 16
0
 def __init__(self, configpath, mapfile=None, fonts=None, home_html=None):
     # 实例化 ConfigParser 并加载配置文件
     conf = SafeConfigParser()
     # 从配置文件读取并分析(分列)配置信息
     conf.readfp(open(configpath))
     # TODO - be able to supply in config as well
     self.home_html = home_html
     self.conf = conf
     if fonts:
         # 注册指定字体
         mapnik.register_fonts(fonts)
     if mapfile:
         # 生成BaseWMSFactory实例
         wms_factory = BaseWMSFactory(configpath)
         # TODO - add support for Cascadenik MML
         wms_factory.loadXML(mapfile)
         wms_factory.finalize()
         self.mapfactory = wms_factory
     else:
         # 阅读default.conf,有疑惑???
         #
         # 原default.conf文件中module未定义,需要使用要在default.conf中自行定义
         if not conf.has_option_with_value('server', 'module'):
             raise ServerConfigurationError(
                 'The factory module is not defined in the configuration file.'
             )
         # 导入指定module
         try:
             # get(section,option),Get an option value for the named
             # section.
             mapfactorymodule = do_import(conf.get('server', 'module'))
         except ImportError:
             raise ServerConfigurationError(
                 'The factory module could not be loaded.')
         if hasattr(mapfactorymodule, 'WMSFactory'):
             # Get a named attribute from an object; getattr(x, 'y') is
             # equivalent to x.y.
             self.mapfactory = getattr(mapfactorymodule, 'WMSFactory')()
         else:
             raise ServerConfigurationError(
                 'The factory module does not have a WMSFactory class.')
     if conf.has_option('server', 'debug'):
         self.debug = int(conf.get('server', 'debug'))
     else:
         self.debug = 0
     if self.conf.has_option_with_value('server', 'maxage'):
         self.max_age = 'max-age=%d' % self.conf.get('server', 'maxage')
     else:
         self.max_age = None
Esempio n. 17
0
def test_encoding():
    import os
    from ogcserver.configparser import SafeConfigParser
    from ogcserver.WMS import BaseWMSFactory
    from ogcserver.wms111 import ServiceHandler as ServiceHandler111
    from ogcserver.wms130 import ServiceHandler as ServiceHandler130

    base_path, tail = os.path.split(__file__)
    file_path = os.path.join(base_path, 'shape_encoding.xml')
    wms = BaseWMSFactory()
    wms.loadXML(file_path)
    wms.finalize()

    conf = SafeConfigParser()
    conf.readfp(open(os.path.join(base_path, 'ogcserver.conf')))

    # srs = EPSG:4326
    # 3.00 , 42,35 - 3.15 , 42.51
    # x = 5 , y = 6
    params = {}
    params['srs'] = 'epsg:4326'
    params['x'] = 5
    params['y'] = 5
    params['bbox'] = [3.00, 42.35, 3.15, 42.51]
    params['height'] = 10
    params['width'] = 10
    params['layers'] = ['row']
    params['styles'] = ''
    params['query_layers'] = ['row']

    for format in ['text/plain', 'text/xml']:
        params['info_format'] = format
        wms111 = ServiceHandler111(conf, wms, "localhost")
        result = wms111.GetFeatureInfo(params)

        wms130 = ServiceHandler130(conf, wms, "localhost")
        wms130.GetCapabilities({})

    return True
Esempio n. 18
0
 def __init__(self, home_html=None):
     conf = SafeConfigParser()
     conf.readfp(open(self.configpath))
     # TODO - be able to supply in config as well
     self.home_html = home_html
     self.conf = conf
     if not conf.has_option_with_value('server', 'module'):
         raise ServerConfigurationError(
             'The factory module is not defined in the configuration file.')
     try:
         mapfactorymodule = __import__(conf.get('server', 'module'))
     except ImportError:
         raise ServerConfigurationError(
             'The factory module could not be loaded.')
     if hasattr(mapfactorymodule, 'WMSFactory'):
         self.mapfactory = getattr(mapfactorymodule, 'WMSFactory')()
     else:
         raise ServerConfigurationError(
             'The factory module does not have a WMSFactory class.')
     if conf.has_option('server', 'debug'):
         self.debug = int(conf.get('server', 'debug'))
     else:
         self.debug = 0
Esempio n. 19
0
 def __init__(self, home_html=None):
     conf = SafeConfigParser()
     conf.readfp(open(self.configpath))
     # TODO - be able to supply in config as well
     self.home_html = home_html
     self.conf = conf
     if not conf.has_option_with_value('server', 'module'):
         raise ServerConfigurationError('The factory module is not defined in the configuration file.')
     try:
         mapfactorymodule = __import__(conf.get('server', 'module'))
     except ImportError:
         raise ServerConfigurationError('The factory module could not be loaded.')
     if hasattr(mapfactorymodule, 'WMSFactory'):
         self.mapfactory = getattr(mapfactorymodule, 'WMSFactory')()
     else:
         raise ServerConfigurationError('The factory module does not have a WMSFactory class.')
     if conf.has_option('server', 'debug'):
         self.debug = int(conf.get('server', 'debug'))
     else:
         self.debug = 0
Esempio n. 20
0
 def __init__(self, configpath):
     conf = SafeConfigParser()
     conf.readfp(open(configpath))
     self.conf = conf
     if not conf.has_option_with_value('server', 'module'):
         raise ServerConfigurationError('The factory module is not defined in the configuration file.')
     try:
         mapfactorymodule = __import__(conf.get('server', 'module'))
     except ImportError:
         raise ServerConfigurationError('The factory module could not be loaded.')
     if hasattr(mapfactorymodule, 'WMSFactory'):
         self.mapfactory = getattr(mapfactorymodule, 'WMSFactory')()
     else:
         raise ServerConfigurationError('The factory module does not have a WMSFactory class.')
     if conf.has_option('server', 'debug'):
         self.debug = int(conf.get('server', 'debug'))
     else:
         self.debug = 0
     if self.conf.has_option_with_value('server', 'maxage'):
         self.max_age = 'max-age=%d' % self.conf.get('server', 'maxage')
     else:
         self.max_age = None
Esempio n. 21
0
 def __init__(self):
     conf = SafeConfigParser()
     conf.readfp(open(settings.MAPNIK_CONFIGFILE))
     self.conf = conf
     self.mapfactory = WMSFactory()
Esempio n. 22
0
class WSGIApp:
    def __init__(self):
        self.conf = SafeConfigParser()
        self.conf.add_section('service')
        self.conf.add_section('contact')
        self.conf.set('service', 'allowedepsgcodes', '900913')
        self.conf.set('service', 'maxwidth', '4326')
        self.conf.set('service', 'maxheight', '4326')
        self.mapfactory = WMSFactory()
        self.debug = True
        self.max_age = None
        self.home_html = None
        self.fonts = None

    def __call__(self, environ, start_response):
        reqparams = {}
        base = True
        for key, value in parse_qs(environ['QUERY_STRING'], True).items():
            reqparams[key.lower()] = value[0]
            base = False

        if self.conf.has_option_with_value('service', 'baseurl'):
            onlineresource = '%s' % self.conf.get('service', 'baseurl')
        else:
            # if there is no baseurl in the config file try to guess a valid one
            onlineresource = 'http://%s%s%s?' % (environ['HTTP_HOST'],
                                                 environ['SCRIPT_NAME'],
                                                 environ['PATH_INFO'])

        try:
            if not reqparams.has_key('request'):
                raise OGCException('Missing request parameter.')
            request = reqparams['request']
            del reqparams['request']
            if request == 'GetCapabilities' and not reqparams.has_key(
                    'service'):
                raise OGCException('Missing service parameter.')
            if request in ['GetMap', 'GetFeatureInfo']:
                service = 'WMS'
            else:
                try:
                    service = reqparams['service']
                except:
                    service = 'WMS'
                    request = 'GetCapabilities'
            if reqparams.has_key('service'):
                del reqparams['service']
            try:
                ogcserver = do_import('ogcserver')
            except:
                raise OGCException('Unsupported service "%s".' % service)
            ServiceHandlerFactory = getattr(ogcserver,
                                            service).ServiceHandlerFactory
            servicehandler = ServiceHandlerFactory(
                self.conf, self.mapfactory, onlineresource,
                reqparams.get('version', None))
            if reqparams.has_key('version'):
                del reqparams['version']
            if request not in servicehandler.SERVICE_PARAMS.keys():
                raise OGCException('Operation "%s" not supported.' % request,
                                   'OperationNotSupported')
            ogcparams = servicehandler.processParameters(request, reqparams)
            try:
                requesthandler = getattr(servicehandler, request)
            except:
                raise OGCException('Operation "%s" not supported.' % request,
                                   'OperationNotSupported')

            # stick the user agent in the request params
            # so that we can add ugly hacks for specific buggy clients
            ogcparams['HTTP_USER_AGENT'] = environ.get('HTTP_USER_AGENT', '')

            response = requesthandler(ogcparams)
        except:
            version = reqparams.get('version', None)
            if not version:
                version = Version()
            else:
                version = Version(version)
            if version >= '1.3.0':
                eh = ExceptionHandler130(self.debug, base, self.home_html)
            else:
                eh = ExceptionHandler111(self.debug, base, self.home_html)
            response = eh.getresponse(reqparams)
        response_headers = [('Content-Type', response.content_type),
                            ('Content-Length', str(len(response.content)))]
        if self.max_age:
            response_headers.append(('Cache-Control', self.max_age))
        start_response('200 OK', response_headers)
        yield response.content
Esempio n. 23
0
class WSGIApp:
    def __init__(self):
        self.conf = SafeConfigParser()
        self.conf.add_section('service')
        self.conf.add_section('contact')
        self.conf.set('service','allowedepsgcodes', '900913')
        self.conf.set('service','maxwidth', '4326')
        self.conf.set('service','maxheight', '4326')
        self.mapfactory = WMSFactory()
        self.debug = True
        self.max_age = None
        self.home_html = None
        self.fonts = None

    def __call__(self, environ, start_response):
        reqparams = {}
        base = True
        for key, value in parse_qs(environ['QUERY_STRING'], True).items():
            reqparams[key.lower()] = value[0]
            base = False

        if self.conf.has_option_with_value('service', 'baseurl'):
            onlineresource = '%s' % self.conf.get('service', 'baseurl')
        else:
            # if there is no baseurl in the config file try to guess a valid one
            onlineresource = 'http://%s%s%s?' % (environ['HTTP_HOST'], environ['SCRIPT_NAME'], environ['PATH_INFO'])

        try:
            if not reqparams.has_key('request'):
                raise OGCException('Missing request parameter.')
            request = reqparams['request']
            del reqparams['request']
            if request == 'GetCapabilities' and not reqparams.has_key('service'):
                raise OGCException('Missing service parameter.')
            if request in ['GetMap', 'GetFeatureInfo']:
                service = 'WMS'
            else:
                try:
                    service = reqparams['service']
                except:
                    service = 'WMS'
                    request = 'GetCapabilities'
            if reqparams.has_key('service'):
                del reqparams['service']
            try:
                ogcserver = do_import('ogcserver')
            except:
                raise OGCException('Unsupported service "%s".' % service)
            ServiceHandlerFactory = getattr(ogcserver, service).ServiceHandlerFactory
            servicehandler = ServiceHandlerFactory(self.conf, self.mapfactory, onlineresource, reqparams.get('version', None))
            if reqparams.has_key('version'):
                del reqparams['version']
            if request not in servicehandler.SERVICE_PARAMS.keys():
                raise OGCException('Operation "%s" not supported.' % request, 'OperationNotSupported')
            ogcparams = servicehandler.processParameters(request, reqparams)
            try:
                requesthandler = getattr(servicehandler, request)
            except:
                raise OGCException('Operation "%s" not supported.' % request, 'OperationNotSupported')

            # stick the user agent in the request params
            # so that we can add ugly hacks for specific buggy clients
            ogcparams['HTTP_USER_AGENT'] = environ.get('HTTP_USER_AGENT', '')

            response = requesthandler(ogcparams)
        except:
            version = reqparams.get('version', None)
            if not version:
                version = Version()
            else:
                version = Version(version)
            if version >= '1.3.0':
                eh = ExceptionHandler130(self.debug,base,self.home_html)
            else:
                eh = ExceptionHandler111(self.debug,base,self.home_html)
            response = eh.getresponse(reqparams)
        response_headers = [('Content-Type', response.content_type),('Content-Length', str(len(response.content)))]
        if self.max_age:
            response_headers.append(('Cache-Control', self.max_age))
        start_response('200 OK', response_headers)
        yield response.content