The OGC web service connections that are configured in the data source manager are stored using the QgsSettings
API.
This is based on QSettings
which provides a way to store application specific settings in a key-value storage.
You can read the docs on how that works in detail: https://doc.qt.io/qt-6/qsettings.html#details
All connections are stored under the entries following the pattern /qgis/connections-{service}/{connection_name}
.
Addressing your example the correct settings key will be /qgis/connections-wms/WMS Sachsen
where WMS Sachsen is just a name I chose that will be shown in the list of connections.
from qgis.core import QgsSettings
url = "https://geodienste.sachsen.de/wms_list_ttsib/guest?"
conn_name = 'WMS Sachsen'
key = f'/qgis/connections-wms/{conn_name}/'
settings = QgsSettings()
settings.setValue(key + 'url', url)
# all the additional parameter settings. Change these to your needs.
settings.setValue(key + 'dpi-mode', 7)
settings.setValue(key + 'ignore-get-map-uri', False)
settings.setValue(key + 'ignore-get-feature-info-uri', False)
settings.setValue(key + 'smooth-pixmap-transform', False)
settings.setValue(key + 'ignore-axis-orientation', False)
settings.setValue(key + 'invert-axis-orientation', False)
If you use the code above in a startup.py file, the WMS connection will be available in the data source manager.
One final note on your initial attempt:
Although the addWmsWcsConnectionSettings
method sounds like it adds a new connection, it actually reads existing connection parameters from QgsSettings
and populates a QgsDataSourceUri
object. I find the name a bit misleading.