safe.utilities.keyword_io module

Keyword IO implementation.

Tip

Provides functionality for reading and writing keywords from within QGIS. It is an abstraction for the keywords system used by the underlying library.

class safe.utilities.keyword_io.KeywordIO[source]

Bases: PyQt4.QtCore.QObject

Class for doing keyword read/write operations.

It abstracts away differences between using SAFE to get keywords from a .keywords file and this plugins implementation of keyword caching in a local sqlite db used for supporting keywords for remote datasources.

are_keywords_file_based(layer)[source]

Check if keywords should be read/written to file or our keywords db.

Determine which keyword lookup system to use (file base or cache db) based on the layer’s provider type. True indicates we should use the datasource as a file and look for a keywords file, False and we look in the keywords db.

Parameters:layer (QgsMapLayer) – The layer which want to know how the keywords are stored.
Returns:True if keywords are stored in a file next to the dataset, else False if the dataset is remove e.g. a database.
Return type:bool
Raises:UnsupportedProviderError
clear_keywords(layer)[source]

Convenience method to clear a layer’s keywords.

Parameters:layer (QgsMapLayer) – A QGIS QgsMapLayer instance.
close_connection()[source]

Close the active sqlite3 connection.

copy_keywords(source_layer, destination_file, extra_keywords=None)[source]

Helper to copy the keywords file from a source to a target dataset.

e.g.:

copyKeywords('foo.shp', 'bar.shp')

Will result in the foo.keywords file being copied to bar.keyword.

Optional argument extraKeywords is a dictionary with additional keywords that will be added to the destination file e.g:

copyKeywords('foo.shp', 'bar.shp', {'resolution': 0.01})
Parameters:
  • source_layer (QgsMapLayer) – A QGIS QgsMapLayer instance.
  • destination_file (str) – The output filename that should be used to store the keywords in. It can be a .shp or a .keywords for example since the suffix will always be replaced with .keywords.
  • extra_keywords (dict) – A dict containing all the extra keywords to be written for the layer. The written keywords will consist of any original keywords from the source layer’s keywords file and and the extra keywords (which will replace the source layers keywords if the key is identical).
default_keyword_db_path()[source]

Helper to get the default path for the keywords file.

Returns:The path to where the default location of the keywords database is. Maps to which is ~/.inasafe/keywords.db
Return type:str
static definition(keyword)[source]

Given a keyword, try to get a definition dict for it.

New in version 3.2.

Definition dicts are defined in keywords.py. We try to return one if present, otherwise we return none. Using this method you can present rich metadata to the user e.g.

keyword = ‘layer_purpose’ kio = safe.utilities.keyword_io.Keyword_IO() definition = kio.definition(keyword) print definition

Parameters:keyword (str) – A keyword key.
Returns:A dictionary containing the matched key definition from definitions.py, otherwise None if no match was found.
Return type:dict, None
delete_keywords(layer, keyword)[source]

Delete the keyword for a given layer..

This is a wrapper method that will ‘do the right thing’ to fetch keywords for the given datasource. In particular, if the datasource is remote (e.g. a database connection) it will fetch the keywords from the keywords store.

Parameters:
  • layer (QgsMapLayer) – A QGIS QgsMapLayer instance.
  • keyword (str) – The specified keyword will be deleted from the keywords dict.
Returns:

True if the keyword was sucessfully delete. False otherwise.

Return type:

bool

delete_keywords_for_uri(uri)[source]

Delete keywords for a URI in the keywords database.

A hash will be constructed from the supplied uri and a lookup made in a local SQLITE database for the keywords. If there is an existing record for the hash, the entire record will be erased.

See also

write_keywords_for_uri, read_keywords_for_uri

Parameters:uri (str) – A layer uri. e.g. `dbname='osm' host=localhost port=5432 user='foo'password='bar' sslmode=disable key='id' srid=4326`
get_cursor()[source]

Get a cursor for the active connection.

The cursor can be used to execute arbitrary queries against the database. This method also checks that the keywords table exists in the schema, and if not, it creates it.

Returns:A valid cursor opened against the connection.
Return type:sqlite.
Raises:An sqlite.Error will be raised if anything goes wrong.
get_statistics(layer)[source]

Get the statistics related keywords from a layer.

Parameters:layer (QgsMapLayer) – A QGIS layer that represents an impact.
Returns:A two-tuple containing the values for the keywords ‘statistics_type’ and ‘statistics_classes’.
Return type:tuple(str, str)
hash_for_datasource(data_source)[source]

Given a data_source, return its hash.

Parameters:data_source (str) – The data_source name from a layer.
Returns:An md5 hash for the data source name.
Return type:str
normalize_uri(layer)[source]

