Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用JSON作为Flask的数据存储?_Python_Json_Flask - Fatal编程技术网

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

Python 使用JSON作为Flask的数据存储?,python,json,flask,Python,Json,Flask,我有一个问题需要一些意见。我有一个小的JSON文件,我正在使用它作为数据存储 {"stress": [1, "good"], "physical": [6, "ok"], "mood": [8, "good"], "perception": "neutral", "spoons": 74} 基本上,对于alexa服务,我有一个webhook在pi上运行。并且在这一天中,数据存储都在更新。ie:如果你通过一个意图,那么它会将压力更新为4。这不是一个应用程序。这是一个独立的安装件,在本地、在房间中

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

{"stress": [1, "good"], "physical": [6, "ok"], "mood": [8, "good"], "perception": "neutral", "spoons": 74}
基本上,对于alexa服务,我有一个webhook在pi上运行。并且在这一天中,数据存储都在更新。ie:如果你通过一个意图,那么它会将压力更新为4。这不是一个应用程序。这是一个独立的安装件,在本地、在房间中运行,根本不需要扩展

最好的方法是什么?我是否应该将这个JSON文件存储在根文件夹中,然后将其导入并写出?我应该看看tinyDB之类的东西吗?我应该扔进Flask的静态文件夹吗


同样,超小的东西,不需要缩放。没有多个用户。我觉得像postgres或是一个完整的db有些过分了

我也有类似的想法。。。它在实际的生产服务器上运行。然而,用户从来不会超过100人。对于您的用例来说,这很好

在我的Flask路由之上,我有两个简单的函数从JSON数据存储读取/写入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重新写入到同一文件中