Skip to content

Commit 421da58

Browse files
committed
Merge pull request #59 from shveenkov/for_python3.4_six
For python3.4 six
2 parents b0b99e1 + 22b87d6 commit 421da58

File tree

11 files changed

+70
-37
lines changed

11 files changed

+70
-37
lines changed

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
msgpack-python>=0.4.0
22
pyyaml>=3.10
3+
six

setup.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,5 +83,7 @@ def find_version(*file_paths):
8383
command_options=command_options,
8484
install_requires=[
8585
'msgpack-python>=0.4',
86+
'six',
87+
'PyYAML>=3.10',
8688
]
8789
)

tarantool/connection.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
This module provides low-level API for Tarantool
55
'''
66

7+
import six
78
import time
89
import errno
910
import ctypes
@@ -154,7 +155,7 @@ def connect(self):
154155
raise NetworkError(e)
155156

156157
def _recv(self, to_read):
157-
buf = ''
158+
buf = b""
158159
while to_read > 0:
159160
try:
160161
tmp = self._socket.recv(to_read)
@@ -188,7 +189,7 @@ def _send_request_wo_reconnect(self, request):
188189

189190
# Repeat request in a loop if the server returns completion_status == 1
190191
# (try again)
191-
for attempt in xrange(RETRY_MAX_ATTEMPTS): # pylint: disable=W0612
192+
for attempt in range(RETRY_MAX_ATTEMPTS): # pylint: disable=W0612
192193
self._socket.sendall(bytes(request))
193194
response = Response(self, self._read_response())
194195

@@ -328,7 +329,7 @@ def replace(self, space_name, values):
328329
329330
:rtype: `Response` instance
330331
'''
331-
if isinstance(space_name, basestring):
332+
if isinstance(space_name, six.string_types):
332333
space_name = self.schema.get_space(space_name).sid
333334
request = RequestReplace(self, space_name, values)
334335
return self._send_request(request)
@@ -377,7 +378,7 @@ def insert(self, space_name, values):
377378
378379
:rtype: `Response` instance
379380
'''
380-
if isinstance(space_name, basestring):
381+
if isinstance(space_name, six.string_types):
381382
space_name = self.schema.get_space(space_name).sid
382383
request = RequestInsert(self, space_name, values)
383384
return self._send_request(request)
@@ -397,9 +398,9 @@ def delete(self, space_name, key, **kwargs):
397398
index_name = kwargs.get("index", 0)
398399

399400
key = check_key(key)
400-
if isinstance(space_name, basestring):
401+
if isinstance(space_name, six.string_types):
401402
space_name = self.schema.get_space(space_name).sid
402-
if isinstance(index_name, basestring):
403+
if isinstance(index_name, six.string_types):
403404
index_name = self.schema.get_index(space_name, index_name).iid
404405
request = RequestDelete(self, space_name, index_name, key)
405406
return self._send_request(request)
@@ -427,9 +428,9 @@ def update(self, space_name, key, op_list, **kwargs):
427428
index_name = kwargs.get("index", 0)
428429

429430
key = check_key(key)
430-
if isinstance(space_name, basestring):
431+
if isinstance(space_name, six.string_types):
431432
space_name = self.schema.get_space(space_name).sid
432-
if isinstance(index_name, basestring):
433+
if isinstance(index_name, six.string_types):
433434
index_name = self.schema.get_index(space_name, index_name).iid
434435
request = RequestUpdate(self, space_name, index_name, key, op_list)
435436
return self._send_request(request)
@@ -503,9 +504,9 @@ def select(self, space_name, key=None, **kwargs):
503504
# tuples)
504505
key = check_key(key, select=True)
505506

506-
if isinstance(space_name, basestring):
507+
if isinstance(space_name, six.string_types):
507508
space_name = self.schema.get_space(space_name).sid
508-
if isinstance(index_name, basestring):
509+
if isinstance(index_name, six.string_types):
509510
index_name = self.schema.get_index(space_name, index_name).iid
510511
request = RequestSelect(self, space_name, index_name, key, offset,
511512
limit, iterator_type)

tarantool/error.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,12 @@
2424
import sys
2525
import warnings
2626

27-
28-
class Error(StandardError):
29-
30-
'''Base class for error exceptions'''
27+
try:
28+
class Error(StandardError):
29+
'''Base class for error exceptions'''
30+
except NameError:
31+
class Error(Exception):
32+
'''Base class for error exceptions'''
3133

3234

3335
class DatabaseError(Error):

tarantool/request.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
Request types definitions
55
'''
66

7+
import six
78
import msgpack
89
import hashlib
910

