Created
March 8, 2010 18:29
-
-
Save jacobian/325428 to your computer and use it in GitHub Desktop.
This file contains 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
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