Skip to content

Instantly share code, notes, and snippets.

@jacobian
Created March 8, 2010 18:29
Show Gist options
  • Save jacobian/325428 to your computer and use it in GitHub Desktop.
Save jacobian/325428 to your computer and use it in GitHub Desktop.
def build_dsn(dbtype, params):
"""
Build a DSN-style connection string, a la:
postgres://dbname=jacob,dbpass=sekreit
Returns a string.
"""
args = ",".join(["%s=%s" % (k,v) for (k,v) in params.items()])
return "%s://%s" % (dbtype, args)
def unpack_dsn(dsn):
"""
Returns (dbtype, dict_of_params)
"""
dbtype, strparams = dsn.split("://", 1)
params = {}
for keypair in strparams.split(","):
k, v = keypair.split("=", 1)
params[k] = v
return (dbtype, params)
if __name__ == '__main__':
params = {'dbname': 'jacob', 'dbpass': 'sekreit'}
print build_dsn('postgres', params)
# should print: postgres://dbname=jacob,dbpass=sekreit
print unpack_dsn("mysql://db=one,pass=two")
# shoud print ("mysql", {"db": "one", "pass": "two"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment