python2.7上传中文名文件到企业微信,返回media_id为空

用python上传中文名文件到企业微信
报错:{'errcode': 44001, 'errmsg': 'empty media data, hint: [1549176653_2_aa7212a4ff64b96314b465d5f66a2b3e], more info at https://open.work.weixin.qq.com/devtool/query?e=44001'}

#!/usr/bin/python
#coding=gbk

import urllib,urllib2
import json
import sys
import requests


print sys.getdefaultencoding()

reload(sys)
sys.setdefaultencoding('utf8')

print sys.getdefaultencoding()

def gettoken():
    url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
    params = {'corpid':'XXXXXXXXXXXXXXXXXXXX','corpsecret':'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'}
    r = requests.get(url=url, params=params)
    token=json.loads(r.text)['access_token']
    return token

def get_media_ID(path):
    token = gettoken()
    img_url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token='+token+'&type=file'
    files = {'file': open(path, 'rb')}
    print files
    r = requests.post(img_url, files=files)
    print r.json()
    re = r.json()['media_id']
    return re

def senddata(accesstoken,user,agentid,filename):
    media_id=get_media_ID(filename)
    print media_id
    post_data={
                "touser": user,
                "msgtype": "file",
                "agentid": agentid,
                "file" : {
                         "media_id" : media_id
                },
                "safe":0
    }
    #json_post_data = json.dumps(post_data,False,False)
    json_post_data=json.dumps(post_data, ensure_ascii=False).encode('utf-8')
    send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='+accesstoken
    print send_url
    r = requests.post(send_url, data=json_post_data, headers={"Content-Type": "application/json; charset=utf-8"})
    return r.text


if __name__ == '__main__':
    user = "ceshi"
    agentid = "1000020"
    filename = u"测试文件.csv"

    print filename

    accesstoken = gettoken()
    senddata(accesstoken, user, agentid, filename)

推测是编码问题,试了N个方法
网上比较统一的解决方法是改fields.py,也已经改过了

    # value = email.utils.encode_rfc2231(value, 'utf-8')
    # value = '%s*=%s' % (name, value)
    value = '%s="%s"' % (name, value.decode("utf8","ignore"))

2个回答

def get_media_ID(path):
token = gettoken()
img_url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload
files = {'file': open(path, 'rb')}
data={
"access_token":{}.format(token),
"type":"file"
}
r = requests.post(img_url, files=files,data=data)
re = json.loads(r.text)["media_id"]
if not re is None:
return re
else:
return None

文件名字不能是中文,我之前试过中文名图片,发现不行。后来改成英文就可以了,你可以在项目里做一个中英文映射就可以了。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!