无法从数据库python中读取

时间:2013-07-02 15:30:51

标签: python database

我有以下数据库:

{'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)}}

我担心的信息是STAGE。

这是我保存它的方式:

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.但是当我执行save_stage()后跟get_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', {})

1 个答案:

答案 0 :(得分:0)

您需要一些load_stage()函数才能从database.json读取数据。您必须在某个文件中保存/读取stage['level']值。

修改

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

data.get代替stage.get