def loadShortHelp(): h = {} path = os.path.dirname(__file__) for f in os.listdir(path): if f.endswith("yaml"): filename = os.path.join(path, f) with codecs.open(filename, encoding='utf-8') as stream: h.update(yaml.load(stream)) version = ".".join(Qgis.QGIS_VERSION.split(".")[0:2]) overrideLocale = QgsSettings().value('locale/overrideFlag', False, bool) if not overrideLocale: locale = QLocale.system().name()[:2] else: locale = QgsSettings().value('locale/userLocale', '') locale = locale.split("_")[0] def replace(s): if s is not None: return s.replace( "{qgisdocs}", "https://docs.qgis.org/%s/%s/docs" % (version, locale)) else: return None h = {k: replace(v) for k, v in list(h.items())} return h
def loadShortHelp(): h = {} path = os.path.dirname(__file__) for f in os.listdir(path): if f.endswith("yaml"): filename = os.path.join(path, f) with codecs.open(filename, encoding='utf-8') as stream: with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) for k, v in yaml.load(stream, Loader=yaml.SafeLoader).items(): if v is None: continue h[k] = QCoreApplication.translate("{}Algorithm".format(f[:-5].upper()), v) version = ".".join(Qgis.QGIS_VERSION.split(".")[0:2]) overrideLocale = QgsSettings().value('locale/overrideFlag', False, bool) if not overrideLocale: locale = QLocale.system().name()[:2] else: locale = QgsSettings().value('locale/userLocale', '') locale = locale.split("_")[0] def replace(s): if s is not None: return s.replace("{qgisdocs}", "https://docs.qgis.org/%s/%s/docs" % (version, locale)) else: return None h = {k: replace(v) for k, v in list(h.items())} return h
def loadShortHelp(): h = {} path = os.path.dirname(__file__) for f in os.listdir(path): if f.endswith("yaml"): filename = os.path.join(path, f) with codecs.open(filename, encoding='utf-8') as stream: with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) for k, v in yaml.load(stream).items(): if v is None: continue h[k] = QCoreApplication.translate( "{}Algorithm".format(f[:-5].upper()), v) version = ".".join(Qgis.QGIS_VERSION.split(".")[0:2]) overrideLocale = QgsSettings().value('locale/overrideFlag', False, bool) if not overrideLocale: locale = QLocale.system().name()[:2] else: locale = QgsSettings().value('locale/userLocale', '') locale = locale.split("_")[0] def replace(s): if s is not None: return s.replace( "{qgisdocs}", "https://docs.qgis.org/%s/%s/docs" % (version, locale)) else: return None h = {k: replace(v) for k, v in list(h.items())} return h
def add_flatten_dataset_table(self): """ Add a flatten dataset table with all links and contacts. """ connections, message = connections_list() if not connections: LOGGER.critical(message) self.set_html_content('PgMetadata', message) return if len(connections) > 1: dialog = QInputDialog() dialog.setComboBoxItems(connections) dialog.setWindowTitle(tr("Database")) dialog.setLabelText(tr("Choose the database to add the catalog")) if not dialog.exec_(): return connection_name = dialog.textValue() else: connection_name = connections[0] metadata = QgsProviderRegistry.instance().providerMetadata('postgres') connection = metadata.findConnection(connection_name) locale = QgsSettings().value("locale/userLocale", QLocale().name()) locale = locale.split('_')[0].lower() uri = QgsDataSourceUri(connection.uri()) uri.setTable(f'(SELECT * FROM pgmetadata.export_datasets_as_flat_table(\'{locale}\'))') uri.setKeyColumn('uid') layer = QgsVectorLayer(uri.uri(), '{} - {}'.format(tr("Catalog"), connection_name), 'postgres') QgsProject.instance().addMapLayer(layer)
def sql_for_layer(uri, output_format: OutputFormats): """ Get the SQL query for a given layer and output format. """ locale = QgsSettings().value("locale/userLocale", QLocale().name()) locale = locale.split('_')[0].lower() if output_format == OutputFormats.HTML: sql = ( "SELECT pgmetadata.get_dataset_item_html_content('{schema}', '{table}', '{locale}');" ).format(schema=uri.schema(), table=uri.table(), locale=locale) elif output_format == OutputFormats.DCAT: sql = ( "SELECT dataset FROM pgmetadata.get_datasets_as_dcat_xml(" " '{locale}'," " (" " SELECT array_agg(uid)" " FROM pgmetadata.dataset AS d" " WHERE d.schema_name = '{schema}' " " AND d.table_name = '{table}'" " )" ") " ).format(schema=uri.schema(), table=uri.table(), locale=locale) else: raise NotImplementedError('Output format is not yet implemented.') return sql
def connections_list() -> tuple: """ List of available connections to PostgreSQL database. """ migrate_from_global_variables_to_pgmetadata_section() metadata = QgsProviderRegistry.instance().providerMetadata('postgres') connection_names = QgsSettings().value("pgmetadata/connection_names", "", type=str) if not connection_names: message = tr( "You must use the 'Set Connections' algorithm in the Processing toolbox. The plugin must be " "aware about the database to use. Multiple databases can be set.") return (), message connections = list() for name in connection_names.split(';'): try: metadata.findConnection(name) except QgsProviderConnectionException: # Todo, we must log something pass else: connections.append(name) return connections, None
def export_dock_content(self, output_format: OutputFormats): """ Export the current displayed metadata sheet to the given format. """ layer_name = iface.activeLayer().name() file_path = os.path.join( self.settings.value("UI/lastFileNameWidgetDir"), '{name}.{ext}'.format(name=layer_name, ext=output_format.value['ext'])) output_file = QFileDialog.getSaveFileName( self, tr("Save File as {format}").format( format=output_format.value['label']), file_path, "{label} (*.{ext})".format( label=output_format.value['label'], ext=output_format.value['ext'], )) if output_file[0] == '': return self.settings.setValue("UI/lastFileNameWidgetDir", os.path.dirname(output_file[0])) if output_format == OutputFormats.Pdf: printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setPageMargins(20, 20, 20, 20, QPrinter.Millimeter) printer.setOutputFileName(output_file[0]) self.viewer.print(printer) iface.messageBar().pushSuccess( tr("Export PDF"), tr("The metadata has been exported as PDF successfully")) elif output_format in [OutputFormats.Html, OutputFormats.Dcat]: if output_format == OutputFormats.Html: data_str = self.viewer.page().currentFrame().toHtml() else: sql = self.sql_for_layer(self.current_datasource_uri, output_format=OutputFormats.Dcat) data = self.current_connection.executeSql(sql) with open(resources_path('xml', 'dcat.xml')) as xml_file: xml_template = xml_file.read() locale = QgsSettings().value("locale/userLocale", QLocale().name()) locale = locale.split('_')[0].lower() xml = parseString( xml_template.format(locale=locale, content=data[0][0])) data_str = xml.toprettyxml() file_writer = open(output_file[0], "w") file_writer.write(data_str) file_writer.close() iface.messageBar().pushSuccess( tr("Export") + ' ' + output_format.value['label'], tr("The metadata has been exported as {format} successfully"). format(format=output_format.value['label']))
def loadShortHelp(): h = {} path = os.path.dirname(__file__) for f in os.listdir(path): if f.endswith("yaml"): filename = os.path.join(path, f) with codecs.open(filename, encoding='utf-8') as stream: h.update(yaml.load(stream)) version = ".".join(Qgis.QGIS_VERSION.split(".")[0:2]) overrideLocale = QgsSettings().value('locale/overrideFlag', False, bool) if not overrideLocale: locale = QLocale.system().name()[:2] else: locale = QgsSettings().value('locale/userLocale', '') locale = locale.split("_")[0] def replace(s): if s is not None: return s.replace("{qgisdocs}", "https://docs.qgis.org/%s/%s/docs" % (version, locale)) else: return None h = {k: replace(v) for k, v in list(h.items())} return h