Normalize URI from layer source. URI can be in a form of QgsDataSourceURI which is related to RDBMS source or general URI like CSV URI

:param layer : A layer :type layer : QgsMapLayer

Returns:normalized URI to be hashed
Raise:AttributeError if providerType not recognized
open_connection()[source]

Open an sqlite connection to the keywords database.

By default the keywords database will be used in the plugin dir, unless an explicit path has been set using setKeywordDbPath, or overridden in QSettings. If the db does not exist it will be created.

Raises:An sqlite.Error is raised if anything goes wrong
read_keyword_from_uri(uri, keyword=None)[source]

Get metadata from the keywords file associated with a URI.

This is used for layers that are non local layer (e.g. postgresql connection) and so we need to retrieve the keywords from the sqlite keywords db.

A hash will be constructed from the supplied uri and a lookup made in a local SQLITE database for the keywords. If there is an existing record it will be returned, if not and error will be thrown.

If the record is a dictionary, it means that it was inserted into the DB in a pre 2.2 version which had no ISO metadata. In this case, we use that dictionary to update the entry to the new ISO based metadata

See also

write_keywords_for_uri, delete_keywords_for_uri

Parameters:
  • uri (str) – A layer uri. e.g. `dbname='osm' host=localhost port=5432 user='foo' password='bar' sslmode=disable key='id' srid=4326`
  • keyword (str) – The metadata keyword to retrieve. If none, all keywords are returned.
Returns:

A string containing the retrieved value for the keyword if the keyword argument is specified, otherwise the complete keywords dictionary is returned.

Raises:

KeywordNotFoundError if the keyword is not found.

read_keywords(layer, keyword=None)[source]

Read keywords for a datasource and return them as a dictionary.

This is a wrapper method that will ‘do the right thing’ to fetch keywords for the given datasource. In particular, if the datasource is remote (e.g. a database connection) it will fetch the keywords from the keywords store.

Parameters:
  • layer (QgsMapLayer, QgsRasterLayer, QgsVectorLayer, QgsPluginLayer) – A QGIS QgsMapLayer instance that you want to obtain the keywords for.
  • keyword (str) – If set, will extract only the specified keyword from the keywords dict.
Returns:

A dict if keyword is omitted, otherwise the value for the given key if it is present.

Return type:

dict, str

TODO: Don’t raise generic exceptions.

Raises:HashNotFoundError, Exception, OperationalError, NoKeywordsFoundError, KeywordNotFoundError, InvalidParameterError, UnsupportedProviderError
set_keyword_db_path(path)[source]

Set the path for the keyword database (sqlite).

The file will be used to search for keywords for non local datasets.

Parameters:path (str) – A valid path to a sqlite database. The database does not need to exist already, but the user should be able to write to the path provided.
setup_keyword_db_path()[source]

Helper to set the active path for the keywords.

Called at init time, you can override this path by calling set_keyword_db_path.setKeywordDbPath.

Returns:The path to where the keywords file is. If the user has never specified what this path is, the defaultKeywordDbPath is returned.
Return type:str
to_message(keywords)[source]

Format keywords as a message object.

New in version 3.2.

The message object can then be rendered to html, plain text etc.

Parameters:keywords (dict) – Keywords to be converted to a message.
Returns:A safe message object containing a table.
Return type:safe.messaging.message
update_keywords(layer, keywords)[source]

Update keywords for a datasource.

Parameters:
  • layer (qgis.core.QgsMapLayer) – A QGIS QgsMapLayer instance.
  • keywords (dict) – A dict containing all the keywords to be updated for the layer.
write_keywords(layer, keywords)[source]

Write keywords for a datasource.

This is a wrapper method that will ‘do the right thing’ to store keywords for the given datasource. In particular, if the datasource is remote (e.g. a database connection) it will write the keywords from the keywords store.

Parameters:
  • layer (QgsMapLayer) – A QGIS QgsMapLayer instance.
  • keywords (dict) – A dict containing all the keywords to be written for the layer.
Raises:

UnsupportedProviderError

write_keywords_for_uri(uri, keywords)[source]

Write keywords for a URI into the keywords database. All the keywords for the uri should be written in a single operation. A hash will be constructed from the supplied uri and a lookup made in a local SQLite database for the keywords. If there is an existing record it will be updated, if not, a new one will be created.

See also

read_keyword_from_uri, delete_keywords_for_uri

Parameters:
  • uri (str) – A layer uri. e.g. `dbname='osm' host=localhost port=5432 user='foo' password='bar' sslmode=disable key='id' srid=4326`
  • keywords (dict) – The metadata keywords to write (which should be provided as a dict of key value pairs).
Returns:

The XML written to the DB

Raises:

KeywordNotFoundError if the keyword is not recognised.