根据rfc 3986验证uri引用
rfc3986的Python项目详细描述
RFC 3986的python实现,包括验证和授权 正在分析。
安装
使用pip安装rfc3986,就像这样:
pip install rfc3986
示例用法
以下是为rfc3986设想的两个最常见的用例。
替换urlparse
解析uri并接收与标准库非常相似的内容 urllib.parse.urlparse
fromrfc3986importurlparsessh=urlparse('ssh://user@git.openstack.org:29418/openstack/glance.git')print(ssh.scheme)# => sshprint(ssh.userinfo)# => userprint(ssh.params)# => Noneprint(ssh.port)# => 29418
要用新的片段创建它的副本,可以使用copy_with:
new_ssh=ssh.copy_with(scheme='https'userinfo='',port=443,path='/openstack/glance')print(new_ssh.scheme)# => httpsprint(new_ssh.userinfo)# => None# etc.
严格解析uri并应用验证
要将uri解析为一个方便的命名元组,您可以简单地:
fromrfc3986importuri_referenceexample=uri_reference('http://example.com')email=uri_reference('mailto:user@domain.com')ssh=uri_reference('ssh://user@git.openstack.org:29418/openstack/keystone.git')
通过解析的uri,您可以访问有关组件的数据:
print(example.scheme)# => httpprint(email.path)# => user@domain.comprint(ssh.userinfo)# => userprint(ssh.host)# => git.openstack.orgprint(ssh.port)# => 29418
它还可以解析存在unicode的uri:
uni=uri_reference(b'http://httpbin.org/get?utf8=\xe2\x98\x83')# ☃print(uni.query)# utf8=%E2%98%83
通过解析的uri,您还可以验证它:
ifssh.is_valid():subprocess.call(['git','clone',ssh.unsplit()])
您还可以获取解析的uri并将其规范化:
mangled=uri_reference('hTTp://exAMPLe.COM')print(mangled.scheme)# => hTTpprint(mangled.authority)# => exAMPLe.COMnormal=mangled.normalize()print(normal.scheme)# => httpprint(mangled.authority)# => example.com
但这两个uri(功能上)是等价的:
ifnormal==mangled:webbrowser.open(normal.unsplit())
您的路径、查询和片段对我们来说是安全的:
mangled=uri_reference('hTTp://exAMPLe.COM/Some/reallY/biZZare/pAth')normal=mangled.normalize()assertnormal=='hTTp://exAMPLe.COM/Some/reallY/biZZare/pAth'assertnormal=='http://example.com/Some/reallY/biZZare/pAth'assertnormal!='http://example.com/some/really/bizzare/path'
如果您实际上不需要真正的引用对象,只想规范化 您的uri:
fromrfc3986importnormalize_uriassert(normalize_uri('hTTp://exAMPLe.COM/Some/reallY/biZZare/pAth')=='http://example.com/Some/reallY/biZZare/pAth')
您还可以非常简单地验证uri:
fromrfc3986importis_valid_uriassertis_valid_uri('hTTp://exAMPLe.COM/Some/reallY/biZZare/pAth')
需要组件
您可以验证特定字符串是否是有效的uri,并要求 独立组件:
fromrfc3986importis_valid_uriassertis_valid_uri('http://localhost:8774/v2/resource',require_scheme=True,require_authority=True,require_path=True)# Assert that a mailto URI is invalid if you require an authority# componentassertis_valid_uri('mailto:user@example.com',require_authority=True)isFalse
如果有URIReference的实例,则可以传递相同的参数 到URIReference#is_valid,例如
fromrfc3986importuri_referencehttp=uri_reference('http://localhost:8774/v2/resource')asserturi.is_valid(require_scheme=True,require_authority=True,require_path=True)# Assert that a mailto URI is invalid if you require an authority# componentmailto=uri_reference('mailto:user@example.com')asserturi.is_valid(require_authority=True)isFalse
备选方案
贡献
这个项目遵循并执行python软件基金会的Code of Conduct。
如果你想贡献,但没有一个错误或功能在脑海中,感觉 免费给伊恩发邮件,看看你能帮上什么忙。
此项目的git存储库维护在 https://github.com/python-hyper/rfc3986