QGIS Initialization scripts

QGIS has the native ability to run a specified Python script when it starts. By loading an init script that will in turn load and run all the scripts in a given directory, this system allows Boundless Desktop’s QGIS to be configured every time it starts.

Setting the scripts path to a network shared folder, allows the system administrator to perform QGIS configuration tasks in several machines by simply adding or changing the scripts in that folder.

Usage

Set the QGIS_INIT_SCRIPTS_DIRECTORY environment variable to a directory path containing Python scripts to run at QGIS start, if the variable is not set, QGIS will look in a default local folder determined by QgsApplication.pkgDataPath() + /init_scripts.

On Windows, the default local folder is:

C:\Program Files\Boundless\Desktop\1.1\osgeo4w\apps\qgis\init_scripts

On Mac OS, the default local folder is:

/Library/Boundless/Desktop/1.1/Cellar/qgis2-bdesk/2.18.10/QGIS for Boundless Desktop 1.1.app/Contents/MacOS/../Resources/init_scripts

Tip

Setting the QGIS_INIT_SCRIPTS_DIRECTORY environment variable to a network shared folder, allows the system administrator to perform configuration tasks in several machines by simply adding or changing the scripts in that folder.

Note

Scripts are alphabetically sorted

Scripts run in alphabetically order, so if necessary prefix them with with some integers.

Warning

In Windows, if the QGIS_INIT_SCRIPTS_DIRECTORY environment variable is set to a folder other than the default one, the 000_win_load_authorities.py script must be copied from the default init_scripts folder to the new one. Otherwise, when trying to connect to some services endpoints, users may receive SSL Errors warnings claiming that a valid certificate for that URL is not available.

Scripts examples

Inside the init_scripts default folder there is an examples folder with some example scripts to illustrate a few common customization tasks, which are transcript below.

Tip

In order to run the examples, you can set QGIS_INIT_SCRIPTS_DIRECTORY environment variable to point to the examples directory before launching QGIS as specified above.

Checking for a setting value

# Sample script for QGIS Init Script
# This script will check for a setting value in user
# settings and set it to 'A Value' if not found

from qgis.PyQt.QtCore import QSettings
from qgis.core import QgsMessageLog
QgsMessageLog.logMessage("Init script: %s" % __file__, tag="Init script", level=QgsMessageLog.INFO)

if not QSettings().value("InitScript/MyTestSetting"):
    QgsMessageLog.logMessage("Setting 'InitScript/MyTestSetting' to 'A Value'", tag="Init script", level=QgsMessageLog.INFO)
    QSettings().setValue("InitScript/MyTestSetting", "A Value")
else:
    QgsMessageLog.logMessage("'InitScript/MyTestSetting' already set to '%s'" % QSettings().value("InitScript/MyTestSetting"), tag="Init script", level=QgsMessageLog.INFO)

Single run script

# Sample script for QGIS Init Script
# This script will check for a setting value to determine
# if it needs to be run.
# When run, it will set the setting value and log a line.


from qgis.PyQt.QtCore import QSettings
from qgis.core import QgsMessageLog
QgsMessageLog.logMessage("Init script: %s" % __file__, tag="Init script", level=QgsMessageLog.INFO)

if not QSettings().value("InitScript/RunOnceHasRun"):
    QgsMessageLog.logMessage("Setting 'InitScript/RunOnceHasRun' to 'true'", tag="Init script", level=QgsMessageLog.INFO)
    QSettings().setValue("InitScript/MyTestSetting", True)
else:
    QgsMessageLog.logMessage("'InitScript/MyTestSetting' already set to '%s'" % QSettings().value("InitScript/MyTestSetting"), tag="Init script", level=QgsMessageLog.INFO)

Install a plugin from a zip file

# Sample script for QGIS Init Script
# This script will install the HelloWorld plugin into user space (if not yet installed)
# The plugin will also be enabled.

import os
import zipfile

from qgis.PyQt.QtCore import QSettings
from qgis.utils import home_plugin_path, loadPlugin, startPlugin, plugins
from qgis.core import QgsMessageLog
QgsMessageLog.logMessage("Init script: %s" % __file__, tag="Init script", level=QgsMessageLog.INFO)

if "HelloWorld" not in plugins:
    # Installing
    zip_ref = zipfile.ZipFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test_data', 'helloworld.zip'), 'r')
    zip_ref.extractall(home_plugin_path)
    zip_ref.close()
    loadPlugin('HelloWorld')
    startPlugin('HelloWorld')
    QgsMessageLog.logMessage("Plugin HelloWorld has been successfully installed", tag="Init script", level=QgsMessageLog.INFO)
else:
    QgsMessageLog.logMessage("Plugin HelloWorld has been already installed", tag="Init script", level=QgsMessageLog.INFO)

Add a WMS connection

# Sample script for QGIS Init Script
# This script will add a demo WMS endpoint


