如何安全地从 URL 获取文件扩展名?

2024-01-03

考虑以下 URL



http://m3u.com/tunein.m3u
http://asxsomeurl.com/listen.asx:8024
http://www.plssomeotherurl.com/station.pls?id=111
http://22.198.133.16:8024
  

确定文件扩展名(.m3u/.asx/.pls)的正确方法是什么?显然最后一个没有文件扩展名。

编辑:我忘了提及 m3u/asx/pls 是音频流的播放列表(文本文件),必须以不同的方式进行解析。目标确定扩展名,然后将 url 发送到正确的解析函数。例如。


url = argv[1]
ext = GetExtension(url)
if ext == "pls":
  realurl = ParsePLS(url)
elif ext == "asx":
  realurl = ParseASX(url)
(etc.)
else:
  realurl = url
Play(realurl)

Use urlparse从 URL 中解析出路径,然后os.path.splitext获得扩展名。

import os
try:
    import urlparse
except ImportError:
    from urllib.parse import urlparse

url = 'http://www.plssomeotherurl.com/station.pls?id=111'
path = urlparse.urlparse(url).path
ext = os.path.splitext(path)[1]

请注意,扩展名可能不是文件类型的可靠指示符。超文本传输​​协议Content-Type标题可能会更好。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何安全地从 URL 获取文件扩展名? 的相关文章

随机推荐