2013-07-02 162 views
-2

閱讀我有以下數據庫:無法從數據庫蟒蛇

{'numberOfExercises': {'quimica:D': 13, 'quimica:E': 12, 'quimica:B': 12, 'quimica:C': 12, 
'quimica:A': 14, 'aventura:A': 0}, 'topicDone': {u'quimica:A': 2}, 'exercisePoints': 
{u'quimica:A:1': 1.0, u'quimica:A:4': 1.0}, 'exerciseTotal': {u'quimica:A:1': 1, 
u'quimica:A:4': 1}, 'toSend': {u'quimica:A:1': u'send_data(quimica, A, 1, 1.0)', 
u'quimica:A:4': u'send_data(quimica, A, 4, 1.0)'}, 'areaPoints': {u'quimica': (2, 2.0)}, 
'stage': {'level': 2}, 'topicPoints': {u'quimica:A': (2, 2.0)}} 

我的信息擔心的是階段。

我這是怎麼保存:

def save_stage(value): 
    global stage 

    stage['level']= value 
    print stage 
    __save_data__() 

def __save_data__(): 
    global areaPoints 
    global topicPoints 
    global exercisePoints 
    global topicDone 
    global toSend 
    global numberOfExercises 
    global stage 

    f = open('database.json', 'w') 
    data = {'areaPoints': areaPoints, 'topicPoints': topicPoints, 
      'exerciseTotal': exerciseTotal, 'numberOfExercises': numberOfExercises, 
      'exercisePoints': exercisePoints, 'topicDone': topicDone, 
      'toSend': toSend, 'stage': stage} 
    f.write(repr(data)) 
    print data 
    f.close() 

,這是我如何得到它:

def get_stage(): 
    return stage.get("level",0) 

爲0作爲默認值。

的事情是,當我打電話時get_stage()我已經保存在數據庫中的東西(我最後一次執行我的程序),它總是返回0。但是,當我執行之後get_stage()save_stage()卻沒有這個問題從閱讀數據庫,任何想法?

def __load_data__(): 
    global areaPoints 
    global topicPoints 
    global exercisePoints 
    global exerciseTotal 
    global topicDone 
    global toSend 
    global numberOfExercises 
    global stage 

    try: 
     f = open("database.json") 
     data = f.read() 
     data = eval(data) 
     f.close() 
    except: 
     data = {} 

    stage = stage.get('stage', {}) 
    areaPoints = data.get('areaPoints', {}) 
    topicPoints = data.get('topicPoints', {}) 
    exercisePoints = data.get('exercisePoints', {}) 
    exerciseTotal = data.get('exerciseTotal', {}) 
    topicDone = data.get('topicDone', {}) 
    toSend = data.get('toSend', {}) 
    numberOfExercises = data.get('numberOfExercises', {}) 
+0

當然,我想要做的就是讓數據庫值每當我打電話'get_stage()',不僅在當前程序執行期間我已經保存了信息 – Malice

+0

當你完成程序的運行時,除非你堅持下去,否則一切都會消失(如果你幸運的話) – doctorlove

+0

我知道,我在「我有以下數據庫:」之後複製的代碼是我的database.json。該信息被保留,但不知何故未被讀取 – Malice

回答

0

你需要一些load_stage()函數從database.json讀取數據。並且您必須在某個文件中保存/讀取stage['level']值。

編輯:

stage = data.get('stage', {})代替stage = stage.get('stage', {})

data.get代替stage.get

+0

是不是我用__load_data __()?做的,除此之外,我已經在database.json中保存了th階段的值 – Malice

+0

看起來你加載了文件,但你沒有設置stage和stage ['level']或者你設置爲'stage = stage.get('stage',{}))'所以兩個都給你'stage ['level'] = 0'(默認值) – furas

+0

我不能跟着這個,你能否再解釋一下?我錯過了什麼? – Malice