Skip to content

Commit

Permalink
Code Style Improvement
Browse files Browse the repository at this point in the history
And run flake8 on travis
  • Loading branch information
whtsky committed Jul 18, 2016
1 parent dcc6f73 commit 206d87f
Show file tree
Hide file tree
Showing 13 changed files with 118 additions and 66 deletions.
4 changes: 3 additions & 1 deletion .travis.yml
Expand Up @@ -13,7 +13,9 @@ install:
- "python setup.py install"
- "pip install -r dev-requirements.txt"

script: coverage run --source=werobot setup.py -q nosetests
script:
- flake8 werobot
- coverage run --source=werobot setup.py -q nosetests

after_success: coveralls

Expand Down
5 changes: 4 additions & 1 deletion werobot/client.py
Expand Up @@ -299,7 +299,10 @@ def get_followers(self, first_user_id=None):
}
if first_user_id:
params["next_openid"] = first_user_id
return self.get("https://api.weixin.qq.com/cgi-bin/user/get", params=params)
return self.get(
"https://api.weixin.qq.com/cgi-bin/user/get",
params=params
)

def send_text_message(self, user_id, content):
"""
Expand Down
2 changes: 1 addition & 1 deletion werobot/config.py
Expand Up @@ -31,7 +31,7 @@ def from_pyfile(self, filename):
d = imp.new_module('config')
d.__file__ = filename
with open(filename) as config_file:
exec (compile(config_file.read(), filename, 'exec'), d.__dict__)
exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
self.from_object(d)
return True

Expand Down
8 changes: 6 additions & 2 deletions werobot/crypto/__init__.py
Expand Up @@ -12,8 +12,12 @@
raise RuntimeError("You need to install PyCrypto.")

from . import pkcs7
from .exceptions import UnvalidEncodingAESKey, AppIdValidationError, InvalidSignature
from werobot.utils import to_text, to_binary, generate_token, byte2int, get_signature
from .exceptions import (
UnvalidEncodingAESKey, AppIdValidationError, InvalidSignature
)
from werobot.utils import (
to_text, to_binary, generate_token, byte2int, get_signature
)


class PrpCrypto(object):
Expand Down
2 changes: 1 addition & 1 deletion werobot/crypto/exceptions.py
Expand Up @@ -11,4 +11,4 @@ class AppIdValidationError(Exception):


class InvalidSignature(Exception):
pass
pass
3 changes: 2 additions & 1 deletion werobot/crypto/pkcs7.py
Expand Up @@ -12,8 +12,9 @@ def encode(text):
pad = chr(amount_to_pad)
return text + pad * amount_to_pad


def decode(decrypted):
pad = ord(decrypted[-1])
if pad<1 or pad >32:
if pad < 1 or pad > 32:
pad = 0
return decrypted[:-pad]
27 changes: 18 additions & 9 deletions werobot/logger.py
Expand Up @@ -7,6 +7,7 @@

try:
import curses

assert curses
except ImportError:
curses = None
Expand Down Expand Up @@ -44,14 +45,22 @@ def __init__(self, color, *args, **kwargs):
if (3, 0) < sys.version_info < (3, 2, 3):
fg_color = six.text_type(fg_color, "ascii")
self._colors = {
logging.DEBUG: six.text_type(curses.tparm(fg_color, 4),
"ascii"), # Blue
logging.INFO: six.text_type(curses.tparm(fg_color, 2),
"ascii"), # Green
logging.WARNING: six.text_type(curses.tparm(fg_color, 3),
"ascii"), # Yellow
logging.ERROR: six.text_type(curses.tparm(fg_color, 1),
"ascii"), # Red
logging.DEBUG: six.text_type(
curses.tparm(fg_color, 4),
"ascii"
), # Blue
logging.INFO: six.text_type(
curses.tparm(fg_color, 2),
"ascii"
), # Green
logging.WARNING: six.text_type(
curses.tparm(fg_color, 3),
"ascii"
), # Yellow
logging.ERROR: six.text_type(
curses.tparm(fg_color, 1),
"ascii"
), # Red
}
self._normal = six.text_type(curses.tigetstr("sgr0"), "ascii")

Expand All @@ -73,4 +82,4 @@ def format(self, record):
record.exc_text = self.formatException(record.exc_info)
if record.exc_text:
formatted = formatted.rstrip() + "\n" + record.exc_text
return formatted.replace("\n", "\n ")
return formatted.replace("\n", "\n ")
27 changes: 19 additions & 8 deletions werobot/pay.py
Expand Up @@ -14,6 +14,7 @@ class WeixinPayClient(Client):
"""
简化微信支付API操作
"""

def __init__(self, appid, pay_sign_key, pay_partner_id, pay_partner_key):
self.pay_sign_key = pay_sign_key
self.pay_partner_id = pay_partner_id
Expand All @@ -31,7 +32,7 @@ def create_js_pay_package(self, **package):
:param package: 需要签名的的参数
:return: 可以使用的packagestr
"""
assert self.pay_partner_id, "PAY_PARTNER_ID IS EMPTY"
assert self.pay_partner_id, "PAY_PARTNER_ID IS EMPTY"
assert self.pay_partner_key, "PAY_PARTNER_KEY IS EMPTY"

