media.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. import os
  4. from ..api.base import BaseWeChatAPI
  5. from ...type import RequestType
  6. from ...utils import sha256
  7. class Media(BaseWeChatAPI):
  8. def _media_upload(self, content, filepath, filename, path):
  9. if not content:
  10. if not (filepath and os.path.exists(filepath) and os.path.isfile(filepath) and path):
  11. raise Exception('filepath is not assigned or not exists')
  12. with open(filepath, mode = 'rb') as f:
  13. content = f.read()
  14. if not filename:
  15. filename = os.path.basename(filepath)
  16. else:
  17. if not filename:
  18. raise Exception('filename is not assigned or not exists')
  19. data = {
  20. 'meta': '{"filename":"%s","sha256":"%s"}' % (filename, sha256(content))
  21. }
  22. mimes = {
  23. '.bmp': 'image/bmp',
  24. '.jpg': 'image/jpeg',
  25. '.jpeg': 'image/jpeg',
  26. '.png': 'image/png',
  27. '.avi': 'video/x-msvideo',
  28. '.wmv': 'video/x-ms-wmv',
  29. '.mpeg': 'video/mpeg',
  30. '.mp4': 'video/mp4',
  31. '.mov': 'video/quicktime',
  32. '.mkv': 'video/x-matroska',
  33. '.flv': 'video/x-flv',
  34. '.f4v': 'video/x-f4v',
  35. '.m4v': 'video/x-m4v',
  36. '.rmvb': 'application/vnd.rn-realmedia-vbr'
  37. }
  38. media_type = os.path.splitext(filename)[-1]
  39. if media_type not in mimes:
  40. raise Exception('wechatpayv3 does not support this media type.')
  41. files = [('file', (filename, content, mimes[media_type]))]
  42. return self.client.core.request(
  43. path, method = RequestType.POST, data = data, sign_data = data.get('meta'), files = files)
  44. def image_upload(self, content = None, filepath = None, filename = None):
  45. """图片上传
  46. :param filepath: 图片文件路径
  47. :param filename: 文件名称,未指定则从filepath参数中截取
  48. """
  49. return self._media_upload(content, filepath, filename, '/v3/merchant/media/upload')
  50. def video_upload(self, content = None, filepath = None, filename = None):
  51. """视频上传
  52. :param filepath: 视频文件路径
  53. :param filename: 文件名称,未指定则从filepath参数中截取
  54. """
  55. return self._media_upload(content, filepath, filename, '/v3/merchant/media/video_upload')