Skip to content

Commit

Permalink
Fix: 修正在 Python 3 中的表现
Browse files Browse the repository at this point in the history
  • Loading branch information
doraemonext committed Apr 9, 2016
1 parent 0a3ab06 commit 3350b40
Show file tree
Hide file tree
Showing 9 changed files with 33 additions and 23 deletions.
4 changes: 0 additions & 4 deletions tests/core/test_conf.py
@@ -1,9 +1,5 @@
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import os
import json
import time
import unittest

Expand Down
3 changes: 2 additions & 1 deletion tests/test_basic.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-

from __future__ import absolute_import, unicode_literals
from __future__ import unicode_literals

import os
import json
import unittest
Expand Down
14 changes: 8 additions & 6 deletions wechat_sdk/basic.py
Expand Up @@ -125,7 +125,7 @@ def generate_jsapi_signature(self, timestamp, noncestr, url, jsapi_ticket=None):
'timestamp': timestamp,
'url': url,
}
keys = data.keys()
keys = list(data.keys())
keys.sort()
data_str = '&'.join(['%s=%s' % (key, data[key]) for key in keys])
signature = hashlib.sha1(data_str.encode('utf-8')).hexdigest()
Expand All @@ -141,10 +141,8 @@ def parse_data(self, data, msg_signature=None, timestamp=None, nonce=None):
:raises ParseError: 解析微信服务器数据错误, 数据不合法
"""
result = {}
if type(data) not in [str, unicode]:
raise ParseError()

data = data.encode('utf-8')
if isinstance(data, six.text_type): # unicode to str(PY2), str to bytes(PY3)
data = data.encode('utf-8')

if self.conf.encrypt_mode == 'safe':
if not (msg_signature and timestamp and nonce):
Expand Down Expand Up @@ -208,7 +206,11 @@ def response_text(self, content, escape=False):
self._check_parse()
content = self._transcoding(content)
if escape:
content = cgi.escape(content)
if six.PY2:
content = cgi.escape(content)
else:
import html
content = html.escape(content)

response = TextReply(message=self.__message, content=content).render()
return self._encrypt_response(response)
Expand Down
7 changes: 5 additions & 2 deletions wechat_sdk/lib/crypto/base.py
Expand Up @@ -5,7 +5,7 @@
import random
import struct
import socket

import six
from Crypto.Cipher import AES

from wechat_sdk.lib.crypto.pkcs7 import PKCS7Encoder
Expand Down Expand Up @@ -56,7 +56,10 @@ def decrypt(self, text, appid):
raise DecryptAESError(e)

try:
pad = ord(plain_text[-1])
if six.PY2:
pad = ord(plain_text[-1])
else:
pad = plain_text[-1]
# 去掉补位字符串
# pkcs7 = PKCS7Encoder()
# plain_text = pkcs7.encode(plain_text)
Expand Down
12 changes: 6 additions & 6 deletions wechat_sdk/lib/crypto/crypto.py
Expand Up @@ -23,7 +23,7 @@ def __init__(self, token, encoding_aes_key, _id):
:param encoding_aes_key: 公众平台上,开发者设置的EncodingAESKey
:param _id: 公众号的 appid 或企业号的 corpid
"""
self.__key = base64.b64decode(to_binary(encoding_aes_key) + '=')
self.__key = base64.b64decode(to_binary(encoding_aes_key) + to_binary('='))
if len(self.__key) != 32:
raise ValidateAESKeyError(encoding_aes_key)
self.__token = to_binary(token)
Expand Down Expand Up @@ -64,14 +64,14 @@ def _encrypt_message(self, msg, nonce, timestamp=None):
</xml>"""
nonce = to_binary(nonce)
timestamp = to_binary(timestamp) or to_binary(int(time.time()))
encrypt = self.__pc.encrypt(msg, self.__id)
encrypt = self.__pc.encrypt(to_text(msg), self.__id)
# 生成安全签名
signature = get_sha1_signature(self.__token, timestamp, nonce, encrypt)
return to_text(xml.format(
encrypt=encrypt,
signature=signature,
timestamp=timestamp,
nonce=nonce
encrypt=to_text(encrypt),
signature=to_text(signature),
timestamp=to_text(timestamp),
nonce=to_text(nonce)
))

def _decrypt_message(self, msg, msg_signature, timestamp, nonce):
Expand Down
4 changes: 3 additions & 1 deletion wechat_sdk/lib/crypto/pkcs7.py
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-

from wechat_sdk.utils import to_binary, to_text


class PKCS7Encoder(object):
"""提供基于PKCS7算法的加解密接口"""
Expand All @@ -18,7 +20,7 @@ def encode(cls, text):
if amount_to_pad == 0:
amount_to_pad = cls.block_size
# 获得补位所用的字符
pad = chr(amount_to_pad)
pad = to_binary(chr(amount_to_pad))
return text + pad * amount_to_pad

@classmethod
Expand Down
5 changes: 3 additions & 2 deletions wechat_sdk/lib/crypto/utils.py
Expand Up @@ -3,6 +3,7 @@
import hashlib

from wechat_sdk.lib.crypto.exceptions import CryptoComputeSignatureError
from wechat_sdk.utils import to_binary


def get_sha1_signature(token, timestamp, nonce, encrypt):
Expand All @@ -16,10 +17,10 @@ def get_sha1_signature(token, timestamp, nonce, encrypt):
"""

try:
sortlist = [token, timestamp, nonce, encrypt]
sortlist = [token, timestamp, nonce, to_binary(encrypt)]
sortlist.sort()
sha = hashlib.sha1()
sha.update("".join(sortlist))
sha.update(to_binary("").join(sortlist))
return sha.hexdigest()
except Exception as e:
raise CryptoComputeSignatureError(e)
4 changes: 3 additions & 1 deletion wechat_sdk/lib/request.py
Expand Up @@ -2,6 +2,7 @@

import json
import requests
import six

from wechat_sdk.exceptions import OfficialAPIError

Expand Down Expand Up @@ -37,7 +38,8 @@ def request(self, method, url, access_token=None, **kwargs):

if isinstance(kwargs.get("data", ""), dict):
body = json.dumps(kwargs["data"], ensure_ascii=False)
body = body.encode('utf8')
if isinstance(body, six.text_type):
body = body.encode('utf8')
kwargs["data"] = body

r = requests.request(
Expand Down
3 changes: 3 additions & 0 deletions wechat_sdk/utils.py
Expand Up @@ -33,6 +33,9 @@ def to_binary(value, encoding='utf-8'):
return value
if isinstance(value, six.text_type):
return value.encode(encoding)

if six.PY3:
return six.binary_type(str(value), encoding) # For Python 3
return six.binary_type(value)


Expand Down

1 comment on commit 3350b40

@cybergalaxy
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

crypto.py:
encrypt = self.__pc.encrypt(to_text(msg), self.__id)
breaked the encrypt on python2.7.

Please sign in to comment.