本文整理汇总了Python中safe.utilities.gis.qgis_version函数的典型用法代码示例。如果您正苦于以下问题:Python qgis_version函数的具体用法?Python qgis_version怎么用?Python qgis_version使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了qgis_version函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, iface, template, layer):
"""Constructor for the Composition Report class.
:param iface: Reference to the QGIS iface object.
:type iface: QgsAppInterface
:param template: The QGIS template path.
:type template: str
"""
LOGGER.debug('InaSAFE Impact Report class initialised')
self._iface = iface
self._template = template
self._layer = layer
self._extent = self._iface.mapCanvas().extent()
self._page_dpi = 300.0
self._safe_logo = resources_path(
'img', 'logos', 'inasafe-logo-url.svg')
self._organisation_logo = default_organisation_logo_path()
self._north_arrow = default_north_arrow_path()
self._disclaimer = disclaimer()
# For QGIS < 2.4 compatibility
# QgsMapSettings is added in 2.4
if qgis_version() < 20400:
map_settings = self._iface.mapCanvas().mapRenderer()
else:
map_settings = self._iface.mapCanvas().mapSettings()
self._template_composition = TemplateComposition(
template_path=self.template,
map_settings=map_settings)
self._keyword_io = KeywordIO()
示例2: request
def request(self, request_url):
"""Mock handler for an http request.
:param request_url: Url being requested.
"""
url = str(request_url.url().toString())
reply = MockQNetworkReply()
if url == 'http://hot-export.geofabrik.de/newjob':
reply.content = read_all('test-importdlg-newjob.html')
elif url == 'http://hot-export.geofabrik.de/wizard_area':
reply.content = read_all('test-importdlg-wizardarea.html')
elif url == 'http://hot-export.geofabrik.de/tagupload':
reply.content = read_all('test-importdlg-job.html')
reply._url = 'http://hot-export.geofabrik.de/jobs/1990'
elif url == 'http://hot-export.geofabrik.de/jobs/1990':
reply.content = read_all('test-importdlg-job.html')
elif url == ('http://osm.inasafe.org/buildings-shp?'
'bbox=20.389938354492188,-34.10782492987083'
',20.712661743164062,'
'-34.008273470938335&qgis_version=%s'
'&inasafe_version=%s'
'&lang=en' % (qgis_version(), get_version())):
reply.content = read_all("test-importdlg-extractzip.zip")
return reply
示例3: test_print_default_template
def test_print_default_template(self):
"""Test printing report to pdf using default template works."""
impact_layer_path = test_data_path(
'impact', 'population_affected_entire_area.shp')
layer, _ = load_layer(impact_layer_path)
# noinspection PyUnresolvedReferences
QgsMapLayerRegistry.instance().addMapLayer(layer)
# noinspection PyCallingNonCallable
rect = QgsRectangle(106.8194, -6.2108, 106.8201, -6.1964)
CANVAS.setExtent(rect)
CANVAS.refresh()
template = resources_path(
'qgis-composer-templates', 'inasafe-portrait-a4.qpt')
report = ImpactReport(IFACE, template, layer)
out_path = unique_filename(
prefix='map_default_template_test',
suffix='.pdf',
dir=temp_dir('test'))
report.print_map_to_pdf(out_path)
# Check the file exists
message = 'Rendered output does not exist: %s' % out_path
self.assertTrue(os.path.exists(out_path), message)
# Check the file is not corrupt
message = 'The output file %s is corrupt' % out_path
out_size = os.stat(out_path).st_size
self.assertTrue(out_size > 0, message)
# Check the components in composition are default components
if qgis_version() < 20500:
safe_logo = report.composition.getComposerItemById(
'safe-logo').pictureFile()
north_arrow = report.composition.getComposerItemById(
'north-arrow').pictureFile()
org_logo = report.composition.getComposerItemById(
'organisation-logo').pictureFile()
else:
safe_logo = report.composition.getComposerItemById(
'safe-logo').picturePath()
north_arrow = report.composition.getComposerItemById(
'north-arrow').picturePath()
org_logo = report.composition.getComposerItemById(
'organisation-logo').picturePath()
expected_safe_logo = resources_path(
'img', 'logos', 'inasafe-logo-url.svg')
expected_north_arrow = resources_path(
'img', 'north_arrows', 'simple_north_arrow.png')
expected_org_logo = resources_path('img', 'logos', 'supporters.png')
message = 'The safe logo path is not the default one'
self.assertEqual(expected_safe_logo, safe_logo, message)
message = 'The north arrow path is not the default one'
self.assertEqual(expected_north_arrow, north_arrow, message)
message = 'The organisation logo path is not the default one'
self.assertEqual(expected_org_logo, org_logo, message)
示例4: _run_tests
def _run_tests(test_suite, package_name, with_coverage=False):
"""Core function to test a test suite."""
count = test_suite.countTestCases()
print('########')
print('%s tests has been discovered in %s' % (count, package_name))
print('QGIS : %s' % qgis_version())
print('Python GDAL : %s' % gdal.VersionInfo('VERSION_NUM'))
print('QT : %s' % Qt.QT_VERSION_STR)
print('Run slow tests : %s' % (not os.environ.get('ON_TRAVIS', False)))
print('########')
if with_coverage:
cov = coverage.Coverage(
source=['safe/'],
omit=['*/test/*', 'safe/definitions/*'],
)
cov.start()
unittest.TextTestRunner(verbosity=3, stream=sys.stdout).run(test_suite)
if with_coverage:
cov.stop()
cov.save()
report = tempfile.NamedTemporaryFile(delete=False)
cov.report(file=report)
# Produce HTML reports in the `htmlcov` folder and open index.html
# cov.html_report()
report.close()
with open(report.name, 'r') as fin:
print(fin.read())
示例5: download
def download(feature_type, output_base_path, extent, progress_dialog=None):
"""Download shapefiles from Kartoza server.
.. versionadded:: 3.2
:param feature_type: What kind of features should be downloaded.
Currently 'buildings', 'building-points' or 'roads' are supported.
:type feature_type: str
:param output_base_path: The base path of the shape file.
:type output_base_path: str
:param extent: A list in the form [xmin, ymin, xmax, ymax] where all
coordinates provided are in Geographic / EPSG:4326.
:type extent: list
:param progress_dialog: A progress dialog.
:type progress_dialog: QProgressDialog
:raises: ImportDialogError, CanceledImportDialogError
"""
# preparing necessary data
min_longitude = extent[0]
min_latitude = extent[1]
max_longitude = extent[2]
max_latitude = extent[3]
box = (
'{min_longitude},{min_latitude},{max_longitude},'
'{max_latitude}').format(
min_longitude=min_longitude,
min_latitude=min_latitude,
max_longitude=max_longitude,
max_latitude=max_latitude
)
url = (
'{url_osm_prefix}'
'{feature_type}'
'{url_osm_suffix}?'
'bbox={box}&'
'qgis_version={qgis}&'
'lang={lang}&'
'inasafe_version={inasafe_version}'.format(
url_osm_prefix=URL_OSM_PREFIX,
feature_type=feature_type,
url_osm_suffix=URL_OSM_SUFFIX,
box=box,
qgis=qgis_version(),
lang=locale(),
inasafe_version=get_version()))
path = tempfile.mktemp('.shp.zip')
# download and extract it
fetch_zip(url, path, feature_type, progress_dialog)
extract_zip(path, output_base_path)
if progress_dialog:
progress_dialog.done(QDialog.Accepted)
示例6: accept
def accept(self):
"""Upload the layer to Geonode."""
enable_busy_cursor()
self.button_box.setEnabled(False)
layer = layer_from_combo(self.layers)
login = self.login.text()
if self.save_login.isChecked():
set_setting(GEONODE_USER, login)
else:
set_setting(GEONODE_USER, '')
password = self.password.text()
if self.save_password.isChecked():
set_setting(GEONODE_PASSWORD, password)
else:
set_setting(GEONODE_PASSWORD, '')
url = self.url.text()
if self.save_url.isChecked():
set_setting(GEONODE_URL, url)
else:
set_setting(GEONODE_URL, '')
geonode_session = login_user(url, login, password)
try:
result = upload(url, geonode_session, layer.source())
except GeoNodeLayerUploadError as e:
result = {
'success': False,
'message': str(e)
}
finally:
self.button_box.setEnabled(True)
disable_busy_cursor()
if result['success']:
self.done(QDialog.Accepted)
layer_url = urljoin(url, result['url'])
# Link is not working in QGIS 2.
# It's gonna work in QGIS 3.
if qgis_version() >= 29900:
external_link = '<a href=\"{url}\">{url}</a>'.format(
url=layer_url)
else:
external_link = layer_url
display_success_message_bar(
tr('Uploading done'),
tr('Successfully uploaded to {external_link}').format(
external_link=external_link),
)
else:
display_warning_message_box(
self,
tr('Error while uploading the layer.'),
str(result)
)
示例7: test_issue71
def test_issue71(self):
"""Test issue #71 in github - cbo changes should update ok button."""
# See https://github.com/AIFDR/inasafe/issues/71
# Push OK with the left mouse button
print 'Using QGIS: %s' % qgis_version()
self.tearDown()
button = DOCK.pbnRunStop
# First part of scenario should have enabled run
file_list = [
join(HAZDATA, 'Flood_Current_Depth_Jakarta_geographic.asc'),
join(TESTDATA, 'Population_Jakarta_geographic.asc')]
hazard_layer_count, exposure_layer_count = load_layers(file_list)
message = (
'Incorrect number of Hazard layers: expected 1 got %s'
% hazard_layer_count)
self.assertTrue(hazard_layer_count == 1, message)
message = (
'Incorrect number of Exposure layers: expected 1 got %s'
% exposure_layer_count)
self.assertTrue(exposure_layer_count == 1, message)
message = 'Run button was not enabled'
self.assertTrue(button.isEnabled(), message)
# Second part of scenario - run disabled when adding invalid layer
# and select it - run should be disabled
path = os.path.join(TESTDATA, 'issue71.tif')
file_list = [path] # This layer has incorrect keywords
clear_flag = False
_, _ = load_layers(file_list, clear_flag)
# set exposure to : Population Count (5kmx5km)
# by moving one down
DOCK.cboExposure.setCurrentIndex(DOCK.cboExposure.currentIndex() + 1)
actual_dict = get_ui_state(DOCK)
expected_dict = {
'Run Button Enabled': False,
'Impact Function Id': '',
'Impact Function Title': '',
'Hazard': 'A flood in Jakarta like in 2007',
'Exposure': 'Population Count (5kmx5km)'}
message = ((
'Run button was not disabled when exposure set to \n%s'
'\nUI State: \n%s\nExpected State:\n%s\n%s') % (
DOCK.cboExposure.currentText(),
actual_dict,
expected_dict,
combos_to_string(DOCK)))
self.assertTrue(expected_dict == actual_dict, message)
# Now select again a valid layer and the run button
# should be enabled
DOCK.cboExposure.setCurrentIndex(DOCK.cboExposure.currentIndex() - 1)
message = (
'Run button was not enabled when exposure set to \n%s' %
DOCK.cboExposure.currentText())
self.assertTrue(button.isEnabled(), message)
示例8: test_save_scenario
def test_save_scenario(self):
"""Test saving Current scenario."""
result, message = setup_scenario(
DOCK,
hazard='Classified Flood',
exposure='Population',
function='Be affected by each hazard class',
function_id='ClassifiedRasterHazardPopulationFunction')
self.assertTrue(result, message)
# Enable on-the-fly reprojection
set_canvas_crs(GEOCRS, True)
set_jakarta_extent(dock=DOCK)
# create unique file
scenario_file = unique_filename(
prefix='scenarioTest', suffix='.txt', dir=temp_dir('test'))
self.save_scenario_dialog.save_scenario(
scenario_file_path=scenario_file)
with open(scenario_file) as f:
data = f.readlines()
title = data[0][:-1]
exposure = data[1][:-1]
hazard = data[2][:-1]
function = data[3][:-1]
extent = data[4][:-1]
self.assertTrue(
os.path.exists(scenario_file),
'File %s does not exist' % scenario_file)
self.assertTrue(
title == '[Classified Flood]',
'Title is not the same')
self.assertTrue(
exposure.startswith('exposure =') and exposure.endswith(
'pop_binary_raster_20_20.asc'),
'Exposure is not the same')
self.assertTrue(
hazard.startswith('hazard =') and hazard.endswith(
'classified_flood_20_20.asc'),
'Hazard is not the same')
self.assertTrue(
function == (
'function = ClassifiedRasterHazardPopulationFunction'),
'Impact function is not same')
# TODO: figure out why this changed between releases
if qgis_version() < 20400:
# For QGIS 2.0
expected_extent = (
'extent = 106.313333, -6.380000, 107.346667, -6.070000')
self.assertEqual(expected_extent, extent)
else:
# for QGIS 2.4
expected_extent = (
'extent = 106.287500, -6.380000, 107.372500, -6.070000')
self.assertEqual(expected_extent, expected_extent)
示例9: download
def download(feature_type, output_base_path, extent, progress_dialog=None):
"""Download shapefiles from Kartoza server.
.. versionadded:: 3.2
:param feature_type: What kind of features should be downloaded.
Currently 'buildings', 'building-points' or 'roads' are supported.
:type feature_type: str
:param output_base_path: The base path of the shape file.
:type output_base_path: str
:param extent: A list in the form [xmin, ymin, xmax, ymax] where all
coordinates provided are in Geographic / EPSG:4326.
:type extent: list
:param progress_dialog: A progress dialog.
:type progress_dialog: QProgressDialog
:raises: ImportDialogError, CanceledImportDialogError
"""
# preparing necessary data
min_longitude = extent[0]
min_latitude = extent[1]
max_longitude = extent[2]
max_latitude = extent[3]
box = (
'{min_longitude},{min_latitude},{max_longitude},'
'{max_latitude}').format(
min_longitude=min_longitude,
min_latitude=min_latitude,
max_longitude=max_longitude,
max_latitude=max_latitude
)
url = URL_OSM_PREFIX + feature_type + URL_OSM_SUFFIX
url = '{url}?bbox={box}&qgis_version={qgis}'.format(
url=url, box=box, qgis=qgis_version())
url += '&inasafe_version=%s' % get_version()
if 'LANG' in os.environ:
# Get the language only : eg 'en_US' -> 'en'
env_lang = os.environ['LANG'].split('_')[0]
url += '&lang=%s' % env_lang
path = tempfile.mktemp('.shp.zip')
# download and extract it
fetch_zip(url, path, feature_type, progress_dialog)
extract_zip(path, output_base_path)
if progress_dialog:
progress_dialog.done(QDialog.Accepted)
示例10: add_impact_layers_to_canvas
def add_impact_layers_to_canvas(impact_function, group=None, iface=None):
"""Helper method to add impact layer to QGIS from impact function.
:param impact_function: The impact function used.
:type impact_function: ImpactFunction
:param group: An existing group as a parent, optional.
:type group: QgsLayerTreeGroup
:param iface: QGIS QgisAppInterface instance.
:type iface: QgisAppInterface
"""
layers = impact_function.outputs
name = impact_function.name
if group:
group_analysis = group
else:
# noinspection PyArgumentList
root = QgsProject.instance().layerTreeRoot()
group_analysis = root.insertGroup(0, name)
group_analysis.setItemVisibilityChecked(True)
group_analysis.setExpanded(group is None)
for layer in layers:
# noinspection PyArgumentList
QgsProject.instance().addMapLayer(layer, False)
layer_node = group_analysis.addLayer(layer)
# set layer title if any
try:
title = layer.keywords['title']
if qgis_version() >= 21800:
layer.setName(title)
else:
layer.setLayerName(title)
except KeyError:
pass
visible_layers = [impact_function.impact.id()]
print_atlas = setting('print_atlas_report', False, bool)
if print_atlas:
visible_layers.append(impact_function.aggregation_summary.id())
# Let's enable only the more detailed layer. See #2925
if layer.id() in visible_layers:
layer_node.setItemVisibilityChecked(True)
else:
layer_node.setItemVisibilityChecked(False)
# we need to set analysis_impacted as an active layer because we need
# to get all qgis variables that we need from this layer for
# infographic.
if iface:
iface.setActiveLayer(impact_function.analysis_impacted)
示例11: create_profile_layer
def create_profile_layer(profiling):
"""Create a tabular layer with the profiling.
:param profiling: A dict containing benchmarking data.
:type profiling: safe.messaging.message.Message
:return: A tabular layer.
:rtype: QgsVectorLayer
"""
fields = [
create_field_from_definition(profiling_function_field),
create_field_from_definition(profiling_time_field)
]
if setting(key='memory_profile', expected_type=bool):
fields.append(create_field_from_definition(profiling_memory_field))
tabular = create_memory_layer(
'profiling',
QgsWkbTypes.NullGeometry,
fields=fields)
# Generate profiling keywords
tabular.keywords['layer_purpose'] = layer_purpose_profiling['key']
tabular.keywords['title'] = layer_purpose_profiling['name']
if qgis_version() >= 21800:
tabular.setName(tabular.keywords['title'])
else:
tabular.setLayerName(tabular.keywords['title'])
tabular.keywords['inasafe_fields'] = {
profiling_function_field['key']:
profiling_function_field['field_name'],
profiling_time_field['key']:
profiling_time_field['field_name'],
}
if setting(key='memory_profile', expected_type=bool):
tabular.keywords['inasafe_fields'][
profiling_memory_field['key']] = profiling_memory_field[
'field_name']
tabular.keywords[inasafe_keyword_version_key] = (
inasafe_keyword_version)
table = profiling.to_text().splitlines()[3:]
tabular.startEditing()
for line in table:
feature = QgsFeature()
items = line.split(', ')
time = items[1].replace('-', '')
if setting(key='memory_profile', expected_type=bool):
memory = items[2].replace('-', '')
feature.setAttributes([items[0], time, memory])
else:
feature.setAttributes([items[0], time])
tabular.addFeature(feature)
tabular.commitChanges()
return tabular
示例12: test_clip_geometry
def test_clip_geometry(self):
"""Test that we can clip a geometry using another geometry."""
geometry = QgsGeometry.fromPolyline([
QgsPoint(10, 10), QgsPoint(20, 20), QgsPoint(30, 30),
QgsPoint(40, 40)])
clip_polygon = QgsGeometry.fromPolygon([
[QgsPoint(20, 20),
QgsPoint(20, 30),
QgsPoint(30, 30),
QgsPoint(30, 20),
QgsPoint(20, 20)]])
result = clip_geometry(clip_polygon, geometry)
expected_wkt = 'LINESTRING(20.0 20.0, 30.0 30.0)'
# There should only be one feature that intersects this clip
# poly so this assertion should work.
assert compare_wkt(expected_wkt, str(result.exportToWkt()))
# Now poly on poly clip test
clip_polygon = QgsGeometry.fromWkt(
'POLYGON((106.8218 -6.1842,106.8232 -6.1842,'
'106.82304963 -6.18317148,106.82179736 -6.18314774,'
'106.8218 -6.1842))')
geometry = QgsGeometry.fromWkt(
'POLYGON((106.8216869 -6.1852067,106.8213233 -6.1843051,'
'106.8212891 -6.1835559,106.8222566 -6.1835184,'
'106.8227557 -6.1835076,106.8228588 -6.1851204,'
'106.8216869 -6.1852067))')
result = clip_geometry(clip_polygon, geometry)
expected_wkt = (
'POLYGON((106.82179833 -6.18353616,106.8222566 -6.1835184,'
'106.8227557 -6.1835076,106.82279996 -6.1842,'
'106.8218 -6.1842,106.82179833 -6.18353616))')
# There should only be one feature that intersects this clip
# poly so this assertion should work.
assert compare_wkt(expected_wkt, str(result.exportToWkt()))
# Now point on poly test clip
geometry = QgsGeometry.fromWkt('POINT(106.82241 -6.18369)')
result = clip_geometry(clip_polygon, geometry)
if qgis_version() > 10800:
expected_wkt = 'POINT(106.82241 -6.18369)'
else:
expected_wkt = 'POINT(106.822410 -6.183690)'
# There should only be one feature that intersects this clip
# poly so this assertion should work.
assert compare_wkt(expected_wkt, str(result.exportToWkt()))
示例13: make_keywordless_layer
def make_keywordless_layer():
"""Helper function that returns a single predefined keywordless layer."""
path = 'keywordless_layer.tif'
base_path = test_data_path('hazard')
full_path = os.path.abspath(os.path.join(base_path, path))
title = 'Keywordless Layer'
# noinspection PyCallingNonCallable
layer = QgsRasterLayer(full_path, title)
if qgis_version() >= 10800: # 1.8 or newer
# noinspection PyArgumentList,PyUnresolvedReferences
QgsMapLayerRegistry.instance().addMapLayers([layer])
else:
# noinspection PyArgumentList,PyUnresolvedReferences
QgsMapLayerRegistry.instance().addMapLayers([layer])
return layer
示例14: add_layer_to_canvas
def add_layer_to_canvas(layer, name):
"""Helper method to add layer to QGIS.
:param layer: The layer.
:type layer: QgsMapLayer
:param name: Layer name.
:type name: str
"""
if qgis_version() >= 21800:
layer.setName(name)
else:
layer.setLayerName(name)
QgsProject.instance().addMapLayer(layer, False)
示例15: load_shapefile
def load_shapefile(self, feature_type, base_path):
"""Load downloaded shape file to QGIS Main Window.
:param feature_type: What kind of features should be downloaded.
Currently 'buildings', 'building-points' or 'roads' are supported.
:type feature_type: str
:param base_path: The base path of the shape file (without extension).
:type base_path: str
:raises: FileMissingError - when buildings.shp not exist
"""
path = '%s.shp' % base_path
if not os.path.exists(path):
message = self.tr(
'%s does not exist. The server does not have any data for '
'this extent.' % path)
raise FileMissingError(message)
layer = self.iface.addVectorLayer(path, feature_type, 'ogr')
# Check if it's a building layer and if it's QGIS 2.14 about the 2.5D
if qgis_version() >= 21400 and feature_type == 'buildings':
layer_scope = QgsExpressionContextUtils.layerScope(layer)
if not layer_scope.variable('qgis_25d_height'):
QgsExpressionContextUtils.setLayerVariable(
layer, 'qgis_25d_height', 0.0002)
if not layer_scope.variable('qgis_25d_angle'):
QgsExpressionContextUtils.setLayerVariable(
layer, 'qgis_25d_angle', 70)
canvas_srid = self.canvas.mapSettings().destinationCrs().srsid()
on_the_fly_projection = self.canvas.hasCrsTransformEnabled()
if canvas_srid != 4326 and not on_the_fly_projection:
if QGis.QGIS_VERSION_INT >= 20400:
self.canvas.setCrsTransformEnabled(True)
else:
display_warning_message_bar(
self.iface,
self.tr('Enable \'on the fly\''),
self.tr(
'Your current projection is different than EPSG:4326. '
'You should enable \'on the fly\' to display '
'correctly your layers')
)