2017-01-26 5 views
1

Ich habe Python-Programm, das versucht, mit Apache Cassandra mit Python-Cassandra-Treiber verbinden und einige Abfragen ausführen. Die Ergebnismenge, die ich zurückbekomme, ist entweder eine Liste oder ein Wörterbuch. Allerdings möchte ich die Ausgabe an den Benutzer in der nativen cql Ausgabeformat zu drucken zurück (als Spalten und Zeilen)Python Drucken CQL-Ausgabe im nativen Format

wie diese,

keyspace | durable_writes | name | strategy_class | strategy_options 
----------+----------------+---------+----------------+--------------------- ------- 
    history |   True | history | SimpleStrategy | {"replication_factor":"1"} 
    ks_info |   True | ks_info | SimpleStrategy |{"replication_factor":"1"} 

(2 rows) 

gibt es ein Modul ich dies zu erreichen, verwenden kann? Ich verwende den folgenden Code

from cassandra.cluster import Cluster 
from cassandra.auth import PlainTextAuthProvider 
from cassandra.query import dict_factory 

def fireCql(cqlStatement): 

auth_provider = PlainTextAuthProvider(
     username='myusername', password='myPassWord') 
cluster = Cluster(['cassandra.myhostname.com'],auth_provider=auth_provider) 

session = cluster.connect('my_keyspace') 
session.row_factory = dict_factory 

rows = session.execute(cqlStatement) 

return rows 

Python zu testen: 2.7

Antwort

0

Ich glaube nicht, das ist eine Funktion innerhalb des Python-Treiber selbst. Wenn Sie denken, dass viele Leute das wollen, können Sie es bei der Python-Treibergruppe anfordern.

Hier ist jedoch der Code, den Cassandra verwendet, um diese Formatierung zu generieren. Sie können dies als Basis verwenden, um die Logik zu implementieren, um das Ergebnis und das Format wie gewünscht zu parsen.

Von https://github.com/apache/cassandra/blob/b02dec3da539d181544cfb0288102d6073f36264/bin/cqlsh.py

def print_formatted_result(self, formatted_names, formatted_values): 
    # determine column widths 
    widths = [n.displaywidth for n in formatted_names] 
    if formatted_values is not None: 
     for fmtrow in formatted_values: 
      for num, col in enumerate(fmtrow): 
       widths[num] = max(widths[num], col.displaywidth) 

    # print header 
    header = ' | '.join(hdr.ljust(w, color=self.color) for (hdr, w) in zip(formatted_names, widths)) 
    self.writeresult(' ' + header.rstrip()) 
    self.writeresult('-%s-' % '-+-'.join('-' * w for w in widths)) 

    # stop if there are no rows 
    if formatted_values is None: 
     self.writeresult("") 
     return 

    # print row data 
    for row in formatted_values: 
     line = ' | '.join(col.rjust(w, color=self.color) for (col, w) in zip(row, widths)) 
     self.writeresult(' ' + line) 

    self.writeresult("")