【问题标题】:Flask + Cloud Datastore: Routes parameters capturing entity ids that have ancestral relationshipsFlask + Cloud Datastore:路由参数捕获具有祖先关系的实体 ID
【发布时间】:2020-03-12 00:26:56
【问题描述】:

Google Cloud Datastore 使用密钥来识别和查询Entities。这在查询实体时与 Flask.route 的 url 参数配合得很好:

from google.cloud import datastore
client = datastore.Client()

@app.route('/post/<post_id>', methods=['GET', 'POST'])
def post(post_id):
    post = client.get(client.key('Post', post_id)) 
    return client

但是,这仅在Post 键没有任何ancestors 时才有效:

Key('Post', 'post123')

但是如果Post 键实际上有ancestors,如下所示呢?

Key('User', 'user123', 'Post', 'post123')

这意味着烧瓶路由将不再处理/post/&lt;post_id&gt;,因为post_id 沿不代表整个实体。

这种情况有哪些可能的解决方案?

【问题讨论】:

    标签: flask google-cloud-firestore google-cloud-datastore


    【解决方案1】:

    与目录文件系统相同,实体在 Cloud Datastore 中是分层结构的。这种类型的结构在组织数据时非常整洁。

    来自Documentation

    标识实体的完整密钥由一系列种类标识符对组成,指定其祖先路径并以实体本身的路径终止:

    对象类别 -> 种类

    一个对象 -> 实体

    对象的个人数据 -> 属性

    对象的唯一 ID -> Key

    我相信您仍然可以使用相同的路线,但需要调整您的代码以首先使用其祖先路径查询您感兴趣的帖子 ID。

    这是我尝试过的工作代码,您可以对其进行修改以适应您的需要。

    from flask import Flask, render_template, redirect, request
    from google.cloud import datastore
    from markupsafe import escape
    
    # Starting Datastore Client.
    client = datastore.Client()
    
    # Home page will do a redirect to the specified URL.
    @app.route('/')
    def hello():
        return redirect('/post/<post_id>', code=302)
    
    # The URL that we are intestered in. 
    @app.route('/post/<post_id>', methods=['GET', 'POST'])
    def profile(post_id):
    
    # Query the post ID using its ancestors. 
    
    # Method is always 'GET' by default, I kept it 'GET' just for testing purposes.
    if request.method == 'GET' and request.url == '<post_id>':
        return '{} is the post ID'.format(escape(post_id))
    else:
        return '{} is the post ID'.format(escape(post_id))
    
    
    
    # The actual Flask app.
    app = Flask(__name__)
    
    if __name__ == '__main__':
        app.run(host='127.0.0.1', port=8080, debug=True)
    

    虽然我知道这可能不会给你一个直接的答案,但我相信它会为你指明正确的方向。

    【讨论】:

    • 仅给定子实体的,如何查询其祖先?这不是不可能的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多