2017-07-08 81 views
0

我有以下代码来列出Apache Cassandra数据库(Rest Api)的密钥空间。问题是使用2.0完成的Apache Cassandra数据库的代码版本。修复Cassandra Python RestApi

从schema_keyspaces在3.0版中不工作,选择keyspace_name如果我替换查询:SELECT * FROM,在3.0版本的作品system_schema.keyspaces我有以下错误:

from math import ceil 
class Pagination(object): 
def __init__(self, page, per_page, total_count): 
    self.page = page 
    self.per_page = per_page 
    self.total_count = total_count 

@property 
def pages(self): 
    return int(ceil(self.total_count/float(self.per_page))) 

@property 
def has_prev(self): 
    return self.page > 1 

@property 
def has_next(self): 
    return self.page < self.pages 

def iter_pages(self, left_edge=2, left_current=2, 
       right_current=5, right_edge=2): 
    last = 0 
    for num in xrange(1, self.pages + 1): 
     if num <= left_edge or \ 
      (num > self.page - left_current - 1 and \ 
      num < self.page + right_current) or \ 
      num > self.pages - right_edge: 
      if last + 1 != num: 
       yield None 
      yield num 
      last = num 
@app.route('/keyspaces/', defaults={'page': 1}, methods=['GET']) 
@app.route('/keyspaces/page/<int:page>', methods=['GET']) 
def getKeyspaces(page): 
auth_provider = PlainTextAuthProvider(username='admin', 
     password='root') 
cluster = Cluster(['hostname'], 
        auth_provider=auth_provider) 
session = cluster.connect() 
rows = session.execute('select keyspace_name from schema_keyspaces') 
keyspaces = [] 
for row in range(len(rows)): 
    keyspaces.append(rows[row][0]) 
    pages = keyspaces[(page - 1) * PER_PAGE:PER_PAGE * page] 
    if not pages and page != 1: 
     abort(404) 
     pagination = Pagination(page, PER_PAGE, len(rows)) 
     return render_template('listkeyspace.html', 
           pagination=pagination, pages=pages, 
           section='getKeyspaces') 

enter image description here

回答

1

根据docsResultSet是一个迭代器。如果你希望能够索引到结果,你首先需要迭代器转换为list,从而通过所有的结果迭代第一:

rows = session.execute('select keyspace_name from schema_keyspaces') 
row_list = list(rows) 
for row in range(len(row_list)): 
    ... 

,然后索引row_list,而不是rows整个身体你的循环

+0

当我按照你说的去做时,我又犯了一个错误: RuntimeError:迭代结果时不能使用索引运算符。 On keyspaces.append(rows [row] [0]) –

+0

Right。如上所述,您还需要在整个循环体中将'rows'的所有实例更改为'row_list'。所以'keyspaces.append(rows [row] [0])''应该成为'keyspaces.append(row_list [row] [0])' –

+0

好,它是行得通的,谢谢我的朋友;) –