Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion chinaapi/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions chinaapi/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand All @@ -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


Expand Down
2 changes: 1 addition & 1 deletion chinaapi/jsonDict.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ def loads(string):
>>> r['score']
95
"""
return json.loads(string, object_hook=lambda pairs: JsonDict(pairs.iteritems()))
return json.loads(string, object_hook=lambda pairs: JsonDict(iter(pairs.items())))
4 changes: 2 additions & 2 deletions chinaapi/open.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
18 changes: 9 additions & 9 deletions chinaapi/qq/weibo/open.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions chinaapi/renren/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 = ''
Expand Down
10 changes: 5 additions & 5 deletions chinaapi/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion chinaapi/sina/weibo/open.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions chinaapi/sina/weibo/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 = {
Expand Down
2 changes: 1 addition & 1 deletion chinaapi/sohu/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import time

ERROR = {
'error3': u'用户名或密码错误',
'error3': '用户名或密码错误',
}


Expand Down
10 changes: 5 additions & 5 deletions chinaapi/taobao/open.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
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

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(),
}
Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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])

Expand Down
2 changes: 1 addition & 1 deletion chinaapi/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# coding=utf-8
from urlparse import urlparse
from urllib.parse import urlparse
from requests import PreparedRequest


Expand Down
4 changes: 2 additions & 2 deletions tests/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_open.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_renren.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)