分析DSN URL
dsnparse的Python项目详细描述
解析dsn connection url strings。我保留了 复制DSN解析代码 prom和morp,我意识到 我打算在未来需要更多的DSN网址,所以我决定 创造一些更模块化的东西。
这是 dj-database-url。
所以,现在您可以创建这样的DSN:
scheme://user:pass@host:port/path?query=query_val#fragment
例如,让我们看看prom dsn:
prom.interface.postgres.Interface://testuser:testpw@localhost/testdb
现在让我们分析一下:
importdsnparsedsn="prom.interface.postgres.Interface://testuser:testpw@localhost:1234/testdb"r=dsnparse.parse(dsn)print(r.scheme)# prom.interface.postgres.Interfaceprint(r.username)# testuserprint(r.password)# testpwprint(r.host)# localhostprint(r.hostloc)# localhost:1234print(r.paths)# ['testdb']
此外,dsnparse可以方便地使用环境变量:
r=dsnparse.parse_environ('ENVIRONMENT_VARIABLE_NAME')
我试图使接口与urlparse非常相似,因此它将 感觉熟悉使用。
示例
默认情况下,dsnparse.parse(dsn)返回一个ParseResult实例, 但可以定制:
importdsnparseclassMyResult(dsnparse.ParseResult):@classmethoddefparse(cls,dsn,**defaults):d=super(MyResult,cls).parse(dsn,**defaults)# d is a dict and you can customize its keys/values hered["interface"]=d.pop("scheme")returnddsn="Interface://testuser:testpw@localhost:1234/testdb"r=dsnparse.parse(dsn,parse_class=MyResult)print(isinstance(r,MyResult))# Trueprint(r.interface)# Interface
安装
使用pip:
pip install dsnparse
或者将pip与github一起使用:
pip install git+https://github.com/Jaymon/dsnparse#egg=dsnparse