tweepy调用update_profile_image传Image对象触发TypeError求助
问题原因
报错核心是Tweepy的update_profile_image方法默认将传入的第一个参数作为本地文件路径处理,从报错栈的源码行files = {'image': open(filename, 'rb')}就能看到,方法内部直接调用open()读取路径,无法直接接收PIL库生成的内存中Image对象,不需要强行把Image对象转成os.PathLike类型,也不需要把处理后的图片写入本地磁盘。
修复代码
注意原代码中api.user_timeline调用行缺少闭合右括号,修复后完整可运行代码如下:
import tweepy import requests from PIL import Image from io import BytesIO auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) # 补全原代码缺失的闭合括号 tweets = api.user_timeline( screen_name=QUERY, count=5, include_rts=False, tweet_mode='extended' ) response = requests.get(tweets[0].user.profile_image_url) img = Image.open(BytesIO(response.content)) flipped_img = img.transpose(Image.Transpose.FLIP_LEFT_RIGHT) # 将处理后的PIL图片写入内存字节流,无需落盘 img_buffer = BytesIO() # 保持和原头像一致的图片格式,避免格式识别错误 flipped_img.save(img_buffer, format=img.format) # 将字节流指针重置到起始位置,保证接口能读取到完整图片内容 img_buffer.seek(0) # 传入类文件对象完成头像更新 api.update_profile_image(filename='temp', file_=img_buffer)
注意事项
update_profile_image方法预留了file_参数,支持直接传入类文件对象(比如内存中的BytesIO流),不需要依赖本地文件路径- 调用
save方法写入字节流时必须明确指定图片格式,PIL无法从内存流自动推断输出格式 - 字节流写入完成后必须调用
seek(0)重置指针,否则接口读取到的是空内容,会触发上传失败
内容的提问来源于stack exchange,提问作者woninshot
相关产品推荐
相关产品推荐

