Completed
Push — master ( 353b75...cee8d5 )
by Messense
05:20
created

wechatpy.parse_message()   B

Complexity

Conditions 6

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6.0702
Metric Value
cc 6
dl 0
loc 24
ccs 14
cts 16
cp 0.875
crap 6.0702
rs 7.6129
1
# -*- coding: utf-8 -*-
2 10
"""
3
    wechatpy.parser
4
    ~~~~~~~~~~~~~~~~
5
    This module provides functions for parsing WeChat messages
6
7
    :copyright: (c) 2014 by messense.
8
    :license: MIT, see LICENSE for more details.
9
"""
10 10
from __future__ import absolute_import, unicode_literals
11 10
import xmltodict
12
13 10
from wechatpy.messages import MESSAGE_TYPES, UnknownMessage
14 10
from wechatpy.events import EVENT_TYPES
15 10
from wechatpy.utils import to_text
16
17
18 10
def parse_message(xml):
19
    """
20
    解析微信服务器推送的 XML 消息
21
22
    :param xml: XML 消息
23
    :return: 解析成功返回对应的消息或事件,否则返回 ``UnknownMessage``
24
    """
25 10
    if not xml:
26
        return
27 10
    message = xmltodict.parse(to_text(xml))['xml']
28 10
    message_type = message['MsgType'].lower()
29 10
    if message_type in ('event', 'device_event'):
30 10
        event_type = message['Event'].lower()
31
        # special event type for device_event
32 10
        if message_type == 'device_event':
33
            event_type = 'device_{event}'.format(event=event_type)
34 10
        if event_type == 'subscribe' and message.get('EventKey'):
35
            # Scan to subscribe with scene id event
36 10
            event_type = 'subscribe_scan'
37 10
            message['Event'] = event_type
38 10
            message['EventKey'] = message['EventKey'].replace('qrscene_', '')
39 10
        message_class = EVENT_TYPES.get(event_type, UnknownMessage)
40
    else:
41 10
        message_class = MESSAGE_TYPES.get(message_type, UnknownMessage)
42
    return message_class(message)
43