本文整理汇总了Python中owslib.wps.WebProcessingService.getcapabilities方法的典型用法代码示例。如果您正苦于以下问题:Python WebProcessingService.getcapabilities方法的具体用法?Python WebProcessingService.getcapabilities怎么用?Python WebProcessingService.getcapabilities使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类owslib.wps.WebProcessingService
的用法示例。
在下文中一共展示了WebProcessingService.getcapabilities方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_wps_getcapabilities_usgs
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
def test_wps_getcapabilities_usgs():
# Initialize WPS client
wps = WebProcessingService('http://cida.usgs.gov/gdp/process/WebProcessingService', skip_caps=True)
# Execute fake invocation of GetCapabilities operation by parsing cached response from USGS service
xml = open(resource_file('wps_USGSCapabilities.xml'), 'rb').read()
wps.getcapabilities(xml=xml)
# Check WPS description
assert wps.updateSequence is not None
assert wps.identification.type == 'WPS'
assert wps.identification.title == 'Geo Data Portal WPS Implementation'
assert wps.identification.abstract == 'A Geo Data Portal Service based on the 52north implementation of WPS 1.0.0'
# Check available operations
operations = [op.name for op in wps.operations]
assert operations == [
'GetCapabilities',
'DescribeProcess',
'Execute']
# Check high level process descriptions
processes = [(p.identifier, p.title) for p in wps.processes]
assert processes == [
('gov.usgs.cida.gdp.wps.algorithm.filemanagement.ReceiveFiles', 'gov.usgs.cida.gdp.wps.algorithm.filemanagement.ReceiveFiles'), # noqa
('gov.usgs.cida.gdp.wps.algorithm.discovery.CalculateWCSCoverageInfo', 'gov.usgs.cida.gdp.wps.algorithm.discovery.CalculateWCSCoverageInfo'), # noqa
('gov.usgs.cida.gdp.wps.algorithm.communication.EmailWhenFinishedAlgorithm', 'gov.usgs.cida.gdp.wps.algorithm.communication.EmailWhenFinishedAlgorithm'), # noqa
('gov.usgs.cida.gdp.wps.algorithm.communication.GeoserverManagementAlgorithm', 'gov.usgs.cida.gdp.wps.algorithm.communication.GeoserverManagementAlgorithm'), # noqa
('gov.usgs.cida.gdp.wps.algorithm.discovery.GetWcsCoverages', 'gov.usgs.cida.gdp.wps.algorithm.discovery.GetWcsCoverages'), # noqa
('gov.usgs.cida.gdp.wps.algorithm.filemanagement.GetWatersGeom', 'gov.usgs.cida.gdp.wps.algorithm.filemanagement.GetWatersGeom'), # noqa
('gov.usgs.cida.gdp.wps.algorithm.discovery.ListOpendapGrids', 'gov.usgs.cida.gdp.wps.algorithm.discovery.ListOpendapGrids'), # noqa
('gov.usgs.cida.gdp.wps.algorithm.filemanagement.CreateNewShapefileDataStore', 'gov.usgs.cida.gdp.wps.algorithm.filemanagement.CreateNewShapefileDataStore'), # noqa
('gov.usgs.cida.gdp.wps.algorithm.discovery.GetGridTimeRange', 'gov.usgs.cida.gdp.wps.algorithm.discovery.GetGridTimeRange'), # noqa
]
示例2: wps
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
def wps():
'''Returns a WPS instance'''
# Initialize WPS client
wps = WebProcessingService('http://example.org/wps', skip_caps=True)
xml = open(resource_file('wps_CEDACapabilities.xml'), 'rb').read()
wps.getcapabilities(xml=xml)
return wps
示例3: test_wps_getcapabilities_52n
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
def test_wps_getcapabilities_52n():
# Initialize WPS client
wps = WebProcessingService(
'http://geoprocessing.demo.52north.org:8080/52n-wps-webapp-3.3.1/WebProcessingService',
skip_caps=True)
# Execute fake invocation of GetCapabilities operation by parsing cached response from 52North service
xml = open(resource_file('wps_52nCapabilities.xml'), 'rb').read()
wps.getcapabilities(xml=xml)
# Check WPS description
assert wps.identification.type == 'WPS'
# Check available operations
operations = [op.name for op in wps.operations]
assert operations == [
'GetCapabilities',
'DescribeProcess',
'Execute']
# Check high level process descriptions
processes = [(p.identifier, p.title) for p in wps.processes]
assert processes == [
('org.n52.wps.server.algorithm.test.MultiReferenceInputAlgorithm', 'for testing multiple inputs by reference'),
('org.n52.wps.server.algorithm.test.EchoProcess', 'Echo process'),
('org.n52.wps.server.algorithm.test.MultiReferenceBinaryInputAlgorithm', 'for testing multiple binary inputs by reference'), # noqa
('org.n52.wps.server.algorithm.test.LongRunningDummyTestClass', 'org.n52.wps.server.algorithm.test.LongRunningDummyTestClass'), # noqa
('org.n52.wps.server.algorithm.JTSConvexHullAlgorithm', 'org.n52.wps.server.algorithm.JTSConvexHullAlgorithm'),
('org.n52.wps.server.algorithm.test.MultipleComplexInAndOutputsDummyTestClass', 'org.n52.wps.server.algorithm.test.MultipleComplexInAndOutputsDummyTestClass'), # noqa
('org.n52.wps.server.algorithm.test.DummyTestClass', 'org.n52.wps.server.algorithm.test.DummyTestClass')]
示例4: run_wps
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
def run_wps(process_id,input,output):
#choose the first wps engine
my_engine = WebProcessingService('http://appsdev.hydroshare.org:8282/wps/WebProcessingService', verbose=False, skip_caps=True)
my_engine.getcapabilities()
my_process = my_engine.describeprocess(process_id)
my_inputs = my_process.dataInputs
input_names = [] #getting list of input
for input1 in my_inputs:
input_names.append(input1)
#executing the process..
execution = my_engine.execute(process_id, input, output)
request = execution.request
#set store executeresponse to false
request = request.replace('storeExecuteResponse="true"', 'storeExecuteResponse="false"')
url_wps = 'http://appsdev.hydroshare.org:8282/wps/WebProcessingService'
wps_request = urllib2.Request(url_wps,request)
wps_open = urllib2.urlopen(wps_request)
wps_read = wps_open.read()
if 'href' in wps_read:
tag = 'href="'
location = wps_read.find(tag)
new= wps_read[location+len(tag):len(wps_read)]
tag2 = '"/>\n </wps:Output>\n </wps:ProcessOutputs>\n</wps:'
location2 = new.find(tag2)
final = new[0:location2]
split = final.split()
wps_request1 = urllib2.Request(split[0])
wps_open1 = urllib2.urlopen(wps_request1)
wps_read1 = wps_open1.read()
#return [final_output_url, final_data]
return [wps_read1, split]
示例5: test_wps_getcapabilities_ceda
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
def test_wps_getcapabilities_ceda():
# Initialize WPS client
wps = WebProcessingService('http://ceda-wps2.badc.rl.ac.uk/wps', skip_caps=True)
# Execute fake invocation of GetCapabilities operation by parsing cached response from USGS service
xml = open(resource_file('wps_CEDACapabilities.xml'), 'rb').read()
wps.getcapabilities(xml=xml)
# Check WPS description
assert wps.identification.type == 'WPS'
assert wps.identification.title == 'WPS Pylons Test Server'
assert wps.identification.abstract is None
# Check available operations
operations = [op.name for op in wps.operations]
assert operations == [
'GetCapabilities',
'DescribeProcess',
'Execute']
# Check high level process descriptions
processes = [(p.identifier, p.title) for p in wps.processes]
assert processes == [
('CDMSSubsetVariable', 'Writes a text file and returns an output.'),
('NCDumpIt', 'Calls ncdump on the input file path and writes it to an output file.'),
('TestDap', 'Writes a text file and returns an output.'),
('CDMSDescribeVariableDomain', 'Writes a text file and returns an output.'),
('CFCheck', 'Writes a text file and returns an output.'),
('DoubleIt', 'Doubles the input number and returns value'),
('SimplePlot', 'Creates a simple map plot.'),
('CDMSListDatasets', 'Writes a text file and returns an output.'),
('CDMSListVariables', 'Writes a text file and returns an output.'),
('WCSWrapper', 'Web Coverage Service Wrapper Process'),
('GetWeatherStations', 'Writes a text file with one weather station per line'),
('ListPPFileHeader', 'Writes a text file that contains a listing of pp-records in a file.'),
('TakeAges', 'A test process to last a long time.'),
('CMIP5FileFinder', 'Writes a test file of matched CMIP5 files.'),
('SubsetPPFile', 'Filters a PP-file to generate a new subset PP-file.'),
('ExtractUKStationData', 'ExtractUKStationData'),
('CDOWrapper1', 'Writes a text file and returns an output.'),
('MMDNCDiff', 'MMDNCDiff'),
('PlotRotatedGrid', 'Creates a plot - to show we can plot a rotated grid.'),
('MMDAsync', 'Writes a text file and returns an output.'),
('MashMyDataMultiplier', 'Writes a text file and returns an output.'),
('Delegator', 'Writes a text file and returns an output.'),
('ExArchProc1', 'Writes a text file and returns an output.'),
('CDOShowInfo', 'Writes a text file and returns an output.'),
('PostTest', 'Writes a text file and returns an output.'),
('StatusTestProcess', 'An process to test status responses'),
('WaitForFileDeletionCached', 'An asynchronous job that waits for a file to be deleted'),
('WaitForAllFilesToBeDeleted', 'An asynchronous job that waits for a number of files to be deleted'),
('AsyncTest', 'Does an asynchronous test job run'),
('SyncTest1', 'Just creates a file.'),
('WaitForFileDeletion', 'An asynchronous job that waits for a file to be deleted'),
('ProcessTemplate', 'Writes a text file and returns an output.')]
示例6: run_wps
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
def run_wps(process_id,input,output):
#choose the first wps engine
#my_engine = WebProcessingService('http://appsdev.hydroshare.org:8282/wps/WebProcessingService', verbose=False, skip_caps=True)
my_engine = WebProcessingService('http://appsdev.hydroshare.org:8282/wps/WebProcessingService',verbose=False, skip_caps=True)
my_engine.getcapabilities()
#wps_engines = list_wps_service_engines()
#my_engine = wps_engines[0]
#choose the r.time-series-converter
my_process = my_engine.describeprocess(process_id)
my_inputs = my_process.dataInputs
input_names = [] #getting list of input
for input1 in my_inputs:
input_names.append(input1)
#executing the process..
execution = my_engine.execute(process_id, input, output)
request = execution.request
#set store executeresponse to false
request = request.replace('storeExecuteResponse="true"', 'storeExecuteResponse="false"')
url_wps = 'http://appsdev.hydroshare.org:8282/wps/WebProcessingService'
wps_request = urllib2.Request(url_wps,request)
wps_open = urllib2.urlopen(wps_request)
wps_read = wps_open.read()
if 'href' in wps_read:
tag = 'href="'
location = wps_read.find(tag)
new= wps_read[location+len(tag):len(wps_read)]
tag2 = '"/>\n </wps:Output>\n </wps:ProcessOutputs>\n</wps:'
location2 = new.find(tag2)
final = new[0:location2]
split = final.split()
wps_request1 = urllib2.Request(split[0])
wps_open1 = urllib2.urlopen(wps_request1)
wps_read1 = wps_open1.read()
#now we must use our own method to send the request1
#we need to use the request
#this code is for the normal wps which is not working right now
# monitorExecution(execution)
# output_data = execution.processOutputs
# final_output_url = output_data[0].reference
# final_data = read_final_data(final_output_url)
#return [final_output_url, final_data]
return [wps_read1, split]
示例7: pyGDPwebProcessing
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
class pyGDPwebProcessing():
"""
This class allows interactive calls to be made into the GDP.
"""
def __init__(self, wfs_url=WFS_URL):
# if WFS_URL is None:
# from pygdp.namespaces import WFS_URL
# wfsUrl = WFS_URL
self.wfsUrl = wfs_url
self.wpsUrl = WPS_URL
self.version = '1.1.0'
self.wps = WebProcessingService(self.wpsUrl)
def WPSgetCapabilities(self, xml=None):
"""
Returns a list of capabilities.
"""
self.wps.getcapabilities(xml)
def WPSdescribeprocess(self, identifier, xml=None):
"""
Returns a list describing a specific identifier/process.
"""
self.wps.describeprocess(identifier, xml)
# pyGDP Submit Feature
def dodsReplace(self, dataSetURI, verbose=False):
if verbose:
ch.setLevel(logging.INFO)
return _execute_request.dodsReplace(dataSetURI, verbose)
def submitFeatureCoverageOPenDAP(self, geoType, dataSetURI, varID, startTime, endTime, attribute='the_geom',
value=None, gmlIDs=None, verbose=False, coverage=True, outputfname=None,
sleepSecs=10, async=False):
if verbose:
ch.setLevel(logging.INFO)
return feature_coverage.submitFeatureCoverageOPenDAP(geoType, dataSetURI, varID, startTime,
endTime, attribute, value, gmlIDs, verbose,
coverage, self.wfsUrl, outputfname, sleepSecs, async=async)
示例8: pyGDPwebProcessing
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
class pyGDPwebProcessing():
"""
This class allows interactive calls to be made into the GDP.
"""
def __init__(self, WFS_URL=None):
if WFS_URL==None:
from pygdp.namespaces import WFS_URL
wfsUrl=WFS_URL
self.wfsUrl = wfsUrl
self.wpsUrl = WPS_URL
self.version = '1.1.0'
self.wps = WebProcessingService(WPS_URL)
def WPSgetCapbilities(self, xml=None):
"""
Returns a list of capabilities.
"""
self.wps.getcapabilities(xml)
def WPSdescribeprocess(self, identifier, xml=None):
"""
Returns a list describing a specific identifier/process.
"""
self.wps.describeprocess(identifier, xml)
#pyGDP Submit Feature
def dodsReplace(self, dataSetURI, verbose=False):
if verbose:
ch.setLevel(logging.INFO)
return _execute_request.dodsReplace(dataSetURI, verbose)
def submitFeatureCoverageOPenDAP(self, geoType, dataSetURI, varID, startTime, endTime, attribute='the_geom', value=None, gmlIDs=None,
verbose=False, coverage='true', outputfname=None, sleepSecs=10):
if verbose:
ch.setLevel(logging.INFO)
return feature_coverage.submitFeatureCoverageOPenDAP(geoType, dataSetURI, varID, startTime, endTime, attribute, value, gmlIDs, verbose, coverage, self.wfsUrl, outputfname, sleepSecs)
def submitFeatureCoverageWCSIntersection(self, geoType, dataSetURI, varID, attribute='the_geom', value=None, gmlIDs=None, verbose=False,
coverage='true', outputfname=None, sleepSecs=10):
if verbose:
ch.setLevel(logging.INFO)
return feature_coverage.submitFeatureCoverageWCSIntersection(geoType, dataSetURI, varID, attribute, value, gmlIDs, verbose, coverage, self.wfsUrl, outputfname, sleepSecs)
def submitFeatureCategoricalGridCoverage(self, geoType, dataSetURI, varID, attribute='the_geom', value=None, gmlIDs=None, verbose=False,
coverage='true', delim='COMMA', outputfname=None, sleepSecs=10):
if verbose:
ch.setLevel(logging.INFO)
return feature_coverage.submitFeatureCategoricalGridCoverage(geoType, dataSetURI, varID, attribute, value, gmlIDs, verbose, coverage, delim, self.wfsUrl, outputfname, sleepSecs)
def submitFeatureWeightedGridStatistics(self, geoType, dataSetURI, varID, startTime, endTime, attribute='the_geom', value=None,
gmlIDs=None, verbose=None, coverage=True, delim='COMMA', stat='MEAN', grpby='STATISTIC',
timeStep=False, summAttr=False, weighted=True, outputfname=None, sleepSecs=10):
if verbose:
ch.setLevel(logging.INFO)
return fwgs.submitFeatureWeightedGridStatistics(geoType, dataSetURI, varID, startTime, endTime, attribute, value, gmlIDs,
verbose, coverage, delim, stat, grpby, timeStep, summAttr, weighted, self.wfsUrl, outputfname, sleepSecs)
#pyGDP File Utilities
def shapeToZip(self, inShape, outZip=None, allFiles=True):
return shape_to_zip.shapeToZip(inShape, outZip=None, allFiles=True)
def uploadShapeFile(self, filePath):
value, ntuple = upload_shapefile.uploadShapefile(filePath)
return value, ntuple
#pyGDP WFS Utilities
def getTuples(self, shapefile, attribute):
return shapefile_id_handle.getTuples(shapefile, attribute)
def getShapefiles(self):
return shapefile_value_handle.getShapefiles(self.wfsUrl)
def getAttributes(self, shapefile):
return shapefile_value_handle.getAttributes(shapefile, self.wfsUrl)
def getValues(self, shapefile, attribute, getTuples='false', limitFeatures=None):
return shapefile_value_handle.getValues(shapefile, attribute, getTuples, limitFeatures, self.wfsUrl)
def getGMLIDs(self, shapefile, attribute, value):
return shapefile_id_handle.getGMLIDs(shapefile, attribute, value, WFS_URL=self.wfsUrl)
def _getFilterID(self, tuples, value):
return shapefile_id_handle._getFilterID(tuples, value)
def _getFeatureCollectionGeoType(self, geoType, attribute='the_geom', value=None, gmlIDs=None):
return _get_geotype._getFeatureCollectionGeoType(geoType, attribute, value, gmlIDs, self.wfsUrl)
def _generateRequest(self, dataSetURI, algorithm, method, varID=None, verbose=False):
return _webdata_xml_generate._generateRequest(dataSetURI, algorithm, method, varID, verbose)
#pyGDP WebData Utilities
def getDataLongName(self, dataSetURI, verbose=False):
if verbose:
ch.setLevel(logging.INFO)
return webdata_handle.getDataLongName(dataSetURI, verbose)
def getDataType(self, dataSetURI, verbose=False):
if verbose:
ch.setLevel(logging.INFO)
return webdata_handle.getDataType(dataSetURI, verbose)
#.........这里部分代码省略.........
示例9: in
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
identifier = arg
elif opt in ("-v", "--verbose"):
verbose = True
else:
assert False, "Unhandled option"
# required arguments for all requests
if request is None or url is None:
usage()
sys.exit(3)
# instantiate client
wps = WebProcessingService(url, verbose=verbose, skip_caps=True)
if request == "GetCapabilities":
wps.getcapabilities()
print("WPS Identification type: %s" % wps.identification.type)
print("WPS Identification title: %s" % wps.identification.title)
print("WPS Identification abstract: %s" % wps.identification.abstract)
for operation in wps.operations:
print("WPS Operation: %s" % operation.name)
for process in wps.processes:
print("WPS Process: identifier=%s title=%s" % (process.identifier, process.title))
elif request == "DescribeProcess":
if identifier is None:
print('\nERROR: missing mandatory "-i (or --identifier)" argument')
usage()
sys.exit(4)
process = wps.describeprocess(identifier)
print("WPS Process: identifier=%s" % process.identifier)
示例10: pyGDPwebProcessing
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
class pyGDPwebProcessing():
"""
This class allows interactive calls to be made into the GDP.
"""
def _init_(self, wfsUrl=WFS_URL, wpsUrl=WPS_URL, version='1.1.0'):
self.wfsUrl = wfsUrl
self.wpsUrl = wpsUrl
self.version = version
self.wps = WebProcessingService(wpsUrl)
def WPSgetCapbilities(self, xml=None):
"""
Returns a list of capabilities.
"""
self.wps.getcapabilities(xml)
def WPSdescribeprocess(self, identifier, xml=None):
"""
Returns a list describing a specific identifier/process.
"""
self.wps.describeprocess(identifier, xml)
def _encodeZipFolder(self, filename):
"""
This function will encode a zipfile and return the filename.
"""
#check extension
if not filename.endswith('.zip'):
print 'Wrong filetype.'
return
#encode the file
with open(filename, 'rb') as fin:
bytesRead = fin.read()
encode= base64.b64encode(bytesRead)
#renames the file and saves it onto local drive
filename = filename.split('.')
filename = str(filename[0]) + '_copy.' + str(filename[-1])
fout = open(filename, "w")
fout.write(encode)
fout.close()
return filename
def uploadShapeFile(self, filePath):
"""
Given a file, this function encodes the file and uploads it onto geoserver.
"""
# encodes the file, opens it, reads it, and closes it
# returns a filename in form of: filename_copy.zip
filePath = self._encodeZipFolder(filePath)
if filePath is None:
return
filehandle = open(filePath, 'r')
filedata = filehandle.read()
filehandle.close()
os.remove(filePath) # deletes the encoded file
# this if for naming the file on geoServer
filename = filePath.split("/")
# gets rid of filepath, keeps only filename eg: file.zip
filename = filename[len(filename) - 1]
filename = filename.replace("_copy.zip", "")
# check to make sure a file with the same name does not exist
fileCheckString = "upload:" + filename
shapefiles = self.getShapefiles()
if fileCheckString in shapefiles:
print 'File exists already.'
return
xmlGen = gdpXMLGenerator()
root = xmlGen.getUploadXMLtree(filename, upload_URL, filedata)
# now we have a complete XML upload request
uploadRequest = etree.tostring(root)
POST = WebProcessingService(WPS_Service)
execution = POST.execute(None, [], request=uploadRequest)
monitorExecution(execution)
return "upload:"+filename
def getTuples(self, shapefile, attribute):
"""
Will return the dictionary tuples only.
"""
return self.getValues(shapefile, attribute, getTuples='only')
def _getGMLIDString(self, GMLbeginterm, line, GMLstopterm, valBeginTerm, valStopTerm):
"""
This function is specific to the output documents from the GDP. This
function parses the XML document, to find the correct GMLID associated
with a feature. Returns the list of values, and a dictionary [feature:id].
"""
# we are searching for attr-value, gml:id pair
value = []
#.........这里部分代码省略.........
示例11: pyGDPwebProcessing
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
class pyGDPwebProcessing():
"""
This class allows interactive calls to be made into the GDP.
"""
def _init_(self, wfsUrl=WFS_URL, wpsUrl=WPS_URL, version='1.1.0'):
self.wfsUrl = wfsUrl
self.wpsUrl = wpsUrl
self.version = version
self.wps = WebProcessingService(wpsUrl)
def WPSgetCapbilities(self, xml=None):
"""
Returns a list of capabilities.
"""
self.wps.getcapabilities(xml)
def WPSdescribeprocess(self, identifier, xml=None):
"""
Returns a list describing a specific identifier/process.
"""
self.wps.describeprocess(identifier, xml)
def _encodeZipFolder(self, filename):
"""
This function will encode a zipfile and return the filename.
"""
#check extension
if not filename.endswith('.zip'):
raise Exception('Wrong filetype.')
#encode the file
with open(filename, 'rb') as fin:
bytesRead = fin.read()
encode= base64.b64encode(bytesRead)
#renames the file and saves it onto local drive
filename = filename.split('.')
filename = str(filename[0]) + '_copy.' + str(filename[-1])
fout = open(filename, "w")
fout.write(encode)
fout.close()
return filename
def shapeToZip(self,inShape, outZip=None, allFiles=True):
"""Packs a shapefile to ZIP format.
arguments
-inShape - input shape file
-outZip - output ZIP file (optional)
default: <inShapeName>.zip in same folder as inShape
(If full path not specified, output is written to
to same folder as inShape)
-allFiles - Include all files? (optional)
True (default) - all shape file components
False - just .shp,.shx,.dbf,.prj,shp.xml files
reference: Esri, Inc, 1998, Esri Shapefile Technical Description
http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf
author: Curtis Price, [email protected]"""
if not os.path.splitext(inShape)[1] == ".shp":
raise Exception, "inShape must be a *.shp"
if not os.path.exists(inShape):
raise Exception, "%s not found" % inShape
# get shapefile root name "path/file.shp" -> "file"
# and shapefile path
rootName = os.path.splitext(os.path.basename(inShape))[0]
inShape = os.path.realpath(inShape)
inDir = os.path.dirname(inShape)
# output zip file path
if outZip in [None,""]:
# default output: shapefilepath/shapefilename.zip
outDir = inDir
outZip = os.path.join(outDir,rootName) + ".zip"
else:
outDir = os.path.dirname(outZip)
if outDir.strip() in ["","."]:
# if full path not specified, use input shapefile folder
outDir = os.path.dirname(os.path.realpath(inShape))
else:
# if output path does exist, raise an exception
if not os.path.exists(outDir):
raise Exception, "Output folder %s not found" % outDir
outZip = os.path.join(outDir,outZip)
# enforce .zip extension
outZip = os.path.splitext(outZip)[0] + ".zip"
if not os.access(outDir, os.W_OK):
raise Exception, "Output directory %s not writeable" % outDir
if os.path.exists(outZip):
os.unlink(outZip)
#.........这里部分代码省略.........
示例12: WPSClient
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
class WPSClient(object):
"""Returns a class where every public method is a WPS process available at
the given url.
Example:
>>> emu = WPSClient(url='<server url>')
>>> emu.hello('stranger')
'Hello stranger'
"""
def __init__(
self,
url,
processes=None,
converters=None,
username=None,
password=None,
headers=None,
verify=True,
cert=None,
verbose=False,
progress=False,
version=WPS_DEFAULT_VERSION,
):
"""
Args:
url (str): Link to WPS provider. config (Config): an instance
processes: Specify a subset of processes to bind. Defaults to all
processes.
converters (dict): Correspondence of {mimetype: class} to convert
this mimetype to a python object.
username (str): passed to :class:`owslib.wps.WebProcessingService`
password (str): passed to :class:`owslib.wps.WebProcessingService`
headers (str): passed to :class:`owslib.wps.WebProcessingService`
verify (bool): passed to :class:`owslib.wps.WebProcessingService`
cert (str): passed to :class:`owslib.wps.WebProcessingService`
verbose (str): passed to :class:`owslib.wps.WebProcessingService`
progress (bool): If True, enable interactive user mode.
version (str): WPS version to use.
"""
self._converters = converters
self._interactive = progress
self._mode = ASYNC if progress else SYNC
self._notebook = notebook.is_notebook()
self._inputs = {}
self._outputs = {}
if not verify:
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
self._wps = WebProcessingService(
url,
version=version,
username=username,
password=password,
verbose=verbose,
headers=headers,
verify=verify,
cert=cert,
skip_caps=True,
)
try:
self._wps.getcapabilities()
except ServiceException as e:
if "AccessForbidden" in str(e):
raise UnauthorizedException(
"You are not authorized to do a request of type: GetCapabilities"
)
raise
self._processes = self._get_process_description(processes)
# Build the methods
for pid in self._processes:
setattr(self, sanitize(pid), types.MethodType(self._method_factory(pid), self))
self.logger = logging.getLogger('WPSClient')
if progress:
self._setup_logging()
self.__doc__ = utils.build_wps_client_doc(self._wps, self._processes)
def _get_process_description(self, processes):
"""Return the description for each process.
Sends the server a `describeProcess` request for each process.
Parameters
----------
processes: str, list, None
A process name, a list of process names or None (for all processes).
Returns
-------
OrderedDict
A dictionary keyed by the process identifier of process descriptions.
"""
#.........这里部分代码省略.........
示例13: BirdyCLI
# 需要导入模块: from owslib.wps import WebProcessingService [as 别名]
# 或者: from owslib.wps.WebProcessingService import getcapabilities [as 别名]
class BirdyCLI(click.MultiCommand):
"""BirdyCLI is an implementation of :class:`click.MultiCommand`. It
adds each process of a Web Processing Service as command to the
command-line interface.
:param url: URL of the Web Processing Service.
:param xml: A WPS GetCapabilities response for testing.
"""
def __init__(self, name=None, url=None, xml=None, **attrs):
click.MultiCommand.__init__(self, name, **attrs)
self.url = os.environ.get('WPS_SERVICE') or url
self.verify = get_ssl_verify()
self.xml = xml
self.wps = WebProcessingService(self.url, verify=self.verify, skip_caps=True)
self.commands = OrderedDict()
def _update_commands(self):
if not self.commands:
try:
self.wps.getcapabilities(xml=self.xml)
except SSLError:
raise ConnectionError('SSL verfication of server certificate failed. Set WPS_SSL_VERIFY=false.')
except Exception:
raise ConnectionError("Web Processing Service not available.")
for process in self.wps.processes:
self.commands[process.identifier] = dict(
name=process.identifier,
url=self.wps.url,
version=process.processVersion,
help=BirdyCLI.format_command_help(process),
options=[])
def list_commands(self, ctx):
ctx.obj = True
self._update_commands()
return self.commands.keys()
def get_command(self, ctx, name):
self._update_commands()
cmd_templ = template_env.get_template('cmd.py.j2')
rendered_cmd = cmd_templ.render(self._get_command_info(name, details=ctx.obj is None or False))
ns = {}
code = compile(rendered_cmd, filename='<string>', mode='exec')
eval(code, ns, ns)
return ns['cli']
def _get_command_info(self, name, details=False):
cmd = self.commands.get(name)
if details:
pp = self.wps.describeprocess(name)
for inp in pp.dataInputs:
help = inp.title or ''
default = BirdyCLI.get_param_default(inp)
if default:
help = "{}. Default: {}".format(help, default)
cmd['options'].append(dict(
name=inp.identifier,
# default=BirdyCLI.get_param_default(inp),
help=help,
type=BirdyCLI.get_param_type(inp),
multiple=inp.maxOccurs > 1))
return cmd
@staticmethod
def format_command_help(process):
return "{}: {}".format(process.title or process.identifier, process.abstract or '')
@staticmethod
def get_param_default(param):
if 'ComplexData' in param.dataType:
# TODO: get default value of complex type
default = None
elif 'BoundingBoxData' in param.dataType:
# TODO: get default value of bbox
default = None
else:
default = getattr(param, 'defaultValue', None)
return default
@staticmethod
def get_param_type(param):
if param.dataType is None:
param_type = click.STRING
elif 'boolean' in param.dataType:
param_type = click.BOOL
elif 'integer' in param.dataType:
param_type = click.INT
elif 'float' in param.dataType:
param_type = click.FLOAT
elif 'ComplexData' in param.dataType:
param_type = COMPLEX
else:
param_type = click.STRING
return param_type