DSN Parser

0.4.0 · active · verified Wed Apr 15

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

Install

Imports

Quickstart

This quickstart demonstrates basic DSN parsing, extracting information from environment variables, and customizing the parsing result class.

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

view raw JSON →