Skip to content

Commit

Permalink
Merge branch 'release/v0.5.8'
Browse files Browse the repository at this point in the history
  • Loading branch information
doraemonext committed Jun 1, 2015
2 parents c15f18a + bf2632b commit 56a185b
Show file tree
Hide file tree
Showing 8 changed files with 127 additions and 21 deletions.
6 changes: 6 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@
ChangeLog
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

v0.5.8
^^^^^^^^^^^^^^^^^^^^^^^^^^^

* 增加了小视频消息类支持
* 修复了多层级XML解析问题

v0.5.7
^^^^^^^^^^^^^^^^^^^^^^^^^^^

Expand Down
4 changes: 4 additions & 0 deletions docs/basic.rst
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@

:return: 解析好的 WechatMessage 对象

.. py:attribute:: message
功能同 :func:`get_message`

.. py:method:: get_access_token()
获取 Access Token 及 Access Token 过期日期, 仅供缓存使用, 如果希望得到原生的 Access Token 请求数据请使用 :func:`grant_token`
Expand Down
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@
# built documents.
#
# The short X.Y version.
version = '0.5.7'
version = '0.5.8'
# The full version, including alpha/beta/rc tags.
release = '0.5.7'
release = '0.5.8'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand Down
47 changes: 39 additions & 8 deletions docs/messages.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,17 @@ media_id 视频消息媒体 ID
thumb_media_id 视频消息缩略图的媒体 ID
================ ==================================

小视频消息类 ShortVideoMessage
---------------------------

================ ==================================
name value
================ ==================================
type 'shortvideo'
media_id 视频消息媒体 ID
thumb_media_id 视频消息缩略图的媒体 ID
================ ==================================

链接消息类 LinkMessage
---------------------------
============ ==================================
Expand Down Expand Up @@ -126,16 +137,36 @@ precision 地理位置精度

自定义菜单事件
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=========== ======================================================
name value
=========== ======================================================
type 'click' 或 'view'
key 事件 key 值
======================== ======================================================
name value
======================== ======================================================
type 'click'

当 type = 'click' 时,它与自定义菜单接口中KEY值对应;
'view'

当 type = 'view' 时,它是设置的跳转URL
=========== ======================================================
'scancode_push'

'scancode_waitmsg'

'pic_sysphoto'

'pic_photo_or_album'

'pic_weixin'

'location_select'

key 事件 key 值

当 type = 'click' 时,它与自定义菜单接口中KEY值对应;

当 type = 'view' 时,它是设置的跳转URL

当 type 为其他取值时,它是事件KEY值,由开发者在创建菜单时设定
ScanCodeInfo 扫描信息,当且仅当 type = 'scancode_push' 或 'scancode_waitmsg' 时存在
SendPicsInfo 发送的图片信息,当且仅当 type = 'pic_sysphoto' 或 'pic_photo_or_album' 或 'pic_weixin' 时存在
SendLocationInfo 发送的位置信息,当且仅当 type = 'location_select' 时存在
======================== ======================================================

模板消息事件
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name='wechat-sdk',
version='0.5.7',
version='0.5.8',
keywords=('wechat', 'sdk', 'wechat sdk'),
description=u'微信公众平台Python开发包',
long_description=open("README.rst").read(),
Expand Down
16 changes: 7 additions & 9 deletions wechat_sdk/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .messages import MESSAGE_TYPES, UnknownMessage
from .exceptions import ParseError, NeedParseError, NeedParamError, OfficialAPIError
from .reply import TextReply, ImageReply, VoiceReply, VideoReply, MusicReply, Article, ArticleReply
from .lib import disable_urllib3_warning
from .lib import disable_urllib3_warning, XMLStore


class WechatBasic(object):
Expand Down Expand Up @@ -113,24 +113,22 @@ def parse_data(self, data):
raise ParseError()

try:
doc = minidom.parseString(data)
xml = XMLStore(xmlstring=data)
except Exception:
raise ParseError()

params = [ele for ele in doc.childNodes[0].childNodes
if isinstance(ele, minidom.Element)]

for param in params:
if param.childNodes:
text = param.childNodes[0]
result[param.tagName] = text.data
result = xml.xml2dict
result['raw'] = data
result['type'] = result.pop('MsgType').lower()

message_type = MESSAGE_TYPES.get(result['type'], UnknownMessage)
self.__message = message_type(result)
self.__is_parse = True

@property
def message(self):
return self.get_message()

def get_message(self):
"""
获取解析好的 WechatMessage 对象
Expand Down
55 changes: 55 additions & 0 deletions wechat_sdk/lib.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-

from xml.dom import minidom, Node


def disable_urllib3_warning():
"""
Expand All @@ -11,3 +13,56 @@ def disable_urllib3_warning():
requests.packages.urllib3.disable_warnings()
except Exception:
pass


class XMLStore(object):
"""
XML 存储类,可方便转换为 Dict
"""
def __init__(self, xmlstring):
self._raw = xmlstring
self._doc = minidom.parseString(xmlstring)

@property
def xml2dict(self):
"""
将 XML 转换为 dict
"""
self._remove_whitespace_nodes(self._doc.childNodes[0])
return self._element2dict(self._doc.childNodes[0])

def _element2dict(self, parent):
"""
将单个节点转换为 dict
"""
d = {}
for node in parent.childNodes:
if not isinstance(node, minidom.Element):
continue
if not node.hasChildNodes():
continue

if node.childNodes[0].nodeType == minidom.Node.ELEMENT_NODE:
try:
d[node.tagName]
except KeyError:
d[node.tagName] = []
d[node.tagName].append(self._element2dict(node))
elif len(node.childNodes) == 1 and node.childNodes[0].nodeType in [minidom.Node.CDATA_SECTION_NODE, minidom.Node.TEXT_NODE]:
d[node.tagName] = node.childNodes[0].data
return d

def _remove_whitespace_nodes(self, node, unlink=True):
"""
删除空白无用节点
"""
remove_list = []
for child in node.childNodes:
if child.nodeType == Node.TEXT_NODE and not child.data.strip():
remove_list.append(child)
elif child.hasChildNodes():
self._remove_whitespace_nodes(child, unlink)
for node in remove_list:
node.parentNode.removeChild(node)
if unlink:
node.unlink()
14 changes: 13 additions & 1 deletion wechat_sdk/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,17 @@ def __init__(self, message):
super(VideoMessage, self).__init__(message)


@handle_for_type('shortvideo')
class ShortVideoMessage(WechatMessage):
def __init__(self, message):
try:
self.media_id = message.pop('MediaId')
self.thumb_media_id = message.pop('ThumbMediaId')
except KeyError:
raise ParseError()
super(ShortVideoMessage, self).__init__(message)


@handle_for_type('location')
class LocationMessage(WechatMessage):
def __init__(self, message):
Expand Down Expand Up @@ -86,7 +97,8 @@ def __init__(self, message):
if self.type == 'subscribe' or self.type == 'scan':
self.key = message.pop('EventKey', None)
self.ticket = message.pop('Ticket', None)
elif self.type == 'click' or self.type == 'view':
elif self.type in ['click', 'view', 'scancode_push', 'scancode_waitmsg',
'pic_sysphoto', 'pic_photo_or_album', 'pic_weixin', 'location_select']:
self.key = message.pop('EventKey')
elif self.type == 'location':
self.latitude = float(message.pop('Latitude'))
Expand Down

0 comments on commit 56a185b

Please sign in to comment.