liukaidi
蜗居的地主
采纳率25%
2019-02-03 16:41 阅读 1.6k

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条回答 默认 最新

  • shiverieskwok shiverieskwok 2019-02-05 18:49

    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

    点赞 评论 复制链接分享
  • u012965373 杨鑫newlfe 2019-07-03 10:50

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

    点赞 评论 复制链接分享

相关推荐