package.update({
Expand All @@ -46,7 +47,9 @@ def create_js_pay_package(self, **package):
params.sort()

sign = md5('&'.join(
["%s=%s" % (str(p[0]), str(p[1])) for p in params + [('key', self.pay_partner_key)]])).hexdigest().upper()
["%s=%s" % (str(p[0]), str(p[1]))
for p in params + [('key', self.pay_partner_key)]]
)).hexdigest().upper()

return urlencode(params + [('sign', sign)])

Expand All @@ -66,7 +69,9 @@ def create_js_pay_params(self, **package):
:param package: 需要签名的的参数
:return: 支付需要的对象
"""
pay_param, sign, sign_type = self._pay_sign_dict(package=self.create_js_pay_package(**package))
pay_param, sign, sign_type = self._pay_sign_dict(
package=self.create_js_pay_package(**package)
)
pay_param['paySign'] = sign
pay_param['signType'] = sign_type

Expand All @@ -92,11 +97,12 @@ def create_js_edit_address_param(self, accesstoken, **params):
"""
params.update({
'appId': self.appid,
'nonceStr': generate_token(8),
'nonceStr': generate_token(8),
'timeStamp': int(time.time())
})

_params = [(k.lower(), str(v)) for k, v in params.items()] + [('accesstoken', accesstoken)]
_params = [(k.lower(), str(v)) for k, v in params.items()]
_params += [('accesstoken', accesstoken)]
_params.sort()