from qgis.PyQt.QtCore import QSettings
from qgis.utils import home_plugin_path, loadPlugin, startPlugin, plugins
from qgis.core import QgsMessageLog
QgsMessageLog.logMessage("Init script: %s" % __file__, tag="Init script", level=QgsMessageLog.INFO)

WMS_URL="http://demo.boundlessgeo.com/geoserver/wms"
WMS_NAME="Boundlessgeo Geoserver Demo"

settings = QSettings()

if "Qgis/WMS/%s/authcfg" % WMS_NAME not in settings.allKeys():
    settings.setValue("Qgis/WMS/%s/authcfg" % WMS_NAME, "")
    settings.setValue("Qgis/WMS/%s/username" % WMS_NAME, "")
    settings.setValue("Qgis/WMS/%s/password" % WMS_NAME, "")
    settings.setValue("Qgis/connections-wms/%s/dpiMode" % WMS_NAME, 7)
    settings.setValue("Qgis/connections-wms/%s/ignoreAxisOrientation" % WMS_NAME, False)
    settings.setValue("Qgis/connections-wms/%s/ignoreGetFeatureInfoURI" % WMS_NAME, False)
    settings.setValue("Qgis/connections-wms/%s/ignoreGetMapURI" % WMS_NAME, False)
    settings.setValue("Qgis/connections-wms/%s/invertAxisOrientation" % WMS_NAME, False)
    settings.setValue("Qgis/connections-wms/%s/referer" % WMS_NAME, "")
    settings.setValue("Qgis/connections-wms/%s/smoothPixmapTransform" % WMS_NAME, "")
    settings.setValue("Qgis/connections-wms/%s/url" % WMS_NAME, WMS_URL)
    QgsMessageLog.logMessage("WMS %s has been successfully installed" % WMS_NAME, tag="Init script", level=QgsMessageLog.INFO)
else:
    QgsMessageLog.logMessage("WMS %s was already installed" % WMS_NAME,  tag="Init script", level=QgsMessageLog.INFO)

Set a default project

# Sample script for QGIS Init Script
# This script will add default project

import os
from shutil import copyfile
from qgis.PyQt.QtCore import QSettings
from qgis.core import QgsMessageLog, QgsApplication
QgsMessageLog.logMessage("Init script: %s" % __file__, tag="Init script", level=QgsMessageLog.INFO)


settings = QSettings()
DEFAULT_PROJECT_PATH=os.path.join(QgsApplication.qgisSettingsDirPath(), "project_default.qgs")

if not os.path.exists(DEFAULT_PROJECT_PATH):
    try:
        copyfile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test_data', 'project_default.qgs'), DEFAULT_PROJECT_PATH)
        QgsMessageLog.logMessage("Default project has been successfully installed", tag="Init script", level=QgsMessageLog.INFO)
        # Set the settings to use the default project
        settings.setValue("qgis/newProjectDefault", True)
    except Exception as ex:
        QgsMessageLog.logMessage("Error installing default project: %s" % ex, tag="Init script", level=QgsMessageLog.CRITICAL)
else:
    QgsMessageLog.logMessage("Default project was already installed",  tag="Init script", level=QgsMessageLog.INFO)

Add an authentication configuration

# Sample script for QGIS Init Script
# This script will initialize the authentication DB and 
# add and HTTP Basic authentication configuration. 
# The script will also set the master password to `password`
# 
# Note: this script can only run if the authentication DB was not 
# already created by the user, this means that it must be executed
# only once on a fresh QGIS installation before the user 
# started QGIS for the first time.


from qgis.PyQt.QtCore import QSettings
from qgis.core import QgsAuthManager, QgsAuthMethodConfig, QgsMessageLog

AUTHDB_MASTERPWD = 'password'

QgsMessageLog.logMessage("Init script: %s" % __file__, tag="Init script", level=QgsMessageLog.INFO)

# Do not run twice!
if not QSettings().value("InitScript/AuthCfgCreated", type=bool):
    QSettings().setValue("InitScript/AuthCfgCreated", True)
    # Check if authdb master password is set
    am = QgsAuthManager.instance()
    if not am.masterPasswordHashInDb():
        # Set it!
        am.setMasterPassword(AUTHDB_MASTERPWD, True)
        # Create config
        am.authenticationDbPath()
        am.masterPasswordIsSet()
        cfg = QgsAuthMethodConfig()
        cfg.setId('myauth1') # Optional, useful for plugins to retrieve an authcfg
        cfg.setName('Example Auth Config HTTP Basic')
        cfg.setMethod('Basic')
        cfg.setConfig('username', 'username')
        cfg.setConfig('password', 'password')
        am.storeAuthenticationConfig(cfg)
    else:
        QgsMessageLog.logMessage("Master password was already set: aborting", tag="Init script", level=QgsMessageLog.INFO)

else:
    QgsMessageLog.logMessage("AuthCfg was already created: aborting", tag="Init script", level=QgsMessageLog.INFO)

Show a message on start up

# Sample script for QGIS Init Script
# This script will open an info dialog


from qgis.PyQt.QtGui import QMessageBox

QMessageBox.information(None, "Hello", "Hello World!")