Python3 URL和数据库 字符字典互转

Python | URL | URI | 连接字符串 | URL转字典 | 字典转 URL | 数据库 | 请求

Posted by luoruiqing on July 24, 2020

URL

urllib 模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from urllib import parse


url = 'https://www.baidu.com/s?ie=utf-8&wd=%E4%BD%A0%E5%A5%BD'
# 解析成ParseResult对象
parsed = parse.urlparse(url)
# 解析成字典对象(默认是有序字典)
parsed_dict = dict(parsed._asdict())
# 解析query查询参数为字典(单值)
parsed_query_dict = dict(parse.parse_qsl(parsed.query))
# 解析query查询参数为字典(值为列表)
parsed_query_dict_list = dict(parse.parse_qs(parsed.query))
# 将query查询参数转字符
unparse_query_string = parse.urlencode(parsed_query_dict)
# URL的组成部分
components = (parsed.scheme, parsed.netloc, parsed.path, parsed.params, unparse_query_string, parsed.fragment)
# 根据模块组合成URL
assembly = parse.urlunparse(components)

print('示例: ', url)
print('URL转字典: ', parsed_dict)
print('URL转字典query(单值类型): ', parsed_query_dict)
print('URL转字典query(列表类型): ', parsed_query_dict_list)
print('字典转URL: ', assembly)

数据库

sqlalchemy 模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from sqlalchemy.engine.url import URL, _parse_rfc1738_args


# 字符
uri = 'mysql://root:123456@localhost:3306/test?timeout=30'
# 字符转URL对象
parsed = _parse_rfc1738_args(str(uri))
# 解析基本信息
parsed_dict = parsed.translate_connect_args()
# 增加解析后的驱动名称及参数(根据情况决定assembly是否需要)
parsed_dict = {**parsed_dict, 'drivername': parsed.drivername, 'query': parsed.query}

# 组合URL
assembly = str(URL(**parsed_dict))
print('示例: ', uri)
print(f'解析后(转字典): ', parsed_dict)
print(f'组合后(转字符): ', assembly)