...

Python解析DB URI

数据库配置信息一般包含数据库类型、数据库服务器地址、端口号、用户名、密码、要链接的数据库,以及一些选项等,例如
通常我们需要配置多个变量来完成整个配置,如

db_type = 'mysql'
host = 'localhost'
port = 3306
user = 'root'
password = 'passw0rd'
db = 'testdb'
charset = 'utf8'
# ...

也可以按URI格式通过一个字符串给出,例如

mysql://root:passw0rd@localhost:3306/testdb?charset=utf8
postgres://postgress@localhost/testdb?sslmode=false

其中,密码、端口号、数据库,以及选项参数可以为空

使用正则解析DB URI

不支持解析?chaset=utf8

import re

PATTEN = r'(?P<db_type>\w+?)://(?P<user>\w+?):(?P<password>\w+?)@(?P<host>.*?):(?P<port>\d+?)/(?P<db>\w+)'

db_uri = 'mysql://root:passw0rd@localhost:3306/testdb'

r = re.match(PATTEN, db_uri)
if r:
    db_type = r.group('db_type')
    user = r.group('user')
    password = r.group('password') or None
    host = r.group('host')
    port = int(r.group('port') or 3306)
    db = r.group('db') or None
    print(host, port, user, password, db)

使用urlparse解析DB URI

from urllib.parse import urlparse, parse_qs

db_uri = 'mysql://root:passw0rd@localhost:3306/testdb?charset=utf8'

parsed_uri = urlparse(db_uri)
db_type = parsed_uri.scheme
user = parsed_uri.username
password = parsed_uri.password
host = parsed_uri.hostname
port = int(parsed_uri.port or 3306)
db = parsed_uri.path.lstrip('/')

charset = 'utf8'
if parsed_uri.query is not None:
    charset = parse_qs(parsed_uri.query).get('charset', [None])[0]

print(host, port, user, password, db, charset)
posted @ 2024-08-23 11:31  韩志超  阅读(9)  评论(0编辑  收藏  举报