Skip to content

Commit 42423fc

Browse files
committed
Make examples runnable under both python2 and python3.
1 parent 99d047d commit 42423fc

File tree

8 files changed

+103
-81
lines changed

8 files changed

+103
-81
lines changed

examples/batch_get_row.py

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,25 @@
44
from tablestore import *
55
import time
66

7-
table_name = 'OTSBatchGetRowSimpleExample'
7+
table_name_1 = 'OTSBatchGetRowSimpleExample_1'
8+
table_name_2 = 'OTSBatchGetRowSimpleExample_2'
89

9-
def create_table(client):
10+
def create_table(client, table_name):
1011
schema_of_primary_key = [('gid', 'INTEGER'), ('uid', 'INTEGER')]
1112
table_meta = TableMeta(table_name, schema_of_primary_key)
1213
table_option = TableOptions()
1314
reserved_throughput = ReservedThroughput(CapacityUnit(0, 0))
1415
client.create_table(table_meta, table_option, reserved_throughput)
1516
print ('Table has been created.')
1617

17-
def delete_table(client):
18-
client.delete_table(table_name)
19-
print ('Table \'%s\' has been deleted.' % table_name)
18+
def delete_table(client, table_name):
19+
try:
20+
client.delete_table(table_name)
21+
print ('Table \'%s\' has been deleted.' % table_name)
22+
except:
23+
pass
2024

21-
def put_row(client):
25+
def put_row(client, table_name):
2226
for i in range(0, 10):
2327
primary_key = [('gid',i), ('uid',i+1)]
2428
attribute_columns = [('name','John'), ('mobile',i), ('address','China'), ('age',i)]
@@ -28,7 +32,7 @@ def put_row(client):
2832
print (u'Write succeed, consume %s write cu.' % consumed.write)
2933

3034
def batch_get_row(client):
31-
# try get 10 rows from exist table and 10 rows from not-exist table
35+
# try to get rows from two different tables
3236
columns_to_get = ['name', 'mobile', 'address', 'age']
3337
rows_to_get = []
3438
for i in range(0, 10):
@@ -40,17 +44,17 @@ def batch_get_row(client):
4044
cond.add_sub_condition(SingleColumnCondition("address", 'China', ComparatorType.EQUAL))
4145

4246
request = BatchGetRowRequest()
43-
request.add(TableInBatchGetRowItem(table_name, rows_to_get, columns_to_get, cond, 1))
44-
request.add(TableInBatchGetRowItem('notExistTable', rows_to_get, columns_to_get, cond, 1))
47+
request.add(TableInBatchGetRowItem(table_name_1, rows_to_get, columns_to_get, cond, 1))
48+
request.add(TableInBatchGetRowItem(table_name_2, rows_to_get, columns_to_get, cond, 1))
4549

4650
result = client.batch_get_row(request)
4751

4852
print ('Result status: %s'%(result.is_all_succeed()))
49-
50-
table_result_0 = result.get_result_by_table(table_name)
51-
table_result_1 = result.get_result_by_table('notExistTable')
5253

53-
print ('Check first table\'s result:')
54+
table_result_0 = result.get_result_by_table(table_name_1)
55+
table_result_1 = result.get_result_by_table(table_name_2)
56+
57+
print ('Check first table\'s result:')
5458
for item in table_result_0:
5559
if item.is_ok:
5660
print ('Read succeed, PrimaryKey: %s, Attributes: %s' % (item.row.primary_key, item.row.attribute_columns))
@@ -66,15 +70,16 @@ def batch_get_row(client):
6670

6771
if __name__ == '__main__':
6872
client = OTSClient(OTS_ENDPOINT, OTS_ID, OTS_SECRET, OTS_INSTANCE)
69-
try:
70-
delete_table(client)
71-
except:
72-
pass
73+
delete_table(client, table_name_1)
74+
delete_table(client, table_name_2)
7375

74-
create_table(client)
76+
create_table(client, table_name_1)
77+
create_table(client, table_name_2)
7578

7679
time.sleep(3) # wait for table ready
77-
put_row(client)
80+
put_row(client, table_name_1)
81+
put_row(client, table_name_2)
7882
batch_get_row(client)
79-
delete_table(client)
83+
delete_table(client, table_name_1)
84+
delete_table(client, table_name_2)
8085

examples/get_range.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,14 @@ def delete_table(client):
2020

