hm_patmol
hm_patmol

Reputation: 79

Fix Cassandra Python RestApi

I have the following code to list the keyspaces of the Apache Cassandra database (Rest Api). The problem is the code version of the Apache Cassandra database that was done with the 2.0.

Select keyspace_name from schema_keyspaces does not work in version 3.0 and if I replace the query with: SELECT * FROM system_schema.keyspaces that works in version 3.0 I have the following error:

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

Upvotes: 0

Views: 404

Answers (1)

Daniel Corin
Daniel Corin

Reputation: 2067

According to the docs, ResultSet is an iterator. If you want to be able to index into the results, you will first need to convert the iterator into a list, thus iterating through all the results first:

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

and then index into row_list rather than rows throughout the body of your loop

Upvotes: 1

Related Questions