DSN Parser
dsnparse is a Python library designed to easily parse Data Source Name (DSN) connection strings, similar to URLs. It's used in projects like 'prom' and 'morp' and aims to provide an interface familiar to users of Python's `urlparse` module. The current version is 0.4.0, and it maintains an infrequent but active release cadence, with the last update in October 2025.
Warnings
- gotcha Accessing DSN components (e.g., `username`, `password`, `port`, `fragment`, `query`) that are not present in the DSN string will return `None`. Always check for `None` or use default values if these components are optional in your application.
- gotcha The `paths` attribute returns a list of path segments, even if there is only one. If you expect a single path, access it as `r.paths[0]` after checking the list is not empty.
- gotcha Be aware of the distinction between `r.host` and `r.hostloc`. `r.host` will provide only the hostname, while `r.hostloc` will include the port if present (e.g., 'localhost' vs 'localhost:1234').
- gotcha When parsing from environment variables using `dsnparse.parse_environ(KEY)`, the library expects the variable to be set. If the environment variable is not found, it will raise a `KeyError` unless handled by the calling code.
Install
-
pip install dsnparse
Imports
- parse
from dsnparse import parse
- parse_environ
from dsnparse import parse_environ
- ParseResult
from dsnparse import ParseResult
Quickstart
import dsnparse
import os
# Example 1: Basic DSN parsing
dsn = "prom.interface.postgres.Interface://testuser:testpw@localhost:1234/testdb?appname=my_app#frag1"
r = dsnparse.parse(dsn)
print(f"Scheme: {r.scheme}") # prom.interface.postgres.Interface
print(f"Username: {r.username}") # testuser
print(f"Password: {r.password}") # testpw
print(f"Host: {r.host}") # localhost
print(f"Port: {r.port}") # 1234
print(f"Host Location: {r.hostloc}") # localhost:1234
print(f"Paths: {r.paths}") # ['testdb']
print(f"Query: {r.query}") # appname=my_app
print(f"Fragment: {r.fragment}") # frag1
print(f"Get Query Param 'appname': {r.get_query('appname')}") # my_app
# Example 2: Parsing from environment variable
os.environ['MY_DB_DSN'] = os.environ.get('MY_DB_DSN', 'sqlite:///:memory:')
env_dsn = dsnparse.parse_environ('MY_DB_DSN')
print(f"Env DSN Scheme: {env_dsn.scheme}") # sqlite
print(f"Env DSN Path: {env_dsn.path}") # :memory:
# Example 3: Custom ParseResult class
class MyResult(dsnparse.ParseResult):
def configure(self):
# Expose 'scheme' as 'interface' for custom logic
self.interface = self.scheme
custom_dsn = "MyInterface://customuser:custompass@host:5432/path"
r_custom = dsnparse.parse(custom_dsn, parse_class=MyResult)
print(f"Custom DSN Type: {type(r_custom)}") # <class '__main__.MyResult'>
print(f"Custom DSN Interface: {r_custom.interface}") # MyInterface