>백엔드 개발 >Golang >Google App Engine의 Go Datastore에서 동적 속성을 구현하는 방법은 무엇입니까?

Google App Engine의 Go Datastore에서 동적 속성을 구현하는 방법은 무엇입니까?

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-11-26 05:57:10768검색

How to Implement Dynamic Properties in Google App Engine's Go Datastore?

Go에서 엔터티에 동적 속성 추가

Google App Engine 데이터 저장소에서는 엔터티의 속성을 동적으로 정의해야 하는 시나리오가 발생할 수 있습니다. 이 기사에서는 Go에서 동적 속성 처리를 달성하기 위해 Python의 Expando 모델과 유사한 기술을 살펴봅니다.

속성 로드 세이버 인터페이스

동적 속성을 생성하는 핵심은 PropertyLoadSaver 인터페이스에 있습니다. 이 인터페이스를 구현하면 저장 시 엔터티의 속성을 동적으로 구성할 수 있습니다.

PropertyList 유형

편리하게 Go AppEngine 플랫폼은 속성 개체의 일부인 PropertyList 유형을 제공합니다. PropertyLoadSaver도 구현합니다. Go에서 Expando 모델을 생성하려면 PropertyList 유형을 사용하면 됩니다. 여기에 원하는 속성을 추가할 수 있으며 이러한 속성은 엔터티의 일부로 저장됩니다.

package main

import (
    "context"
    "time"

    "google.golang.org/appengine/datastore"
)

func main() {
    ctx := context.Background()

    props := datastore.PropertyList{
        datastore.Property{Name: "time", Value: time.Now()},
        datastore.Property{Name: "email", Value: "example@email.com"},
    }

    k := datastore.NewIncompleteKey(ctx, "DynEntity", nil)
    key, err := datastore.Put(ctx, k, &props)
    if err != nil {
        // Handle error
    }

    c.Infof("%v", key)
}

이 예에서 "DynEntity"라는 엔터티는 두 개의 동적 속성인 "time" 및 "time"과 함께 저장됩니다. "email."

기본 지도 구현

지도와 같은 사용자 정의 유형을 사용하여 PropertyLoadSaver 인터페이스를 구현할 수도 있습니다. 다음 코드 조각은 지도를 래핑하는 DynEnt 유형을 생성하는 방법을 보여줍니다.

type DynEnt map[string]interface{}

func (d *DynEnt) Load(props []datastore.Property) error {
    for _, p := range props {
        (*d)[p.Name] = p.Value
    }
    return nil
}

func (d *DynEnt) Save() (props []datastore.Property, err error) {
    for k, v := range *d {
        props = append(props, datastore.Property{Name: k, Value: v})
    }
    return
}

이 사용자 정의 유형은 엔터티를 동적으로 로드하고 저장하는 데 사용할 수 있습니다.

d := DynEnt{"email": "example@email.com", "time": time.Now()}

k := datastore.NewIncompleteKey(ctx, "DynEntity", nil)
key, err := datastore.Put(ctx, k, &d)
if err != nil {
    // Handle error
}

c.Infof("%v", key)

이 접근 방식은 다음을 제공합니다. Google App Engine 데이터 저장소의 항목에 동적 속성을 추가하는 유연한 방법입니다.

위 내용은 Google App Engine의 Go Datastore에서 동적 속성을 구현하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.