【问题标题】:Reading & Writing JSON file on Google Cloud Storage using Python使用 Python 在 Google Cloud Storage 上读取和写入 JSON 文件
【发布时间】:2023-03-05 11:54:01
【问题描述】:

如前所述,我在 Cloud Storage 存储桶上有一个 JSON 文件,有没有办法通过 Python 读取(和修改)其内容?

@app.route("/myform/", methods=('GET', 'POST'))
def myform():
    form = MyForm()
    if form.validate_on_submit():
       return redirect('/')
    return render_template('my_form.html', form=form)

我想读取 Google Cloud Storage 上的 JSON 并向其中添加表单定义的值(键及其值)。

这一切都在标准 AppEngine 上运行的 Flask webapp 上。

【问题讨论】:

    标签: python json flask google-cloud-storage


    【解决方案1】:

    Google Cloud Platform (GCP) 有一个示例 Bookshelf tutorial,它展示了如何使用 Python 中的 Flask 框架在 Cloud Storage 上存储持久数据。以下是有关如何创建、读取、更新和删除 (CRUD) 存储在 Cloud Storage 中的数据的示例。

    创建:

    @crud.route('/add', methods=['GET', 'POST'])
    def add():
        if request.method == 'POST':
            data = request.form.to_dict(flat=True)
            book = get_model().create(data)
            return redirect(url_for('.view', id=book['id']))
        return render_template("form.html", action="Add", book={})
    

    阅读:

    @crud.route("/")
    def list():
        token = request.args.get('page_token', None)
        if token:
            token = token.encode('utf-8')
        books, next_page_token = get_model().list(cursor=token)
        return render_template(
            "list.html",
            books=books,
            next_page_token=next_page_token)
    

    更新:

    @crud.route('/<id>/edit', methods=['GET', 'POST'])
    def edit(id):
        book = get_model().read(id)
    if request.method == 'POST':
        data = request.form.to_dict(flat=True)
        book = get_model().update(data, id)
        return redirect(url_for('.view', id=book['id']))
    return render_template("form.html", action="Edit", book=book)
    

    删除:

    @crud.route('/<id>/delete')
    def delete(id):
        get_model().delete(id)
        return redirect(url_for('.list'))
    

    您可以找到有关 GCP JSON API 参考here 的更多详细信息。

    【讨论】:

    • 就 Google 示例应用程序而言,对此答案感到困惑 - 该示例仅将云存储用于图像等静态资产。 CRUD 操作是使用 Cloud Datastore 完成的,而不是 Cloud Storage cloud.google.com/python/getting-started/using-cloud-storage 我很确定您不能简单地将 JSON 文件用作 CRUD 数据存储,除非您使用某种数据库库 - 这称为“嵌入式数据库”。我玩过一个名为 JsonDb 的 Java 嵌入式 JSON 数据库,仍在寻找 Python 等价物; TinyDB 看起来很相似。
    猜你喜欢
    • 2015-04-09
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2019-11-17
    • 2020-05-05
    • 2013-01-26
    相关资源
    最近更新 更多