diff --git a/chinaapi/decorators.py b/chinaapi/decorators.py index 4618ef0..fbfdcad 100644 --- a/chinaapi/decorators.py +++ b/chinaapi/decorators.py @@ -12,7 +12,7 @@ def f_retry(*args, **kwargs): while tries > 1: try: return f(*args, **kwargs) - except exceptions, e: + except exceptions as e: if hook is not None: hook(e) tries -= 1 diff --git a/chinaapi/exceptions.py b/chinaapi/exceptions.py index b7b2ca0..9ba1c38 100644 --- a/chinaapi/exceptions.py +++ b/chinaapi/exceptions.py @@ -12,10 +12,10 @@ def __init__(self, url='', code=0, message='', sub_code=0, sub_message=''): @staticmethod def format(code, message): - return u'[%s]: %s, ' % (code, message) if code or message else '' + return '[%s]: %s, ' % (code, message) if code or message else '' def __str__(self): - return u'%s%srequest: %s' % ( + return '%s%srequest: %s' % ( self.format(self.code, self.message), self.format(self.sub_code, self.sub_message), self.url) @@ -29,7 +29,7 @@ def is_multipart(self): def get_url(self): if not self.is_multipart() and self.request.body: - return u'%s?%s' % (self.request.url, self.request.body) + return '%s?%s' % (self.request.url, self.request.body) return self.request.url diff --git a/chinaapi/jsonDict.py b/chinaapi/jsonDict.py index ba07621..04f1a00 100644 --- a/chinaapi/jsonDict.py +++ b/chinaapi/jsonDict.py @@ -42,4 +42,4 @@ def loads(string): >>> r['score'] 95 """ - return json.loads(string, object_hook=lambda pairs: JsonDict(pairs.iteritems())) \ No newline at end of file + return json.loads(string, object_hook=lambda pairs: JsonDict(iter(pairs.items()))) \ No newline at end of file diff --git a/chinaapi/open.py b/chinaapi/open.py index 2474c06..d92bafd 100644 --- a/chinaapi/open.py +++ b/chinaapi/open.py @@ -98,7 +98,7 @@ def _prepare_queries(self, queries): def _prepare_body(self, queries): results = ({}, {}) - for k, v in queries.items(): + for k, v in list(queries.items()): results[hasattr(v, 'read')][k] = v return results @@ -125,7 +125,7 @@ def request(self, segments, **queries): def handle_error(e): if self._is_retry_error(e): if files: - for f in files.values(): + for f in list(files.values()): f.seek(0) else: raise e diff --git a/chinaapi/qq/weibo/open.py b/chinaapi/qq/weibo/open.py index 250cb60..9c0816d 100644 --- a/chinaapi/qq/weibo/open.py +++ b/chinaapi/qq/weibo/open.py @@ -17,21 +17,21 @@ DEFAULT_IS_POST_METHOD = lambda m: False RET = { - 0: u'成功返回', - 1: u'参数错误', - 2: u'频率受限', - 3: u'鉴权失败', - 4: u'服务器内部错误', - 5: u'用户错误', - 6: u'未注册微博', - 7: u'未实名认证' + 0: '成功返回', + 1: '参数错误', + 2: '频率受限', + 3: '鉴权失败', + 4: '服务器内部错误', + 5: '用户错误', + 6: '未注册微博', + 7: '未实名认证' } def parse(response): r = response.json_dict() if 'ret' in r and r.ret != 0: - raise ApiResponseError(response, r.ret, RET.get(r.ret, u''), r.get('errcode', ''), r.get('msg', '')) + raise ApiResponseError(response, r.ret, RET.get(r.ret, ''), r.get('errcode', ''), r.get('msg', '')) if 'data' in r: return r.data return r diff --git a/chinaapi/renren/web.py b/chinaapi/renren/web.py index 9aaa40f..e9aa50d 100644 --- a/chinaapi/renren/web.py +++ b/chinaapi/renren/web.py @@ -9,7 +9,7 @@ class Client(ClientBase): @staticmethod def encrypt_password(e, m, s): def _encrypt_chunk(e, m, chunk): - chunk = map(ord, chunk) + chunk = list(map(ord, chunk)) # 补成偶数长度 if not len(chunk) % 2 == 0: @@ -68,8 +68,8 @@ def login(self, username, password): if self.get_show_captcha(username) == 1: fn = 'icode.%s.jpg' % os.getpid() self.get_icode(fn) - print "Please input the code in file '%s':" % fn - icode = raw_input().strip() + print("Please input the code in file '%s':" % fn) + icode = input().strip() os.remove(fn) else: icode = '' diff --git a/chinaapi/request.py b/chinaapi/request.py index 9ca07e5..26ff8e5 100644 --- a/chinaapi/request.py +++ b/chinaapi/request.py @@ -10,14 +10,14 @@ def json_dict(self): try: - return self.json(object_hook=lambda pairs: JsonDict(pairs.iteritems())) - except ValueError, e: + return self.json(object_hook=lambda pairs: JsonDict(iter(pairs.items()))) + except ValueError as e: try: self.raise_for_status() - except requests.RequestException, e: - raise ApiResponseError(self, message=u'%s, response: %s' % (e, self.text)) + except requests.RequestException as e: + raise ApiResponseError(self, message='%s, response: %s' % (e, self.text)) else: - raise ApiResponseError(self, e.__class__.__name__, u'%s, value: %s' % (e, self.text)) + raise ApiResponseError(self, e.__class__.__name__, '%s, value: %s' % (e, self.text)) def jsonp_dict(self): diff --git a/chinaapi/sina/weibo/open.py b/chinaapi/sina/weibo/open.py index 35505c2..96b2af7 100644 --- a/chinaapi/sina/weibo/open.py +++ b/chinaapi/sina/weibo/open.py @@ -113,7 +113,7 @@ def base64decode(s): sign = base64decode(encoded_sign) data = loads(base64decode(encoded_data)) token = Token(data.oauth_token, data.expires, uid=data.user_id, created_at=data.issued_at, **data) - is_valid = data.algorithm == u'HMAC-SHA256' and hmac.new(self.app.key, encoded_data, + is_valid = data.algorithm == 'HMAC-SHA256' and hmac.new(self.app.key, encoded_data, hashlib.sha256).digest() == sign return token, is_valid diff --git a/chinaapi/sina/weibo/web.py b/chinaapi/sina/weibo/web.py index 23459b1..2191282 100644 --- a/chinaapi/sina/weibo/web.py +++ b/chinaapi/sina/weibo/web.py @@ -2,7 +2,7 @@ from chinaapi.utils import parse_querystring from chinaapi.web import ClientBase from chinaapi.exceptions import ApiResponseError -import urllib +import urllib.request, urllib.parse, urllib.error import re import base64 import rsa @@ -35,7 +35,7 @@ def pre_login(self, su): return r.jsonp_dict() def login(self, username, password): - su = base64.b64encode(urllib.quote(username)) + su = base64.b64encode(urllib.parse.quote(username)) pre_data = self.pre_login(su) sp = self.encrypt_password(password, pre_data) data = { diff --git a/chinaapi/sohu/web.py b/chinaapi/sohu/web.py index 80f31b4..fb55475 100644 --- a/chinaapi/sohu/web.py +++ b/chinaapi/sohu/web.py @@ -5,7 +5,7 @@ import time ERROR = { - 'error3': u'用户名或密码错误', + 'error3': '用户名或密码错误', } diff --git a/chinaapi/taobao/open.py b/chinaapi/taobao/open.py index 0d1167d..2ac660e 100644 --- a/chinaapi/taobao/open.py +++ b/chinaapi/taobao/open.py @@ -3,7 +3,7 @@ import hmac from hashlib import md5 from datetime import datetime -from urllib import unquote +from urllib.parse import unquote from chinaapi.open import ClientBase, OAuthBase, OAuth2Base, App, Token from chinaapi.exceptions import ApiResponseError from chinaapi.utils import parse_querystring @@ -11,7 +11,7 @@ DEFAULT_VALUE_TO_STR = lambda x: str(x) VALUE_TO_STR = { type(datetime.now()): lambda v: v.strftime('%Y-%m-%d %H:%M:%S'), - type(u'a'): lambda v: v.encode('utf-8'), + type('a'): lambda v: v.encode('utf-8'), type(0.1): lambda v: "%.2f" % v, type(True): lambda v: str(v).lower(), } @@ -32,7 +32,7 @@ def join_dict(data): - return ''.join(["%s%s" % (k, v) for k, v in sorted(data.iteritems())]) + return ''.join(["%s%s" % (k, v) for k, v in sorted(data.items())]) class Client(ClientBase): @@ -70,7 +70,7 @@ def _prepare_body(self, queries): Return encoded data and files """ data, files = {}, {} - for k, v in queries.items(): + for k, v in list(queries.items()): kk = k.replace('__', '.') if hasattr(v, 'read'): files[kk] = v @@ -86,7 +86,7 @@ def _parse_response(self, response): raise ApiResponseError(response, error.get('code', ''), error.get('msg', ''), error.get('sub_code', ''), error.get('sub_msg', '')) else: - keys = r.keys() + keys = list(r.keys()) if keys and keys[0].endswith('_response'): return r.get(keys[0]) diff --git a/chinaapi/utils.py b/chinaapi/utils.py index 03544a0..3d3b10f 100644 --- a/chinaapi/utils.py +++ b/chinaapi/utils.py @@ -1,5 +1,5 @@ # coding=utf-8 -from urlparse import urlparse +from urllib.parse import urlparse from requests import PreparedRequest diff --git a/tests/decorator.py b/tests/decorator.py index 1638746..1e8fc1f 100644 --- a/tests/decorator.py +++ b/tests/decorator.py @@ -22,12 +22,12 @@ def inner_func(*args, **kw): if os.path.isabs(path): file_path = path else: - fun_path, fun_filename = os.path.split(func.func_code.co_filename) + fun_path, fun_filename = os.path.split(func.__code__.co_filename) file_path = os.path.join(fun_path, path, os.path.splitext(fun_filename)[0]) if not os.path.splitext(file_path)[1]: serializer = kwargs.get('serializer', vcr.serializer) - file_path = os.path.join(file_path, '{0}.{1}'.format(func.func_name.lower(), serializer)) + file_path = os.path.join(file_path, '{0}.{1}'.format(func.__name__.lower(), serializer)) with vcr.use_cassette(file_path, **kwargs): return func(*args, **kw) diff --git a/tests/test_decorators.py b/tests/test_decorators.py index fab5eb7..7543479 100644 --- a/tests/test_decorators.py +++ b/tests/test_decorators.py @@ -8,13 +8,13 @@ class DecoratorsTest(TestCase): @staticmethod def handle_error(exception): - print exception + print(exception) def test_retry(self): @retry(3, hook=self.handle_error) def retry_me(): self.n += 1 - raise Exception(u'exception in try %s' % self.n) + raise Exception('exception in try %s' % self.n) self.assertRaises(Exception, retry_me) self.assertEqual(self.n, 3) diff --git a/tests/test_open.py b/tests/test_open.py index 6083bc1..876834a 100644 --- a/tests/test_open.py +++ b/tests/test_open.py @@ -3,7 +3,7 @@ import httpretty from chinaapi.open import ClientBase, OAuth2Base, Method, Token, App from chinaapi.exceptions import MissingRedirectUri, ApiError -from test_request import BASE_URL, TestBase +from .test_request import BASE_URL, TestBase class ApiClient(ClientBase): diff --git a/tests/test_renren.py b/tests/test_renren.py index d46682f..9ebef58 100644 --- a/tests/test_renren.py +++ b/tests/test_renren.py @@ -23,4 +23,4 @@ def test_api_error(self): self.client.token.access_token = '' with self.assertRaises(ApiError) as cm: self.client.user.get(userId=self.uid) - self.assertEqual(u'验证参数错误。', cm.exception.message) + self.assertEqual('验证参数错误。', cm.exception.message)