前言如何判断一个文件的类型呢,判断这个文件是png还jpg,还是mp3文件? filetype 包是 python 用来判断文件类型的依赖包,github地址https://github.com/h2non/filetype.py filetype 安装pip install filetype
简介一个小巧自由开放Python开发包,主要用来获得文件类型。包要求Python 3.+ 功能特色 使用示例import filetype
def main(): kind = filetype.guess('tests/fixtures/sample.jpg') if kind is None: print('Cannot guess file type!') return
print('File extension: %s' % kind.extension) print('File MIME type: %s' % kind.mime)
if __name__ == '__main__': main() 结合文件上传使用示例接下来看下使用场景,在前面接口测试文件上传的时候,参考这篇https://www.cnblogs.com/yoyoketang/p/8024039.html from requests_toolbelt import MultipartEncoder import requests
m = MultipartEncoder( fields = [ ('source', ('f1.ext', f1, 'application/x-example-mimetype')), ('source', ('f2.ext', f2, 'application/x-example-mimetype')), ] )
r = requests.post('http:///post', data=m, headers={'Content-Type': m.content_type}) imgFile 后面的参数 ("1.png", open("d:\\1.png", "rb"), "image/png") , 每次都需要根据不同的文件类型去修改成对应的mime类型。 接下来可以用上面的自动获取文件类型的方法,写个函数,只需传文件的路径即可自动获取
import filetype import os from requests_toolbelt import MultipartEncoder import requests # 作者-上海悠悠 QQ交流群:717225969
def upload(filepath="files/122.png"): '''根据文件路径,自动获取文件名称和文件mime类型''' kind = filetype.guess(filepath) if kind is None: print('Cannot guess file type!') return # 媒体类型,如:image/png mime_type = kind.mime # 文件真实路径 file_real_path = os.path.realpath(filepath) # 获取文件名 122.png fullflname = os.path.split(file_real_path)[-1] return (fullflname, open(file_real_path, "rb"), mime_type)
m = MultipartEncoder( fields = [ ('source', upload(filepath="files/122.png")), ('source', upload(filepath="files/123.png")), ] )
r = requests.post('http:///post', data=m, headers={'Content-Type': m.content_type})
|