Python2.7 uploads the file with Chinese name to WeCom, and the return media_id is empty.

upload Chinese name file to WeCom with python
report error: {"errcode": 44001," errmsg": "empty media data, hint: [1549176653_2_aa7212a4ff64b96314b465d5f66a2b3e], more info at https://open.work.weixin.qq.c..."}

-sharp!/usr/bin/python
-sharpcoding=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
    }
    -sharpjson_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)

speculate that it is a coding problem. I have tried N methods.
the more unified solution on the Internet is to change fields.py, and it has been changed

.
    -sharp value = email.utils.encode_rfc2231(value, "utf-8")
    -sharp value = "%s*=%s" % (name, value)
    value = "%s="%s"" % (name, value.decode("utf8","ignore"))
Jun.08,2022
Menu