英文:
GAE/Go: Namespace not working
问题
我正在尝试使用GAE/Go将数据存储记录存储在命名空间MyNameSpace
中,但是下面的代码不起作用。
import (
"cloud.google.com/go/datastore"
"github.com/gin-gonic/gin"
"google.golang.org/appengine"
)
func Save(c *gin.Context, list []MyStruct) ([]MyStruct, error) {
r := c.Request
ctx := appengine.NewContext(r)
ctx_with_namespace, err := appengine.Namespace(ctx, "MyNameSpace")
if err != nil {
return nil, err
}
client, err := datastore.NewClient(ctx_with_namespace, "MyProject")
if err != nil {
return nil, err
}
var keyList []*datastore.Key
for _, v := range list {
key := datastore.NameKey("MyStruct", v.ColA, nil)
keyList = append(keyList, key)
}
_, err = client.PutMulti(ctx_with_namespace, keyList, list)
return list,nil
}
这段代码在默认命名空间中创建记录,而不是MyNameSpace
。
cloud.google.com/go/datastore
是否忽略了命名空间设置?
英文:
I am trying to store datastore record in namespace MyNameSpace
with GAE/Go, but the code below not working.
import (
"cloud.google.com/go/datastore"
"github.com/gin-gonic/gin"
"google.golang.org/appengine"
)
func Save(c *gin.Context, list []MyStruct) ([]MyStruct, error) {
r := c.Request
ctx := appengine.NewContext(r)
ctx_with_namespace, err := appengine.Namespace(ctx, "MyNameSpace")
if err != nil {
return nil, err
}
client, err := datastore.NewClient(ctx_with_namespace, "MyProject")
if err != nil {
return nil, err
}
var keyList []*datastore.Key
for _, v := range list {
key := datastore.NameKey("MyStruct", v.ColA, nil)
keyList = append(keyList, key)
}
_, err = client.PutMulti(ctx_with_namespace, keyList, list)
return list,nil
}
This code creates records in the default namespace, not MyNameSpace
.
Does cloud.google.com/go/datastore
ignores namespace setting?
答案1
得分: 2
我找到了这个文档
> 2016年11月8日
>
> Datastore的重大变更:上下文不再持有命名空间,而是必须显式地设置键的命名空间。此外,键函数已经更改和重命名。
>
> WithNamespace函数已被移除。要在查询中指定命名空间,请使用Query.Namespace方法:
>
> q := datastore.NewQuery("Kind").Namespace("ns")
>
> Key的所有字段都是可导出的。这意味着你可以使用结构体字面量构造任何Key:
>
> k := &Key{Kind: "Kind", ID: 37, Namespace: "ns"}
我意识到我应该显式地设置命名空间,但这非常不方便。我已经迁移到使用google.golang.org/appengine/datastore
。
英文:
I found this document
> November 8, 2016
>
> Breaking changes to datastore: contexts no longer hold namespaces;
> instead you must set a key's namespace explicitly. Also, key functions
> have been changed and renamed.
>
> The WithNamespace function has been removed. To specify a namespace in
> a Query, use the Query.Namespace method:
>
> q := datastore.NewQuery("Kind").Namespace("ns")
>
> All the fields of Key are exported. That means you can construct any Key with a struct literal:
>
> k := &Key{Kind: "Kind", ID: 37, Namespace: "ns"}
I realized I should explicitly set namespace, but it is very inconvenient. I migrated to use google.golang.org/appengine/datastore
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论