如何在Go中使用GAE的数据存储(Datastore),当它最初是用Python创建的?

huangapple go评论93阅读模式
英文:

How to use datastore GAE in Go when initially it was created in Python?

问题

我有一个在Python中创建的数据存储类型为"Items"的数据存储。在这段代码中,不要在Go中迭代数据q.Run()(这是版本2):

type Items struct{
    code string
    date time.Time
    name string
}

func getcode(w http.ResponseWriter, r *http.Request) {
    code := mux.Vars(r)["code"]
    fmt.Fprintf(w,"get code %v",code)

    c := appengine.NewContext(r)
    q := datastore.NewQuery("Items")

    for t := q.Run(c); ; {
        var x Items
        key, err := t.Next(&x)
        fmt.Fprintf(w,"%v",key)

        if err == datastore.Done {
            break
        }
        if err != nil {
            //serveError(c, w, err)
            return
        }
        fmt.Fprintf(w, "Code=%v\n", x.code)
    }
}
英文:

I have a datastore kind "Items" which was created in Python, in this code do not iterate data q.Run() in Go (it's version 2):

type Items struct{
	code string
	date time.Time
	name string
}
func getcode(w http.ResponseWriter, r *http.Request) {
	code := mux.Vars(r)["code"]
	fmt.Fprintf(w,"get code %v",code)

	c := appengine.NewContext(r)
	q := datastore.NewQuery("Items")

	for t := q.Run(c); ; {
	    var x Items
	    key, err := t.Next(&x)
		fmt.Fprintf(w,"%v",key)

	    if err == datastore.Done {
	        break
	    }
	    if err != nil {
	        //serveError(c, w, err)
	        return
	    }
	    fmt.Fprintf(w, "Code=%v\n", x.code)
	}

答案1

得分: 3

Datastore包在从数据存储中读取实体时使用反射来填充结构字段。在Go语言中,以小写字母开头的结构字段是不可导出的。不可导出的字段不能从其他包中设置。

只有可导出的字段(以大写字母开头)才能存储在/从数据存储中检索出来。您可以使用标签来告诉数据存储中属性的名称,以防它与字段的名称不同。因此,您需要将Items结构更改为以下形式:

type Items struct {
    Code string    `datastore:"code"`
    Date time.Time `datastore:"date"`
    Name string    `datastore:"name"`
}
英文:

The Datastore package uses reflection to fill struct fields when reading an entity from the datastore. In Go struct fields whose name start with lowercase letter are not exported. Unexported fields cannot be set from packages other than the one they were defined in.

Only exported fields (that start with uppercase letters) can be stored in / retrieved from the datastore. You can use tags to tell what the name of the property is in the datastore in case it differs from the field's name. So you have to change your Items struct to this:

type Items struct {
    Code string    `datastore:"code"`
    Date time.Time `datastore:"date"`
    Name string    `datastore:"name"`
}

huangapple
  • 本文由 发表于 2015年9月3日 14:56:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/32368888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定