@@ -105,14 +106,18 @@ def __init__(self, conn, salt, user, password):
105106
super(RequestAuthenticate, self).__init__(conn)
106107

107108
def sha1(values):
108-
sha1 = hashlib.sha1()
109+
sha = hashlib.sha1()
109110
for i in values:
110-
sha1.update(i)
111-
return sha1.digest()
111+
if i is not None:
112+
sha.update(i if isinstance(i, six.binary_type) else i.encode())
113+
return sha.digest()
112114

113115
def strxor(rhs, lhs):
116+
if six.PY2:
114117
return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(rhs, lhs))
115118

119+
return bytes([x ^ y for x, y in zip(rhs, lhs)])
120+
116121
hash1 = sha1((password,))
117122
hash2 = sha1((hash1,))
118123
scramble = sha1((salt, hash2))

tarantool/response.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: utf-8 -*-
22
# pylint: disable=C0301,W0105,W0401,W0614
33

4+
import six
45
import sys
56
import msgpack
67
import yaml
@@ -41,7 +42,11 @@ def __init__(self, conn, response):
4142
# created in the __new__(). But let it be.
4243
super(Response, self).__init__()
4344

44-
unpacker = msgpack.Unpacker(use_list=True)
45+
if six.PY2:
46+
unpacker = msgpack.Unpacker(use_list=True)
47+
else:
48+
unpacker = msgpack.Unpacker(use_list=True, encoding="utf-8")
49+
4550
unpacker.feed(response)
4651
header = unpacker.unpack()
4752

