Cassandra 與 JSON

調用情境回首頁


程式碼

#!/usr/bin/python
# -*- coding: utf-8 -*-

import json
from cassandra.cluster import Cluster


class FromDB:
    cassandraHost = ''
    casandraDbName = ''

    dbCluster = None
    dbSession = None

    dictProductInfoFromDB = dict()

    def __init__(self, cassandraHost, casandraDbName):
        self.cassandraHost = cassandraHost
        self.casandraDbName = casandraDbName

    def openDB(self):
        OK = True
        try:
            self.dbCluster = Cluster(contact_points=[self.cassandraHost])
            self.dbSession = self.dbCluster.connect(self.casandraDbName)
        except:
            self.dbCluster = None
            self.dbSession = None
            OK = False

        return OK

    def closeDB(self):
        if self.dbSession is not None:
            try:
                dbCluster.shutdown()
            except:
                pass

    def queryDB(self, productID):
        if self.dbSession is None:
            self.dictProductInfoFromDB.clear()
        else:
            try:
                dbStatement = \
                    self.dbSession.prepare('SELECT productName, productPrice FROM ProductInfo WHERE (productID = ?)'
                        )
                dbSQL = dbStatement.bind([productID])

                dbResultSet = self.dbSession.execute(dbSQL)
                for dbRow in dbResultSet:
                    self.dictProductInfoFromDB['productName'] = dbRow[0]
                    productPriceList = dbRow[1]
                    dictproductPrice = dict()
                    for productPriceCurrency in productPriceList:
                        dictproductPrice[productPriceCurrency] = \
                            productPriceList[productPriceCurrency]

                    self.dictProductInfoFromDB['productPrice'] = \
                        dictproductPrice
            except:
                pass

        return self.dictProductInfoFromDB


class FromOther:
    dictProductInfoFromOther = dict()

    def __init__(self):
        pass

    def query(self, productID):
        self.dictProductInfoFromOther = \
            {'productDescription': '''An interactive story for curious kids, budding scientists and history enthusiasts which talks about stones that once were dinosaur bones.

When dinosaurs thundered across the land, and enormous reptiles swam in the salty oceans, reptiles called Ornithocheirus, part of the Pterosaur family, ruled the ancient skies. Claire Ewart transports readers back to the age of the dinosaurs to take flight with a majestic Ornithocheirus that once soared through North American skies more than ninety million years ago, following it from sunup to sunup. When the Ornithocheirus finally lives out its natural life, layers of Earth and time work to transform this creature into a fossil - an amazing transformation that happens over millions of years.
Fossil is based on the book written and illustrated by Claire Ewart by the same name and is also a part of StoriesAlive subscription app.

> ENHANCE CREATIVITY BY PERSONALIZING THE STORY:
- You can write your own version of the text for the book
- Personalize the narration: kids or parents can record the narration to make it their own!

> DEVELOP READING SKILLS WITH THESE LITERACY TOOLS:
- Karaoke effect - when a word is spoken during narration, the word is highlighted.
- Touch a word to hear it being spoken in "Read Myself" mode (almost like "training wheels" for new readers)

> THREE WAYS TO READ THE BOOK:
1) "Read to me" - Listen to the narrated story while the text is displayed Karaoke style.
2) "Auto Play" - same as "Read to Me" except the page advances automatically once the narration is finished. 
Useful for those long car rides when you want the child to have a complete book experience. 3) "Read myself" - There is no narration but the child can touch a word to hear it being spoken aloud. Please rate and review the app. Your feedback means a lot to us! Stay in the loop: www.auryn.com Write to us: community@auryn.com Like us: Facebook.com/aurynapps Follow us: Twitter.com/aurynapps Follow us: Pinterest.com/appsbyauryn'''
} return self.dictProductInfoFromOther # Local Function def mergeDict(dictA, dictB): dictC = dictA.copy() dictC.update(dictB) return dictC productID = '0b786d40-8e73-4dd4-8840-82b3385e5b5a' dictProductInfoFromDB = dict() # Calling Cassandra myFromDB = FromDB(cassandraHost='localhost', casandraDbName='navipass') if myFromDB.openDB(): dictProductInfoFromDB = myFromDB.queryDB(productID) myFromDB.closeDB() # Calling Solr Maybe myFromOther = FromOther() dictProductInfoFromOther = myFromOther.query(productID) # Merge Two Dicts dictProductInfo = mergeDict(dictProductInfoFromDB, dictProductInfoFromOther) # Convert to JSON print json.dumps(dictProductInfo, sort_keys=True, indent=4, separators=(',', ': '))

輸出 JSON

{
"productDescription": "An interactive story for curious kids, budding scientists and history enthusiasts which talks about stones that once were dinosaur bones.\n\n When dinosaurs thundered across the land, and enormous reptiles swam in the salty oceans, reptiles called Ornithocheirus, part of the Pterosaur family, ruled the ancient skies.
Claire Ewart transports readers back to the age of the dinosaurs to take flight with a majestic Ornithocheirus that once soared through North American skies more than ninety million years ago, following it from sunup to sunup.
When the Ornithocheirus finally lives out its natural life, layers of Earth and time work to transform this creature into a fossil - an amazing transformation that happens over millions of years.\n
Fossil is based on the book written and illustrated by Claire Ewart by the same name and is also a part of StoriesAlive subscription app.\n\n>
 ENHANCE CREATIVITY BY PERSONALIZING THE STORY:\n
- You can write your own version of the text for the book\n- Personalize the narration: kids or parents can record the narration to make it their own!\n\n
> DEVELOP READING SKILLS WITH THESE LITERACY TOOLS:\n
- Karaoke effect - when a word is spoken during narration, the word is highlighted.\n- Touch a word to hear it being spoken in \"Read Myself\" mode (almost like \"training wheels\" for new readers)\n\n>
 THREE WAYS TO READ THE BOOK:\n1) \"Read to me\" - Listen to the narrated story while the text is displayed Karaoke style.\n2) \"Auto Play\" - same as \"Read to Me\" except the page advances automatically once the narration is finished.
Useful for those long car rides when you want the child to have a complete book experience.\n3) \"Read myself\" - There is no narration but the child can touch a word to hear it being spoken aloud.\n\n Please rate and review the app.
Your feedback means a lot to us!\nStay in the loop: www.auryn.com\nWrite to us: community@auryn.com\nLike us: Facebook.com/aurynapps\n
Follow us: Twitter.com/aurynapps\nFollow us: Pinterest.com/appsbyauryn",
"productName": "Fossil",
"productPrice": {
"NBC": 140,
"USD": 3.990000009536743
}
}
ċ
Cassandra-JSON.py
(5k)
李智,
2015年3月29日 下午10:40