本文整理汇总了Golang中google/golang.org/appengine/datastore.Get函数的典型用法代码示例。如果您正苦于以下问题:Golang Get函数的具体用法?Golang Get怎么用?Golang Get使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Get函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestStoreUser
// Should store the given user, after encrypting its password
func TestStoreUser(t *testing.T) {
ctx, done, err := aetest.NewContext()
if err != nil {
t.Fatal(err)
}
defer done()
user := &models.User{Username: "testertim", FirstName: "Tim", Email: "[email protected]", Password: []byte("I <3 golang")}
err = repositories.StoreUser(ctx, user)
if err != nil {
t.Fatal(err)
}
key := datastore.NewKey(ctx, "User", "testertim", 0, nil)
var storedUser models.User
err = datastore.Get(ctx, key, &storedUser)
if err != nil {
t.Fatal(err)
}
if storedUser.FirstName != user.FirstName {
t.Errorf("FirstName %d, want %d", storedUser.FirstName, user.FirstName)
}
if storedUser.Username != "" {
t.Errorf("Username %d should be derived from the key, not stored", storedUser.Username)
}
if string(storedUser.Password) == "I <3 golang" {
t.Errorf("Password %d should be hashed and not %d", string(storedUser.Password), "I <3 golang")
}
}
示例2: GetCompanyByUser
func GetCompanyByUser(ctx context.Context, w http.ResponseWriter, r *http.Request) (int, error) {
if r.Method != "GET" {
return http.StatusMethodNotAllowed, nil
}
p, ok := passenger.FromContext(ctx)
if !ok {
return http.StatusUnauthorized, nil
}
var u model.User
if err := datastore.Get(ctx, p.User, &u); err != nil {
return http.StatusInternalServerError, nil
}
if u.Company == nil {
return http.StatusUnauthorized, nil
}
// The account is associated with a company, so we return it.
var company model.Company
if err := datastore.Get(ctx, u.Company, &company); err != nil {
return http.StatusInternalServerError, err
}
json.NewEncoder(w).Encode(company.Key(u.Company))
return http.StatusOK, nil
}
示例3: Increment
// Increment increments the named counter.
func Increment(ctx context.Context, name string) error {
// Get counter config.
var cfg counterConfig
ckey := datastore.NewKey(ctx, configKind, name, 0, nil)
err := datastore.RunInTransaction(ctx, func(ctx context.Context) error {
err := datastore.Get(ctx, ckey, &cfg)
if err == datastore.ErrNoSuchEntity {
cfg.Shards = defaultShards
_, err = datastore.Put(ctx, ckey, &cfg)
}
return err
}, nil)
if err != nil {
return err
}
var s shard
err = datastore.RunInTransaction(ctx, func(ctx context.Context) error {
shardName := fmt.Sprintf("%s-shard%d", name, rand.Intn(cfg.Shards))
key := datastore.NewKey(ctx, shardKind, shardName, 0, nil)
err := datastore.Get(ctx, key, &s)
// A missing entity and a present entity will both work.
if err != nil && err != datastore.ErrNoSuchEntity {
return err
}
s.Name = name
s.Count++
_, err = datastore.Put(ctx, key, &s)
return err
}, nil)
if err != nil {
return err
}
memcache.IncrementExisting(ctx, memcacheKey(name), 1)
return nil
}
示例4: viewStory
func viewStory(res http.ResponseWriter, req *http.Request, ps httprouter.Params) {
ctx := appengine.NewContext(req)
sd := sessionInfo(req)
link := ps.ByName("story")
title := strings.Replace(link, "-", " ", -1) //translate link to title
owner := ps.ByName("owner")
userkey := datastore.NewKey(ctx, "Users", owner, 0, nil)
key := datastore.NewKey(ctx, "Stories", title, 0, userkey) //owner is ancestor - eliminates need for owner-story table
var story Story
err := datastore.Get(ctx, key, &story)
if err != nil {
panic(err)
}
var user User
user.Username = owner
err = datastore.Get(ctx, userkey, &user)
if err != nil {
panic(err)
}
sd.ViewingStory = story
sd.ViewingUser = user
tpl.ExecuteTemplate(res, "view.html", &sd)
}
示例5: Increment
// Increment increments the named counter.
func Increment(c context.Context, valName string) error {
// Get counter config.
shardsTotal := dsu.WrapInt{}
dsu.McacheGet(c, mcKeyShardsTotal(valName), &shardsTotal)
if shardsTotal.I < 1 {
ckey := datastore.NewKey(c, dsKindNumShards, mcKeyShardsTotal(valName), 0, nil)
errTx := datastore.RunInTransaction(c,
func(c context.Context) error {
err := datastore.Get(c, ckey, &shardsTotal)
if err == datastore.ErrNoSuchEntity {
shardsTotal.I = defaultNumShards
_, err = datastore.Put(c, ckey, &shardsTotal)
}
return err
}, nil)
if errTx != nil {
return errTx
}
dsu.McacheSet(c, mcKeyShardsTotal(valName), dsu.WrapInt{shardsTotal.I})
}
// pick random counter and increment it
errTx := datastore.RunInTransaction(c,
func(c context.Context) error {
shardId := rand.Intn(shardsTotal.I)
dsKey := datastore.NewKey(c, dsKindShard, keySingleShard(valName, shardId), 0, nil)
var sd WrapShardData
err := datastore.Get(c, dsKey, &sd)
// A missing entity and a present entity will both work.
if err != nil && err != datastore.ErrNoSuchEntity {
return err
}
sd.Name = valName
sd.ShardId = shardId
sd.I++
_, err = datastore.Put(c, dsKey, &sd)
if ll > 2 {
aelog.Infof(c, "ds put %v %v", dsKey, sd)
}
return err
}, nil)
if errTx != nil {
return errTx
}
memcache.Increment(c, mcKey(valName), 1, 0)
// collect number of updates
// per valName per instance in memory
// for every interval of 10 minutes
//
// a batch job checks if the number of shards should be increased or decreased
// and truncates this map
updateSamplingFrequency[valName+util.TimeMarker()[:len("2006-01-02 15:0")]] += 1
return nil
}
示例6: Load
// Load - Takes a datastore.Key provided and loads it into the current Ticket object
func (t *Ticket) Load(ctx context.Context, k datastore.Key) error {
err := datastore.Get(ctx, &k, t)
t.DatastoreKey = k
t.EventKey = k.Parent()
if err = datastore.Get(ctx, &k, t); err != nil {
return err
}
return nil
}
示例7: TestDatastoreFixture
func TestDatastoreFixture(t *testing.T) {
filepath := mkTempfile(`[{
"_kind": "FixtureKind",
"_key": "key1",
"IntValue": 10,
"FloatValue": 2.4,
"BoolValue": true,
"StringValue": "foobar",
"BytesValue": "[]bytesfoobar",
"DateTimeValue": "2014-01-02T14:02:50Z",
"DateValue": "2014-01-02",
"Slice": ["a", "b", "c"],
"Struct": {
"Foo": "bar"
}
},{
"_kind": "FixtureKind",
"_key": "key1",
"_ns": "ns1",
"StringValue": "withns1"
}
]`)
assert := wcg.NewAssert(t)
var fk FixtureKind
assert.Nil(DatastoreFixture(ts.Context, filepath, nil), "DatastoreFixture")
key := datastore.NewKey(ts.Context, "FixtureKind", "key1", 0, nil)
wcg.NewLogger(nil).Infof("GET: %s", key)
assert.Nil(datastore.Get(ts.Context, key, &fk), "datastore.Get('key1') ")
assert.EqInt(10, fk.IntValue, "IntValue should be 10")
assert.EqFloat32(2.4, fk.FloatValue, "FloatValue should be 2.4")
assert.EqStr("foobar", fk.StringValue, "StringValue should be 'foobar'")
assert.EqStr("bytesfoobar", string(fk.BytesValue), "BytesValue should be 'foobar'")
assert.EqInt(3, len(fk.Slice), "len(Slice) should be 3")
assert.EqStr("a", string(fk.Slice[0]), "Slice[0] should be 'a'")
assert.EqStr("b", string(fk.Slice[1]), "Slice[0] should be 'a'")
assert.EqStr("c", string(fk.Slice[2]), "Slice[0] should be 'a'")
assert.EqTime(time.Date(2014, 01, 02, 14, 02, 50, 0, time.UTC), fk.DateTimeValue, "DateTimeValue should be 2014-01-02T14:02:50Z")
assert.EqTime(time.Date(2014, 01, 02, 0, 0, 0, 0, time.UTC), fk.DateValue, "DateTimeValue should be 2014-01-02T00:00:00Z")
assert.EqStr("bar", string(fk.Struct.Foo), "Struct.Foo should be 'bar'")
// namespace
ns1, _ := appengine.Namespace(ts.Context, "ns1")
key = datastore.NewKey(ns1, "FixtureKind", "key1", 0, nil)
assert.Nil(datastore.Get(ns1, key, &fk), "datastore.Get('key1') /w ns1")
assert.EqStr("withns1", fk.StringValue, "StringValue should be 'withns1'")
}
示例8: LoadAccess
//LoadAccess loads access data by token
func (s *AEStorage) LoadAccess(c context.Context, code string) (*osin.AccessData, error) {
log.Infof(c, "Access code: %s", code)
key := datastore.NewKey(c, AccessDataKind, code, 0, nil)
var token AccessDataModel
err := datastore.Get(c, key, &token)
if err != nil {
return nil, errors.New("Access not found")
}
var rtoken = token.ToAccessData()
client, err := s.GetClient(c, token.ClientID)
if client == nil || err != nil {
return nil, errors.New("Client not found")
}
rtoken.Client = client
if token.AuthorizationCode != "" {
auth, err := s.LoadAuthorize(c, token.AuthorizationCode)
if auth == nil || err != nil {
return nil, errors.New("Authorization not found")
}
rtoken.AuthorizeData = auth
}
return rtoken, nil
}
示例9: ByID
func (s *TaskService) ByID(ctx context.Context, id string) (*Task, error) {
rootKey := datastore.NewKey(ctx, "Root", "root", 0, nil)
k := datastore.NewKey(ctx, "Task", id, 0, rootKey)
ct, ok := CacheFromContext(ctx).Get(k).(*Task)
if ok {
return ct, nil
}
span := trace.FromContext(ctx).NewChild("trythings.task.ByID")
defer span.Finish()
var t Task
err := datastore.Get(ctx, k, &t)
if err != nil {
return nil, err
}
ok, err = s.IsVisible(ctx, &t)
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("cannot access task")
}
CacheFromContext(ctx).Set(k, &t)
return &t, nil
}
示例10: ByID
func (s *ViewService) ByID(ctx context.Context, id string) (*View, error) {
rootKey := datastore.NewKey(ctx, "Root", "root", 0, nil)
k := datastore.NewKey(ctx, "View", id, 0, rootKey)
cv, ok := CacheFromContext(ctx).Get(k).(*View)
if ok {
return cv, nil
}
span := trace.FromContext(ctx).NewChild("trythings.view.ByID")
defer span.Finish()
var v View
err := datastore.Get(ctx, k, &v)
if err != nil {
return nil, err
}
ok, err = s.IsVisible(ctx, &v)
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("cannot access view")
}
CacheFromContext(ctx).Set(k, &v)
return &v, nil
}
示例11: showUser
func showUser(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
u := user.Current(ctx)
email := u.Email
key := datastore.NewKey(ctx, "User", email, 0, nil)
var entity User
err := datastore.Get(ctx, key, &entity)
if err == datastore.ErrNoSuchEntity {
http.NotFound(res, req)
return
} else if err != nil {
http.Error(res, err.Error(), 500)
return
}
log.Infof(ctx, "%v", entity)
res.Header().Set("Content-Type", "text/html")
fmt.Fprintln(res, `
<dl>
<dt>`+entity.FirstName+`</dt>
<dd>`+entity.LastName+`</dd>
<dd>`+u.Email+`</dd>
</dl>
`)
}
示例12: Tasks
func Tasks(ctx context.Context, w http.ResponseWriter, r *http.Request) (status int, err error) {
p, ok := passenger.FromContext(ctx)
if !ok {
return http.StatusUnauthorized, nil
}
var u model.User
if err = datastore.Get(ctx, p.User, &u); err != nil {
return http.StatusInternalServerError, err
}
// User is a coder
if u.Company == nil {
return http.StatusUnauthorized, nil
}
switch r.Method {
case "GET":
return getAllTasks(ctx, w, r)
case "POST":
return createTask(ctx, w, r)
default:
return http.StatusMethodNotAllowed, nil
}
}
示例13: handlePersonalPage
func handlePersonalPage(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
session := getSession(ctx, req)
username := strings.SplitN(req.URL.Path, "/", 3)[2]
if username == "" {
http.Redirect(res, req, "/userslist", 302)
return
}
q := datastore.NewQuery("Image").Filter("Username =", username)
var images []Image
q.GetAll(ctx, &images)
key := datastore.NewKey(ctx, "List", username, 0, nil)
var list List
datastore.Get(ctx, key, &list)
listItems := make([]string, 0)
if strings.TrimSpace(list.List) != "" {
listItems = strings.Split(list.List, "\n")
}
model := &personalModel{
Session: session,
Username: username,
ListItems: listItems,
Images: images,
}
err := tpls.ExecuteTemplate(res, "personalpage", model)
if err != nil {
http.Error(res, err.Error(), 500)
return
}
}
示例14: ByID
func (s *UserService) ByID(ctx context.Context, id string) (*User, error) {
rootKey := datastore.NewKey(ctx, "Root", "root", 0, nil)
k := datastore.NewKey(ctx, "User", id, 0, rootKey)
cu, ok := CacheFromContext(ctx).Get(k).(*User)
if ok {
return cu, nil
}
var u User
err := datastore.Get(ctx, k, &u)
if err != nil {
return nil, err
}
ok, err = s.IsVisible(ctx, &u)
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("cannot access user")
}
CacheFromContext(ctx).Set(k, &u)
return &u, nil
}
示例15: createFinalResult
func createFinalResult(ctx context.Context, w http.ResponseWriter, result model.KeyedResult) (int, error) {
var challenge model.Challenge
if err := datastore.Get(ctx, result.Challenge, &challenge); err != nil {
return http.StatusInternalServerError, nil
}
result.Finished = time.Now()
for i, taskKey := range challenge.Tasks {
key, err := getLatestSubmissionKey(ctx, result.Key, taskKey)
if err != nil {
return http.StatusInternalServerError, err
}
result.FinalSubmissions[i] = key
}
_, err := result.Put(ctx, result.Key)
if err != nil {
return http.StatusInternalServerError, err
}
json.NewEncoder(w).Encode(result)
go computeFinalScore(ctx, result, challenge)
return http.StatusOK, nil
}