Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_write(self):
configuration.CONFIG.set('server', 'outputpath', self.tmp_dir)
configuration.CONFIG.set('server', 'outputurl', 'file://' + self.tmp_dir)
storage = FileStorageBuilder().build()
output = ComplexOutput('testme', 'Test', supported_formats=[FORMATS.TEXT], workdir=self.tmp_dir)
output.data = "Hello World!"
url = storage.write(output.data, 'foo.txt')
self.assertEqual(url, 'file://' + self.tmp_dir + '/foo.txt')
with open(self.tmp_dir + '/foo.txt') as f:
self.assertEqual(f.read(), "Hello World!")
def json(self):
"""Convert the response to JSON structure
"""
processes = [p.json for p in self.processes.values()]
return {
'pywps_version': __version__,
'version': self.version,
'title': config.get_config_value('metadata:main', 'identification_title'),
'abstract': config.get_config_value('metadata:main', 'identification_abstract'),
'keywords': config.get_config_value('metadata:main', 'identification_keywords').split(","),
'keywords_type': config.get_config_value('metadata:main', 'identification_keywords_type').split(","),
'fees': config.get_config_value('metadata:main', 'identification_fees'),
'accessconstraints': config.get_config_value(
'metadata:main',
'identification_accessconstraints'
).split(','),
'profile': config.get_config_value('metadata:main', 'identification_profile'),
'provider': {
'name': config.get_config_value('metadata:main', 'provider_name'),
'site': config.get_config_value('metadata:main', 'provider_url'),
'individual': config.get_config_value('metadata:main', 'contact_name'),
'position': config.get_config_value('metadata:main', 'contact_position'),
'voice': config.get_config_value('metadata:main', 'contact_phone'),
'fascimile': config.get_config_value('metadata:main', 'contaact_fax'),
else:
# if not found then take the first
exc_tb = sys.exc_info()[2]
break
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
method_name = exc_tb.tb_frame.f_code.co_name
# update the process status to display process failed
msg = 'Process error: method={}.{}, line={}, msg={}'.format(fname, method_name, exc_tb.tb_lineno, e)
LOGGER.error(msg)
# In case of a ProcessError use the validated exception message.
if isinstance(e, ProcessError):
msg = "Process error: {}".format(e)
# Only in debug mode we use the log message including the traceback ...
elif config.get_config_value("logging", "level") != "DEBUG":
# ... otherwise we use a sparse common error message.
msg = 'Process failed, please check server error log'
wps_response._update_status(WPS_STATUS.FAILED, msg, 100)
finally:
# The run of the next pending request if finished here, weather or not it successfull
self.launch_next_process()
return wps_response
def Process(process, wps_request, wps_response):
"""
Factory method (looking like a class) to return the
configured processing class.
:return: instance of :class:`pywps.processing.Processing`
"""
mode = config.get_config_value("processing", "mode")
LOGGER.info("Processing mode: {}".format(mode))
if mode == SCHEDULER:
process = Scheduler(process, wps_request, wps_response)
else:
process = MultiProcessing(process, wps_request, wps_response)
return process
def cache_path():
cache_path = configuration.get_config_value("cache", "cache_path")
if not cache_path:
LOGGER.warn("No cache path configured. Using default value.")
cache_path = os.path.join(configuration.get_config_value("server", "outputpath"), "cache")
return cache_path
def _post_request(self):
"""HTTP GET request parser
"""
# check if input file size was not exceeded
maxsize = configuration.get_config_value('server', 'maxrequestsize')
maxsize = configuration.get_size_mb(maxsize) * 1024 * 1024
if self.http_request.content_length > maxsize:
raise FileSizeExceeded('File size for input exceeded.'
' Maximum request size allowed: %i megabytes' % (maxsize / 1024 / 1024))
try:
doc = lxml.etree.fromstring(self.http_request.get_data())
except Exception as e:
if PY2:
raise NoApplicableCode(e.message)
else:
raise NoApplicableCode(e.msg)
operation = doc.tag
version = get_version_from_ns(doc.nsmap[doc.prefix])
self.set_version(version)
request_parser = self._post_request_parser(operation)
def _get_serviceinstance(self):
url = config.get_config_value("server", "url")
params = {'request': 'GetCapabilities', 'service': 'WPS'}
url_parts = list(urlparse.urlparse(url))
query = dict(urlparse.parse_qsl(url_parts[4]))
query.update(params)
url_parts[4] = urlencode(query)
return urlparse.urlunparse(url_parts).replace("&", "&")
import json
import os
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, VARCHAR, Float, DateTime, LargeBinary
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import NullPool, StaticPool
LOGGER = logging.getLogger('PYWPS')
_SESSION_MAKER = None
_LAST_SESSION = None
_tableprefix = configuration.get_config_value('logging', 'prefix')
_schema = configuration.get_config_value('logging', 'schema')
Base = declarative_base()
class ProcessInstance(Base):
__tablename__ = '{}requests'.format(_tableprefix)
uuid = Column(VARCHAR(255), primary_key=True, nullable=False)
pid = Column(Integer, nullable=False)
operation = Column(VARCHAR(30), nullable=False)
version = Column(VARCHAR(5), nullable=False)
time_start = Column(DateTime(), nullable=False)
time_end = Column(DateTime(), nullable=True)
identifier = Column(VARCHAR(255), nullable=True)
message = Column(String, nullable=True)
percent_done = Column(Float, nullable=True)
try:
nc_file = opendap_or_download(
one_resource.data,
auth_tkt_cookie=request.http_request.cookies,
output_path='/tmp')
except Exception:
raise Exception(traceback.format_exc())
list_of_files.append(nc_file)
if ('typename' in request.inputs) and ('featureids' in request.inputs):
typename = request.inputs['typename'][0].data
features = [f.data for f in request.inputs['featureids']]
if 'geoserver' in request.inputs:
geoserver = request.inputs['geoserver'][0].data
else:
geoserver = configuration.get_config_value('extra', 'geoserver')
if 'mosaic' in request.inputs:
mosaic = request.inputs['mosaic'][0].data
else:
mosaic = False
try:
conn = WebFeatureService(url=geoserver, version='2.0.0')
resp = conn.getfeature([typename], featureid=features,
outputFormat='application/json')
feature = json.loads(resp.read())
crs_code = owslib.crs.Crs(
feature['crs']['properties']['name']).code
crs = ocgis.CoordinateReferenceSystem(epsg=crs_code)
geom = [
{'geom': shape(f['geometry']), 'crs': crs,
'properties': f['properties']}
for f in feature['features']]
def _construct_doc(self):
if not self.identifiers:
raise MissingParameterValue('Missing parameter value "identifier"', 'identifier')
template = self.template_env.get_template(self.version + '/describe/main.xml')
max_size = int(config.get_size_mb(config.get_config_value('server', 'maxsingleinputsize')))
doc = template.render(max_size=max_size, **self.json)
return doc