用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"))