上传文件的特殊处理formdata
上传文件 链接的处理
from contextlib import closing
from io import BytesIO
from requests_toolbelt.multipart.encoder import MultipartEncoder
def judge_url_size(self, url, size_limit):
#获取url地址的大小
content = bytearray()
with closing(
requests.get(url, stream=True)) as req: # stream=True 设置文本流使用迭代器获取 如:req.iter_lines
if 'content-length' in req.headers:
if int(req.headers['content-length']) > size_limit:
raise Exception(
'content-length too many. content-length: ' + str(req.headers['content-length']))
content = req.content
else:
size_temp = 0
for line in req.iter_lines():
if line:
size_temp += len(line)
if size_temp > size_limit:
raise Exception('content-length too many.')
content.extend(line)
return bytes(content)
data = MultipartEncoder(
fields={
# "file": (name, open(file_path, 'rb'), "type=txt"),
# "file": (name, open(file_path, 'rb'), f'type={type}'),
"file": (name, BytesIO(file)),
}
)
本文来自博客园,作者:寻月隐君,转载请注明原文链接:https://www.cnblogs.com/QiaoPengjun/p/16317235.html