tarantool/schema.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
It is a Tarantool schema description.
66
'''
77

8+
import six
9+
810
from tarantool.error import SchemaError
911
import tarantool.const as const
1012

@@ -16,7 +18,7 @@ def __init__(self, array, space):
1618
self.index = array[3]
1719
self.unique = array[4]
1820
self.parts = []
19-
for i in xrange(array[5]):
21+
for i in range(array[5]):
2022
self.parts.append((array[5 + 1 + i * 2], array[5 + 2 + i * 2]))
2123
self.space = space
2224
self.space.indexes[self.iid] = self
@@ -57,14 +59,14 @@ def get_space(self, space):
5759
except KeyError:
5860
pass
5961
_index = (const.INDEX_SPACE_NAME
60-
if isinstance(space, basestring)
62+
if isinstance(space, six.string_types)
6163
else const.INDEX_SPACE_PRIMARY)
6264

6365
array = self.con.select(const.SPACE_SPACE, space, index=_index)
6466
if len(array) > 1:
6567
raise SchemaError('Some strange output from server: \n' + array)
6668
elif len(array) == 0 or not len(array[0]):
67-
temp_name = ('name' if isinstance(space, basestring) else 'id')
69+
temp_name = ('name' if isinstance(space, six.string_types) else 'id')
6870
raise SchemaError(
6971
"There's no space with {1} '{0}'".format(space, temp_name))
7072
array = array[0]
@@ -77,15 +79,15 @@ def get_index(self, space, index):
7779
except KeyError:
7880
pass
7981
_index = (const.INDEX_INDEX_NAME
80-
if isinstance(index, basestring)
82+
if isinstance(index, six.string_types)
8183
else const.INDEX_INDEX_PRIMARY)
8284

8385
array = self.con.select(const.SPACE_INDEX, [_space.sid, index],
8486
index=_index)
8587
if len(array) > 1:
8688
raise SchemaError('Some strange output from server: \n' + array)
8789
elif len(array) == 0 or not len(array[0]):
88-
temp_name = ('name' if isinstance(index, basestring) else 'id')
90+
temp_name = ('name' if isinstance(index, six.string_types) else 'id')
8991
raise SchemaError(
9092
"There's no index with {2} '{0}' in space '{1}'".format(
9193
index, _space.name, temp_name))

tarantool/utils.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import six
4+
15
def check_key(*args, **kwargs):
26
if 'first' not in kwargs:
37
kwargs['first'] = True
@@ -12,5 +16,5 @@ def check_key(*args, **kwargs):
1216
elif args[0] is None and kwargs['select']:
1317
return []
1418
for key in args:
15-
assert isinstance(key, (int, long, basestring))
19+
assert isinstance(key, six.integer_types + six.string_types)
1620
return list(args)

tests/suites/lib/tarantool_server.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
# -*- coding: utf-8 -*-
2+
13
import os
4+
import os.path
25
import errno
36
import shlex
47
import random
@@ -39,6 +42,7 @@ def __init__(self, host, port):
3942
self.port = port
4043
self.is_connected = False
4144
self.socket = None
45+
4246
def connect(self):
4347
self.socket = socket.create_connection((self.host, self.port))
4448
self.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
@@ -87,7 +91,7 @@ def execute_no_reconnect(self, command):
8791
if not command:
8892
return
8993
cmd = command.replace('\n', ' ') + '\n'
90-
self.socket.sendall(cmd)
94+
self.socket.sendall(cmd.encode())
9195

9296
bufsiz = 4096
9397
res = ""
@@ -96,7 +100,7 @@ def execute_no_reconnect(self, command):
96100
buf = self.socket.recv(bufsiz)
97101
if not buf:
98102
break
99-
res = res + buf
103+
res = res + buf.decode()
100104
if (res.rfind("\n...\n") >= 0 or res.rfind("\r\n...\r\n") >= 0):
101105
break
102106

@@ -134,6 +138,7 @@ def script_dst(self):
134138
def script(self):
135139
if not hasattr(self, '_script'): self._script = None
136140
return self._script
141+
137142
@script.setter
138143
def script(self, val):
139144
if val is None:
@@ -153,6 +158,7 @@ def _admin(self):
153158
if not hasattr(self, 'admin'):
154159
self.admin = None
155160
return self.admin
161+
156162
@_admin.setter
157163
def _admin(self, port):
158164
try:
@@ -168,6 +174,7 @@ def log_des(self):
168174
if not hasattr(self, '_log_des'):
169175
self._log_des = open(self.logfile_path, 'a')
170176
return self._log_des
177+
171178
@log_des.deleter
172179
def log_des(self):
173180
if not hasattr(self, '_log_des'):
@@ -193,7 +200,7 @@ def find_exe(self):
193200
exe = os.path.join(_dir, self.default_tarantool["bin"])
194201
if os.access(exe, os.X_OK):
195202
return os.path.abspath(exe)
196-
raise RuntimeError("Can't find server executable in " + path)
203+
raise RuntimeError("Can't find server executable in " + os.environ["PATH"])
197204

198205
def generate_configuration(self):
199206
os.putenv("PRIMARY_PORT", str(self.args['primary']))
@@ -240,7 +247,7 @@ def start(self):
240247
self.generate_configuration()
241248
if self.script:
242249
shutil.copy(self.script, self.script_dst)
243-
os.chmod(self.script_dst, 0777)
250+
os.chmod(self.script_dst, 0o777)
244251
args = self.prepare_args()
245252
self.process = subprocess.Popen(args,
246253
cwd = self.vardir,
@@ -249,15 +256,17 @@ def start(self):
249256
self.wait_until_started()
250257

251258
def stop(self):
252-
self.process.terminate()
253-
self.process.wait()
259+
if self.process.poll() is None:
260+
self.process.terminate()
261+
self.process.wait()
254262

255263
def restart(self):
256264
self.stop()
257265
self.start()
258266

259267
def clean(self):
260-
shutil.rmtree(self.vardir)
268+
if os.path.isdir(self.vardir):
269+
shutil.rmtree(self.vardir)
261270

262271
def __del__(self):
263272
self.stop()

tests/suites/test_dml.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# -*- coding: utf-8 -*-
2+
3+
import six
24
import yaml
35
import unittest
46
import tarantool
@@ -7,8 +9,8 @@
79
class Request(unittest.TestCase):
810
@classmethod
911
def setUpClass(self):
10-
print ' DML '.center(70, '=')
11-
print '-' * 70
12+
print(' DML '.center(70, '='))
13+
print('-' * 70)
1214
self.srv = TarantoolServer()
1315
self.srv.script = 'tests/suites/box.lua'
1416
self.srv.start()
@@ -32,7 +34,7 @@ def test_00_01_space_created(self):
3234

3335
def test_00_02_fill_space(self):
3436
# Fill space with values
35-
for i in xrange(1, 500):
37+
for i in range(1, 500):
3638
self.assertEqual(
3739
self.con.insert('space_1', [i, i%5, 'tuple_'+str(i)])[0],
3840
[i, i%5, 'tuple_'+str(i)]
@@ -145,7 +147,7 @@ def test_07_call(self):
145147
ans = self.con.call('fiber.time64')
146148
self.assertEqual(len(ans), 1)
147149
self.assertEqual(len(ans[0]), 1)
148-
self.assertIsInstance(ans[0][0], (int, long))
150+
self.assertIsInstance(ans[0][0], six.integer_types)
149151
ans = self.con.call('uuid.str')
150152
self.assertEqual(len(ans), 1)
151153
self.assertEqual(len(ans[0]), 1)

0 commit comments

Comments
 (0)