使用JSON作为Flask的数据存储?

2024-10-04 07:34:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题需要一些意见。我有一个小的JSON文件,我用它作为数据存储。在

{"stress": [1, "good"], "physical": [6, "ok"], "mood": [8, "good"], "perception": "neutral", "spoons": 74}

基本上我有一个webhook运行在一个pialexa服务上。整天都在更新这个数据存储。ie:如果你经历了一个意图,那么它会将压力更新为4。这不是一个应用程序。这是一个独立的安装,在本地运行,在一个房间里,根本不需要扩展。在

最好的办法是什么?我是否应该将这个JSON文件存储在根文件夹中,然后导入并写入?我应该看看像tinyDB这样的东西吗?我应该扔进烧瓶的静态文件夹吗?在

再说一次,超小的东西,不需要缩放。没有多个用户。我觉得像postgres或者一个完整的数据库是有点过分了。在


Tags: 文件数据文件夹jsonokwebhook意见good
1条回答
网友
1楼 · 发布于 2024-10-04 07:34:16

我也有类似的东西。。。它在实际的生产服务器上运行。但是用户永远不会超过100个。对于您的用例,这很好。在

在我的Flask路径上,我有两个简单的函数,它们读/写JSON数据存储。 我个人会在你的应用程序中创建一个名为“datastore”的单独文件夹,然后把它放在那里。下面是一个简单的例子:

def write_json(path, json_data):
    with open(path, 'w') as file_out:
        json.dump(json_data, file_out)


def read_json(path):
    with open(path) as file_in:
        return json.load(file_in)


# begin Flask views/routes
@app.route('/user_form', methods=['POST', 'GET'])
def user_form():
    path = "/home/myapp/datastore/store.json"


    # input from form or wherever your new JSON is coming from...
    # It could also be coming from a REST API etc:
    input = request.form['data']
    # {"new": "data"}


    # read in existing JSON
    existing_json = read_json(path)
    # {"existing": "json"}


    # add new JSON to existing JSON however you see fit
    [(k, v)] = input.items()
    existing_json[k] = v
    {"existing": "json", "new": "data"}


    # now update datastore
    write_json(path, existing_json)


    # could also be app.response or jsonify here etc...
    return render_template("success.html")

等等。。。在

只需将path变量设置为文件存储的位置。。。在

因此,一旦代码运行并且有了可以添加到数据存储区的值,就调用read函数,将新数据添加到JSON对象中,然后立即调用write函数将新更新的JSON重新写入到相同的文件中。在

相关问题 更多 >