2121
def put_row(client):
2222
for i in range(0, 100):
23-
primary_key = [('uid',i), ('gid', bytearray(str(i+1)))]
23+
primary_key = [('uid',i), ('gid', bytearray(str(i+1), 'utf-8'))]
2424
attribute_columns = [('name','John'), ('mobile',i), ('address','China'), ('age',i)]
2525
row = Row(primary_key, attribute_columns)
2626
condition = Condition(RowExistenceExpectation.IGNORE) # Expect not exist: put it into table only when this row is not exist.
2727
consumed, return_row = client.put_row(table_name, row, condition)
2828
print ('Write succeed, consume %s write cu.' % consumed.write)
2929

30-
def get_range(client):
30+
def get_range(client):
3131
'''
3232
Scan table to get all the rows.
3333
It will not return you all once, you should continue read from next start primary key till next start primary key is None.
@@ -42,10 +42,10 @@ def get_range(client):
4242
cond.add_sub_condition(SingleColumnCondition("age", 50, ComparatorType.LESS_THAN))
4343

4444
consumed, next_start_primary_key, row_list, next_token = client.get_range(
45-
table_name, Direction.FORWARD,
45+
table_name, Direction.FORWARD,
4646
inclusive_start_primary_key, exclusive_end_primary_key,
47-
columns_to_get,
48-
limit,
47+
columns_to_get,
48+
limit,
4949
column_filter = cond,
5050
max_version = 1
5151
)
@@ -55,9 +55,9 @@ def get_range(client):
5555
while next_start_primary_key is not None:
5656
inclusive_start_primary_key = next_start_primary_key
5757
consumed, next_start_primary_key, row_list, next_token = client.get_range(
58-
table_name, Direction.FORWARD,
58+
table_name, Direction.FORWARD,
5959
inclusive_start_primary_key, exclusive_end_primary_key,
60-
columns_to_get, limit,
60+
columns_to_get, limit,
6161
column_filter = cond,
6262
max_version = 1
6363
)
@@ -79,10 +79,10 @@ def xget_range(client):
7979
cond = CompositeColumnCondition(LogicalOperator.AND)
8080
cond.add_sub_condition(SingleColumnCondition("address", 'China', ComparatorType.EQUAL))
8181
cond.add_sub_condition(SingleColumnCondition("age", 50, ComparatorType.GREATER_EQUAL))
82-
82+
8383
columns_to_get = []
8484
range_iter = client.xget_range(
85-
table_name, Direction.FORWARD,
85+
table_name, Direction.FORWARD,
8686
inclusive_start_primary_key, exclusive_end_primary_key,
8787
consumed_counter, columns_to_get, 100,
8888
column_filter = cond, max_version = 1

examples/put_row.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def delete_table(client):
2323

2424
def put_row(client):
2525
primary_key = [('gid',1), ('uid',101)]
26-
attribute_columns = [('name','萧峰'), ('mobile',15100000000), ('address', bytearray('China')),
26+
attribute_columns = [('name','萧峰'), ('mobile',15100000000), ('address', bytearray('China', 'utf-8')),
2727
('female', False), ('age', 29.7)]
2828
row = Row(primary_key, attribute_columns)
2929

examples/search_index.py

Lines changed: 52 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,16 @@ def match_all_query(table_name, index_name):
2323
all_rows.extend(rows)
2424

2525
for row in all_rows:
26-
print row
26+
print(row)
2727

28-
print 'Total rows:', len(all_rows)
28+
print ('Total rows: %d' % len(all_rows))
2929

3030
def _print_rows(rows, total_count):
3131
for row in rows:
32-
print row
32+
print(row)
3333

34-
print 'Rows return:', len(rows)
35-
print 'Total count:', total_count
34+
print ('Rows return: %d' % len(rows))
35+
print ('Total count: %d' % total_count)
3636

3737
def match_query(table_name, index_name):
3838
query = MatchQuery('t', 'this is 0')
@@ -122,7 +122,7 @@ def bool_query(table_name, index_name):
122122
def geo_distance_query(table_name, index_name):
123123
query = GeoDistanceQuery('g', '32.5,116.5', 300000)
124124
sort = Sort(sorters=[
125-
GeoDistanceSort('g', ['32.5,116.5', '32.0,116.0'], sort_order=SortOrder.DESC, sort_mode=SortMode.MAX)
125+
GeoDistanceSort('g', ['32.5,116.5', '32.0,116.0'], sort_order=SortOrder.DESC)
126126
])
127127
rows, next_token, total_count, is_all_succeed = client.search(
128128
table_name, index_name, SearchQuery(query, limit=100, get_total_count=True, sort=sort), ColumnsToGet(return_type=ColumnReturnType.ALL)
@@ -171,6 +171,7 @@ def function_score_query(table_name, index_name):
171171
_print_rows(rows, total_count)
172172

173173
def prepare_data(rows_count):
174+
print ('Begin prepare data: %d' % rows_count)
174175
for i in range(rows_count):
175176
pk = [('PK1', i), ('PK2', 'pk_' + str(i % 10))]
176177
lj = i / 100
@@ -183,6 +184,8 @@ def prepare_data(rows_count):
183184

184185
client.put_row(table_name, Row(pk, cols))
185186

187+
print ('End prepare data.')
188+
186189
def prepare_table():
187190
table_meta = TableMeta(table_name, [('PK1', 'INTEGER'), ('PK2', 'STRING')])
188191

@@ -216,52 +219,64 @@ def prepare_index(index_name, with_nested=False):
216219

217220
def list_search_index():
218221
for table, index_name in client.list_search_index(table_name):
219-
print table, index_name
222+
print ('%s, %s' % (table, index_name))
220223

221224
def describe_search_index():
222225
index_meta, sync_stat = client.describe_search_index(table_name, index_name)
223-
print json.dumps(index_meta, default=lambda x:x.__dict__, indent=2)
224-
print json.dumps(sync_stat, default=lambda x:x.__dict__, indent=2)
226+
print ('sync stat: %s, %d' % (str(sync_stat.sync_phase), sync_stat.current_sync_timestamp))
227+
print ('index name: %s' % index_name)
228+
print ('index fields:')
229+
for field in index_meta.fields:
230+
print (' field name: %s' % field.field_name)
231+
print (' field type: %s' % str(field.field_type))
232+
print (' field indexed: %s' % str(field.index))
233+
print (' field stored: %s' % str(field.store))
234+
print (' field is array: %s' % str(field.is_array))
235+
print (' field allow sort and aggregate: %s' % str(field.enable_sort_and_agg))
236+
print ('index routing keys: %s' % str(index_meta.index_setting.routing_fields))
237+
print ('index sort: %s' % (index_meta.index_sort.sorters))
225238

226239
def delete_table():
227240
try:
228241
client.delete_table(table_name)
229-
except Exception,e:
230-
print e
242+
except:
243+
pass
231244

232245
def delete_search_index(index_name):
233246
try:
234247
client.delete_search_index(table_name, index_name)
235-
except Exception,e:
236-
print e
248+
except:
249+
pass
237250

238251
if __name__ == '__main__':
239252
client = OTSClient(OTS_ENDPOINT, OTS_ID, OTS_SECRET, OTS_INSTANCE)
240-
#delete_search_index(index_name)
241-
#delete_search_index(nested_index_name)
242-
#delete_table()
243-
244-
#prepare_table()
245-
#prepare_index(index_name, with_nested=False)
246-
#prepare_index(nested_index_name, with_nested=True)
247-
#prepare_data(1000)
253+
delete_search_index(index_name)
254+
delete_search_index(nested_index_name)
255+
delete_table()
248256

249-
#list_search_index()
250-
#describe_search_index()
257+
prepare_table()
258+
prepare_index(index_name, with_nested=False)
259+
prepare_index(nested_index_name, with_nested=True)
260+
prepare_data(1000)
261+
list_search_index()
262+
describe_search_index()
251263

252264
# perform queries
253-
#match_all_query(table_name, index_name)
265+
match_all_query(table_name, index_name)
254266
match_query(table_name, index_name)
255-
#match_phrase_query(table_name, index_name)
256-
#term_query(table_name, index_name)
257-
#range_query(table_name, index_name)
258-
#prefix_query(table_name, index_name)
259-
#terms_query(table_name, index_name)
260-
#bool_query(table_name, index_name)
261-
#wildcard_query(table_name, index_name)
262-
#geo_distance_query(table_name, index_name)
263-
#geo_bounding_box_query(table_name, index_name)
264-
#geo_polygon_query(table_name, index_name)
265-
#nested_query(table_name, nested_index_name)
266-
#function_score_query(table_name, nested_index_name)
267-
267+
match_phrase_query(table_name, index_name)
268+
term_query(table_name, index_name)
269+
range_query(table_name, index_name)
270+
prefix_query(table_name, index_name)
271+
terms_query(table_name, index_name)
272+
bool_query(table_name, index_name)
273+
wildcard_query(table_name, index_name)
274+
geo_distance_query(table_name, index_name)
275+
geo_bounding_box_query(table_name, index_name)
276+
geo_polygon_query(table_name, index_name)
277+
nested_query(table_name, nested_index_name)
278+
function_score_query(table_name, nested_index_name)
279+
280+
delete_search_index(index_name)
281+
delete_search_index(nested_index_name)
282+
delete_table()

examples/secondary_index_operations.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import json
77

88
table_name = 'SecondaryIndexOperationExample'
9+
index_name_1 = 'index1'
10+
index_name_2 = 'index2'
911

1012
def create_table(client):
1113
print ('Begin CreateTable')
@@ -15,14 +17,14 @@ def create_table(client):
1517
table_option = TableOptions(-1, 1)
1618
reserved_throughput = ReservedThroughput(CapacityUnit(0, 0))
1719
secondary_indexes = [
18-
SecondaryIndexMeta('index1', ['i', 's'], ['gid', 'uid', 'bool', 'b', 'd']),
20+
SecondaryIndexMeta(index_name_1, ['i', 's'], ['bool', 'b', 'd']),
1921
]
2022
client.create_table(table_meta, table_option, reserved_throughput, secondary_indexes)
2123
print ('Table has been created.')
2224

2325
def create_index(client):
2426
print ('Begin CreateIndex')
25-
index_meta = SecondaryIndexMeta('index2', ['i', 's'], ['gid', 'uid', 'bool', 'b', 'd'])
27+
index_meta = SecondaryIndexMeta(index_name_2, ['i', 's'], ['bool', 'b', 'd'])
2628
client.create_secondary_index(table_name, index_meta)
2729
print ('Index has been created.')
2830

@@ -40,12 +42,14 @@ def describe_table(client):
4042
print ('table options\'s max_time_deviation: %s' % describe_response.table_options.max_time_deviation)
4143
print ('Secondary indexes:')
4244
for secondary_index in describe_response.secondary_indexes:
43-
print (json.dumps(secondary_index, default=lambda x:x.__dict__, indent=2))
45+
print ('index name: %s' % secondary_index.index_name)
46+
print ('primary key names: %s' % str(secondary_index.primary_key_names))
47+
print ('defined column names: %s' % str(secondary_index.defined_column_names))
4448
print ('End DescribeTable')
4549

46-
def delete_index(client):
50+
def delete_index(client, index_name):
4751
print ('Begin DeleteIndex')
48-
client.delete_secondary_index(table_name, 'index1')
52+
client.delete_secondary_index(table_name, index_name)
4953
print ('End delete index.')
5054

5155
def delete_table(client):
@@ -57,7 +61,6 @@ def delete_table(client):
5761
client = OTSClient(OTS_ENDPOINT, OTS_ID, OTS_SECRET, OTS_INSTANCE)
5862
try:
5963
delete_table(client)
60-
print 'delete succeeded.'
6164
except:
6265
pass
6366

@@ -66,6 +69,8 @@ def delete_table(client):
6669
#time.sleep(3) # wait for table ready
6770
create_index(client)
6871
describe_table(client)
69-
delete_index(client)
72+
delete_index(client, index_name_1)
7073
describe_table(client)
74+
delete_index(client, index_name_2)
75+
delete_table(client)
7176

examples/table_operations.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def describe_table(client):
3636
print ('table options\'s max version: %s' % describe_response.table_options.max_version)
3737
print ('table options\'s max_time_deviation: %s' % describe_response.table_options.max_time_deviation)
3838
print ('End DescribeTable')
39-
39+
4040
def update_table(client):
4141
print ('Begin UpdateTable')
4242
table_option = TableOptions(100001, None, None)
@@ -59,7 +59,6 @@ def delete_table(client):
5959
client = OTSClient(OTS_ENDPOINT, OTS_ID, OTS_SECRET, OTS_INSTANCE)
6060
try:
6161
delete_table(client)
62-
print 'delete succeeded.'
6362
except:
6463
pass
6564

examples/update_row.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,20 +50,18 @@ def get_row(client):
5050

5151
if __name__ == '__main__':
5252
client = OTSClient(OTS_ENDPOINT, OTS_ID, OTS_SECRET, OTS_INSTANCE)
53-
'''
5453
try:
5554
delete_table(client)
5655
except:
5756
pass
5857
create_table(client)
59-
'''
6058

6159
#time.sleep(3) # wait for table ready
62-
#put_row(client)
60+
put_row(client)
6361
print ('#### row before update ####')
6462
get_row(client)
6563
update_row(client)
6664
print ('#### row after update ####')
6765
get_row(client)
68-
#delete_table(client)
66+
delete_table(client)
6967

0 commit comments

Comments
 (0)