string1 = '&'.join(["%s=%s" % (p[0], p[1]) for p in _params])
Expand Down Expand Up @@ -142,7 +148,9 @@ def pay_deliver_notify(self, **deliver_info):
:param 需要签名的的参数
:return: 支付需要的对象
"""
params, sign, _ = self._pay_sign_dict(add_noncestr=False, add_timestamp=False, **deliver_info)
params, sign, _ = self._pay_sign_dict(
add_noncestr=False, add_timestamp=False, **deliver_info
)

params['app_signature'] = sign
params['sign_method'] = 'sha1'
Expand All @@ -169,12 +177,15 @@ def pay_order_query(self, out_trade_no):
_package = package.items()
_package.sort()

s = '&'.join(["%s=%s" % (p[0], str(p[1])) for p in _package + [('key', self.pay_partner_key)]])
s = '&'.join(["%s=%s" % (p[0], str(p[1]))
for p in (_package + [('key', self.pay_partner_key)])])
package['sign'] = md5(s).hexdigest().upper()

package = '&'.join(["%s=%s" % (p[0], p[1]) for p in package.items()])

params, sign, _ = self._pay_sign_dict(add_noncestr=False, package=package)
params, sign, _ = self._pay_sign_dict(
add_noncestr=False, package=package
)

params['app_signature'] = sign
params['sign_method'] = 'sha1'
Expand Down
73 changes: 45 additions & 28 deletions werobot/robot.py
Expand Up @@ -66,11 +66,16 @@ def crypto(self):
return self._crypto
app_id = self.config.get("APP_ID", None)
if not app_id:
raise ConfigError("You need to provide app_id to encrypt/decrypt messages")
raise ConfigError(
"You need to provide app_id to encrypt/decrypt messages"
)

encoding_aes_key = self.config.get("ENCODING_AES_KEY", None)
if not encoding_aes_key:
raise ConfigError("You need to provide encoding_aes_key to encrypt/decrypt messages")
raise ConfigError(
"You need to provide encoding_aes_key "
"to encrypt/decrypt messages"
)

from .crypto import MessageCrypt
self._crypto = MessageCrypt(
Expand Down Expand Up @@ -180,13 +185,16 @@ def filter(self, *args):

def _check_content(message):
return message.content == target_content
elif hasattr(target_content, "match") and callable(target_content.match):
elif (hasattr(target_content, "match") and
callable(target_content.match)):
# 正则表达式什么的

def _check_content(message):
return target_content.match(message.content)
else:
raise TypeError("%s is not a valid target_content" % target_content)
raise TypeError(
"%s is not a valid target_content" % target_content
)

def wraps(f):
if content_is_list:
Expand Down Expand Up @@ -248,33 +256,42 @@ def get_reply(self, message):
self.logger.warning("Catch an exception", exc_info=True)

def check_signature(self, timestamp, nonce, signature):
return check_signature(self.config["TOKEN"], timestamp, nonce, signature)
return check_signature(
self.config["TOKEN"], timestamp, nonce, signature
)


class WeRoBot(BaseRoBot):
ERROR_PAGE_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8" />
<title>Error: {{e.status}}</title>
<style type="text/css">
html {background-color: #eee; font-family: sans;}
body {background-color: #fff; border: 1px solid #ddd;
padding: 15px; margin: 15px;}
pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}
</style>
</head>
<body>
<h1>Error: {{e.status}}</h1>
<p>微信机器人不可以通过 GET 方式直接进行访问。</p>
<p>想要使用本机器人,请在微信后台中将 URL 设置为 <pre>{{request.url}}</pre> 并将 Token 值设置正确。</p>
<p>如果你仍有疑问,请<a href="http://werobot.readthedocs.org/en/%s/">阅读文档</a>
</body>
</html>
""" % werobot.__version__
ERROR_PAGE_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8" />
<title>Error: {{e.status}}</title>
<style type="text/css">
html {background-color: #eee; font-family: sans;}
body {background-color: #fff; border: 1px solid #ddd;
padding: 15px; margin: 15px;}
pre {
background-color: #eee;
border: 1px solid #ddd;
padding: 5px;
}
</style>
</head>
<body>
<h1>Error: {{e.status}}</h1>
<p>微信机器人不可以通过 GET 方式直接进行访问。</p>
<p>
想要使用本机器人,请在微信后台中将 URL 设置为 <pre>{{request.url}}</pre> 并将 Token 值设置正确。
</p>
<p>如果你仍有疑问,请<a href="http://werobot.readthedocs.org/en/%s/">阅读文档</a>
</body>
</html>
""" % werobot.__version__


class WeRoBot(BaseRoBot):
@property
def wsgi(self):
if not self._handlers:
Expand Down
8 changes: 4 additions & 4 deletions werobot/tests/test_config.py
@@ -1,11 +1,10 @@
import os

basedir = os.path.dirname(os.path.abspath(__file__))

from werobot import WeRoBot
from werobot.config import Config
from werobot.utils import generate_token

basedir = os.path.dirname(os.path.abspath(__file__))

TOKEN = "123"

Expand All @@ -21,8 +20,9 @@ def test_from_object():
config = Config()
config.from_pyfile(os.path.join(basedir, "test_config.py"))

class ConfigObject():
class ConfigObject:
TOKEN = "456"

config.from_object(ConfigObject())
assert config["TOKEN"] == "456"

Expand All @@ -36,4 +36,4 @@ def test_config_attribute():

token = generate_token()
robot.token = token
assert robot.config["TOKEN"] == token
assert robot.config["TOKEN"] == token
3 changes: 1 addition & 2 deletions werobot/tests/test_parser.py
@@ -1,5 +1,4 @@
from werobot.parser import parse_user_msg
from werobot.utils import to_text


def test_none_message():
Expand Down Expand Up @@ -196,4 +195,4 @@ def test_unknown_message():
assert message.raw == xml
assert message.target == "toUser"
assert message.source == "fromUser"
assert message.time == 1351776360
assert message.time == 1351776360
8 changes: 4 additions & 4 deletions werobot/tests/test_robot.py
Expand Up @@ -103,19 +103,19 @@ def test_filter():
robot = WeRoBot()

@robot.filter("喵")
def _():
def _1():
return "喵"

assert len(robot._handlers["text"]) == 1

@robot.filter(re.compile(to_text(".*?呵呵.*?")))
def _():
def _2():
return "哼"

assert len(robot._handlers["text"]) == 2

@robot.text
def _():
def _3():
return "汪"

assert len(robot._handlers["text"]) == 3
Expand Down Expand Up @@ -148,7 +148,7 @@ def _():
assert len(robot._handlers["text"]) == 3

@robot.text
def _():
def _4():
return "哦"

assert len(robot._handlers["text"]) == 4
Expand Down

0 comments on commit 206d87f

Please sign in to comment.