Skip to content

Commit

Permalink
对python3做兼容性适配
Browse files Browse the repository at this point in the history
  • Loading branch information
zwczou committed Jan 28, 2017
1 parent d5299e0 commit 177123a
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 61 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def fread(fname):
long_description=fread('README.md'),
license='BSD',
packages=find_packages(),
version='0.3.0',
version='0.4.0',
author='zwczou',
author_email='[email protected]',
url='https://github.com/zwczou/weixin-python',
Expand Down
25 changes: 19 additions & 6 deletions weixin/__init__.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,32 @@
# -*- coding: utf-8 -*-


from flask import current_app
from .msg import WeixinMsg
from .pay import WeixinPay
from .login import WeixinLogin
from .mp import WeixinMP
from .base import WeixinError, Map

from msg import WeixinMsg
from pay import WeixinPay
from login import WeixinLogin
from mp import WeixinMP
from base import WeixinError, Map
from collections import namedtuple


__all__ = ("Weixin")
__author__ = "Weicheng Zou <[email protected]>"


StandaloneApplication = namedtuple("StandaloneApplication", ["config"])


class Weixin(object):
"""
微信SDK
:param app 如果非flask,传入字典配置,如果是flask直接传入app实例
"""
def __init__(self, app=None):
if app is not None:
if isinstance(app, dict):
app = StandaloneApplication(config=app)
self.init_app(app)
self.app = app

Expand Down
4 changes: 2 additions & 2 deletions weixin/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
for k, v in arg.items():
if isinstance(v, dict):
v = Map(v)
self[k] = v

if kwargs:
for k, v in kwargs.iteritems():
for k, v in kwargs.items():
if isinstance(v, dict):
v = Map(v)
self[k] = v
Expand Down
18 changes: 11 additions & 7 deletions weixin/login.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
# -*- coding: utf-8 -*-


from __future__ import unicode_literals

import json
import urllib2
import requests

from base import Map, WeixinError
from urllib import urlencode
from .base import Map, WeixinError
try:
from urllib import urlencode
except Exception:
from urllib.parse import urlencode


__all__ = ("WeixinLoginError", "WeixinLogin")
Expand All @@ -20,7 +25,7 @@ def __init__(self, msg):
class WeixinLogin(object):

def __init__(self, app_id, app_secret):
self.opener = urllib2.build_opener(urllib2.HTTPSHandler())
self.sess = requests.Session()
self.app_id = app_id
self.app_secret = app_secret

Expand All @@ -31,9 +36,8 @@ def add_query(self, url, args):

def get(self, url, params):
url = self.add_query(url, params)
req = urllib2.Request(url)
resp = self.opener.open(req)
data = Map(json.loads(resp.read()))
resp = self.sess.get(url)
data = Map(json.loads(resp.content))
if data.errcode:
msg = "%(errcode)d %(errmsg)s" % data
raise WeixinLoginError(msg)
Expand Down
9 changes: 7 additions & 2 deletions weixin/mp.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-


from __future__ import unicode_literals

import os
import time
import json
Expand All @@ -9,8 +11,11 @@
import random
import requests

from base import Map, WeixinError
from urllib import urlencode
from .base import Map, WeixinError
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode


__all__ = ("WeixinMPError", "WeixinMP")
Expand Down
4 changes: 3 additions & 1 deletion weixin/msg.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
# -*- coding: utf-8 -*-


from __future__ import unicode_literals

import time
import hashlib

from datetime import datetime

from base import WeixinError
from .base import WeixinError
try:
from flask import request, Response
except ImportError:
Expand Down
57 changes: 15 additions & 42 deletions weixin/pay.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
# -*- coding: utf-8 -*-


from __future__ import unicode_literals

import time
import string
import random
import hashlib
import httplib
import urllib2
import requests

from base import Map, WeixinError
from .base import Map, WeixinError

try:
from flask import request
Expand All @@ -30,29 +31,6 @@
SUCCESS = "SUCCESS"


class HTTPSClientAuthHandler(urllib2.HTTPSHandler):

def __init__(self, key, cert):
"""
Usage:
opener = urllib2.build_opener(HTTPSClientAuthHandler('/path/to/file.pem', '/path/to/file.pem.') )
response = opener.open("https://example.org")
print response.read()
"""
urllib2.HTTPSHandler.__init__(self)
self.key = key
self.cert = cert

def https_open(self, req):
# Rather than pass in a reference to a connection class, we pass in
# a reference to a function which, for all intents and purposes,
# will behave as a constructor
return self.do_open(self.getConnection, req)

def getConnection(self, host, timeout=300):
return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)


class WeixinPayError(WeixinError):

def __init__(self, msg):
Expand All @@ -68,9 +46,7 @@ def __init__(self, app_id, mch_id, mch_key, notify_url, key=None, cert=None):
self.notify_url = notify_url
self.key = key
self.cert = cert
self.opener = urllib2.build_opener(urllib2.HTTPSHandler())
if self.key and self.cert:
self.openers = urllib2.build_opener(HTTPSClientAuthHandler(self.key, self.cert))
self.sess = requests.Session()

@property
def remote_addr(self):
Expand All @@ -83,24 +59,23 @@ def nonce_str(self):
char = string.ascii_letters + string.digits
return "".join(random.choice(char) for _ in range(32))

to_utf8 = lambda self, x: x.encode("utf8") if isinstance(x, unicode) else x

def sign(self, raw):
raw = [(k, str(raw[k]) if isinstance(raw[k], int) else raw[k])
for k in sorted(raw.keys())]
s = "&".join("=".join(kv) for kv in raw if kv[1])
s += "&key={0}".format(self.mch_key)
return hashlib.md5(self.to_utf8(s)).hexdigest().upper()
return hashlib.md5(s.encode("utf-8")).hexdigest().upper()

def check(self, data):
sign = data.pop("sign")
return sign == self.sign(data)

def to_xml(self, raw):
s = ""
for k, v in raw.iteritems():
s += "<{0}>{1}</{0}>".format(k, self.to_utf8(v), k)
return "<xml>{0}</xml>".format(s)
for k, v in raw.items():
s += "<{0}>{1}</{0}>".format(k, v)
s = "<xml>{0}</xml>".format(s)
return s.encode("utf-8")

def to_dict(self, content):
raw = {}
Expand All @@ -115,13 +90,11 @@ def fetch(self, url, data, use_cert=False):
data.setdefault("nonce_str", self.nonce_str)
data.setdefault("sign", self.sign(data))

req = urllib2.Request(url, data=self.to_xml(data))
try:
opener = self.openers if use_cert else self.opener
resp = opener.open(req, timeout=20)
except urllib2.HTTPError, e:
resp = e
content = resp.read()
if use_cert:
resp = self.sess.post(url, data=self.to_xml(data), cert=(self.cert, self.key))
else:
resp = self.sess.post(url, data=self.to_xml(data))
content = resp.content.decode("utf-8")
if "return_code" in content:
data = Map(self.to_dict(content))
if data.return_code == FAIL:
Expand Down

0 comments on commit 177123a

Please sign in to comment.