Rumah > Soal Jawab > teks badan
我想用django存储微信服务器发送过来的文件,与微信的交互使用的了'wechat-python-SDK',其中用一个方法是.download_media(media_id)用于获取微信服务器上的媒体文件。
这个方法的介绍如下:
返回值:当请求成功时,返回一个 requests.Response 对象,下面示例将该对象存储为本地文件:
response = wechat.download_media('your media id') with open('yourfilename', 'wb') as fd: for chunk in response.iter_content(1024): fd.write(chunk)
异常:当发生失败时抛出 exceptions.OfficialAPIError 异常,该异常包含了错误的代号与原因信息。
我写的代码如下:
if type == 'voice':#语音数据 media_id = WC.message.media_id # 对应于 XML 中的 MediaId format = WC.message.format # 对应于 XML 中的 Format media_name = media_id +'.'+ format recognition = WC.message.recognition # 对应于 XML 中的 Recognition try: response = WC.download_media(media_id=media_id) media = File(response.raw) media_file = FileSystemStorage().save(name=media_name,content=media) msg = Record( CreateTime=datetime.utcfromtimestamp(int(time)), Media = media_file, Recognition=recognition, Type=type, FromUser=user, Corrected=False, ) msg.save() except Exception as e: ResponseXml = WC.response_text(content="存储语音信息出错!" + str(e)) return HttpResponse(ResponseXml) ResponseXml = WC.response_text(content="保存成功!")
现在有一个问题:现在的代码运行可以成功的创建一个文件,但文件的大小是0,也就是并没有成功的将数据保存下来,只是创建了文件,不知道应该如何定位问题?