Created
January 13, 2026 07:48
-
-
Save vidhav/7e780705e09a4410605b9abd064b97b6 to your computer and use it in GitHub Desktop.
Startup-skript for QGIS som laster token for Norge i bilder WMTS (https://docs.qgis.org/3.40/en/docs/pyqgis_developer_cookbook/intro.html#the-startup-py-file)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import base64 | |
| from datetime import datetime, timezone | |
| from os import getenv | |
| from qgis.core import Qgis, QgsApplication, QgsAuthMethodConfig | |
| from qgis.utils import iface | |
| import requests | |
| def nib_token(): | |
| """Norge i bilder Token""" | |
| nib_auth = { | |
| "id": "nib1138", | |
| "name": "Norge i bilder Token", | |
| "url": "https://tilecache.norgeibilder.no/token", | |
| } | |
| GEOID_USERNAME = getenv("GEOID_USERNAME", "") | |
| GEOID_PASSWORD = getenv("GEOID_PASSWORD", "") | |
| if GEOID_USERNAME == "" or GEOID_PASSWORD == "": | |
| iface.messageBar().pushMessage(nib_auth["name"], "Fant ikke GeoID brukernavn og/eller passord i env.", duration=0, level=Qgis.Warning) | |
| return | |
| encoded = f"{GEOID_USERNAME}:{GEOID_PASSWORD}".encode() | |
| credentials = base64.b64encode(encoded).decode() | |
| # Sett expiration (i minutter) til slutten av dagen. | |
| now = datetime.now(timezone.utc) | |
| delta = now.replace(hour=23, minute=59, second=59, microsecond=999999) - now | |
| expiration = round(delta.total_seconds() / 60.0) | |
| res = requests.post( | |
| data={ | |
| "expiration": expiration, | |
| "f": "json", | |
| "client": "requestip", | |
| "ip": "", | |
| "referer": "", | |
| }, | |
| headers={ | |
| "Authorization": f"Basic {credentials}", | |
| }, | |
| url=nib_auth["url"], | |
| ) | |
| if res.ok == False: | |
| iface.messageBar().pushMessage(nib_auth["name"], f"Tjenesten svarte med feilkode: {res.status_code}.", duration=0, level=Qgis.Warning) | |
| return | |
| token = res.json().get("token", None) | |
| if token is None: | |
| iface.messageBar().pushMessage(nib_auth["name"], "Fant ikke token i respons.", duration=0, level=Qgis.Warning) | |
| return | |
| # Oppdater auth objekt for Norge i bilder. | |
| config = QgsAuthMethodConfig() | |
| config.setId(nib_auth["id"]) | |
| config.setName(nib_auth["name"]) | |
| config.setMethod("APIHeader") | |
| config.setUri(nib_auth["url"]) | |
| config.setConfig("X-Esri-Authorization", f"Bearer {token}") | |
| QgsApplication.authManager().storeAuthenticationConfig(config, True) | |
| iface.messageBar().pushMessage(nib_auth["name"], "Token er oppdatert.", duration=0, level=Qgis.Info) | |
| iface.initializationCompleted.connect(nib_token) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment