Completed
Pull Request — master (#144)
by
unknown
21:10
created

_check_signature()   A

Complexity

Conditions 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1
Metric Value
cc 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
1
# -*- coding: utf-8 -*-
2 10
from __future__ import absolute_import, unicode_literals
3 10
import copy
4 10
import hashlib
5
import socket
6 10
7
import six
8 10
9
from wechatpy.utils import to_binary, to_text
10
11 10
12 10
def format_url(params, api_key=None):
13 10
    data = [to_binary('{0}={1}'.format(k, params[k])) for k in sorted(params) if params[k]]
14 10
    if api_key:
15 10
        data.append(to_binary('key={0}'.format(api_key)))
16
    return b"&".join(data)
17
18 10
19 10
def calculate_signature(params, api_key):
20 10
    url = format_url(params, api_key)
21
    return to_text(hashlib.md5(url).hexdigest().upper())
22
23 10
24 10
def _check_signature(params, api_key):
25 10
    _params = copy.deepcopy(params)
26
    sign = _params.pop('sign', '')
27 10
    return sign == calculate_signature(_params, api_key)
28 10
29
30
def dict_to_xml(d, sign):
31 10
    xml = ['<xml>\n']
32
    for k in sorted(d):
33
        # use sorted to avoid test error on Py3k
34 10
        v = d[k]
35 10
        if isinstance(v, six.integer_types) or v.isdigit():
36
            xml.append('<{0}>{1}</{0}>\n'.format(to_text(k), to_text(v)))
37
        else:
38 10
            xml.append(
39
                '<{0}><![CDATA[{1}]]></{0}>\n'.format(to_text(k), to_text(v))
40
            )
41
    xml.append('<sign><![CDATA[{0}]]></sign>\n</xml>'.format(to_text(sign)))
42
    return ''.join(xml)
43
44
45
def get_external_ip():
46
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
47
    try:
48
        wechat_ip = socket.gethostbyname('api.mch.weixin.qq.com')
49
        sock.connect((wechat_ip, 80))
50
        addr, port = sock.getsockname()
51
        sock.close()
52
        return addr
53
    except socket.error:
54
        return '127.0.0.1'
55