根据内容类型确定文件扩展名
最好使用内容类型标头来确定内容的类型,并确定用于将内容存储为文件的扩展名。
怎么做
继续运行示例的脚本。
可以使用 .extension 属性找到媒体类型的扩展名:
util = URLUtility(const.ApodEclipseImage())
print("Filename from content-type: " + util.extension_from_contenttype)
print("Filename from url: " + util.extension_from_url)
这会产生以下输出:
Reading URL: https://apod.nasa.gov/apod/image/1709/BT5643s.jpg
Read 171014 bytes
Filename from content-type: .jpg
Filename from url: .jpg
这会报告根据文件类型和 URL 确定的扩展名。 这些可能不同,但在本例中它们是相同的。
工作原理
以下是 .extension_from_contenttype 属性的实现:
@property
def extension_from_contenttype(self):
self.ensure_response()
map = const.ContentTypeToExtensions()
if self.contenttype in map:
return map[self.contenttype]
return None
第一行确保我们已读取 URL 的响应。 然后该函数使用 const 模块中定义的 python 字典,其中包含要扩展的内容类型字典:
def ContentTypeToExtensions():
return {
"image/jpeg": ".jpg",
"image/jpg": ".jpg",
"image/png": ".png"
}
如果内容类型在字典中,则返回相应的值。 否则,不返回任何内容。
请注意相应的属性 .extension_from_url:
@property
def extension_from_url(self):
ext = os.path.splitext(os.path.basename(self._parsed.path))[1]
return ext
这使用与 .filename 属性相同的技术来解析 URL,但返回 [1] 元素,该元素表示扩展名而不是基本文件名。