本文整理汇总了Golang中appengine/datastore.NewIncompleteKey函数的典型用法代码示例。如果您正苦于以下问题:Golang NewIncompleteKey函数的具体用法?Golang NewIncompleteKey怎么用?Golang NewIncompleteKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewIncompleteKey函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: addTagToFact
func addTagToFact(c appengine.Context, factKey *datastore.Key, tag string) {
q := datastore.NewQuery("Tag").Filter("Name =", tag)
cnt, _ := q.Count(c)
var existingTag Tag
var existingTagKey *datastore.Key
if cnt > 0 {
// retrieve
for t := q.Run(c); ; {
existingTagKey, _ = t.Next(&existingTag)
break // only need one
}
} else {
// create a new one
var t = Tag{Name: tag}
existingTagKey, _ = datastore.Put(c, datastore.NewIncompleteKey(c, "Tag", nil), &t)
}
qft := datastore.NewQuery("FactTag").
Filter("Fact = ", factKey).
Filter("Tag = ", existingTagKey)
cnt2, _ := qft.Count(c)
if cnt2 == 0 {
// create a new one
var ft = FactTag{Fact: factKey, Tag: existingTagKey}
_, _ = datastore.Put(c, datastore.NewIncompleteKey(c, "FactTag", nil), &ft)
}
}
示例2: createNewGame
func createNewGame(c appengine.Context, userId string, players []string) (Game, error) {
g := Game{
UserId: userId,
Started: time.Now(),
Players: players,
}
err := datastore.RunInTransaction(c, func(c appengine.Context) error {
key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "game", nil), &g)
if err != nil {
return err
}
// For now just add all players into the queue.
for _, p := range players {
qp := QueuePlayer{
UserId: p,
Timestamp: time.Now(),
}
_, err := datastore.Put(c, datastore.NewIncompleteKey(c, "queueplayer", key), &qp)
if err != nil {
return err
}
}
g.Id = key.Encode()
return nil
}, nil)
return g, err
}
示例3: Post
func (handler *userHandler) Post(r *fhttp.JsonRequest) fhttp.Response {
user := new(models.User)
err := r.Extract(user)
if err != nil {
return fhttp.UserError("invalid json")
}
if user.Nickname == "" {
return fhttp.UserError("nickname cannot be empty")
}
context := appengine.NewContext((*http.Request)(r))
userKey, err := datastore.Put(context, datastore.NewIncompleteKey(context, "User", nil), user)
if err != nil {
return fhttp.ServerError(err.String())
}
auth := models.NewAuth(userKey)
_, err = datastore.Put(context, datastore.NewIncompleteKey(context, "Auth", nil), auth)
if err != nil {
return fhttp.ServerError(err.String())
}
return fhttp.JsonResponse{
&postResponse{
fmt.Sprintf("%x", auth.Public),
},
}
}
示例4: save
func save(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
c := appengine.NewContext(r)
u := user.Current(c)
tags := strings.Split(r.FormValue("tags"), ",")
p := datatypes.Post{
Author: u.String(),
Title: r.FormValue("title"),
Text: r.FormValue("blogcontent"),
GoDate: time.Now(),
ID: -1,
Tags: tags,
}
key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "posts", nil), &p)
if err != nil {
log.Fatal(err)
}
for i := range tags {
_, err := datastore.Put(c, datastore.NewIncompleteKey(c, tags[i], nil), &p)
if err != nil {
log.Fatal(err)
}
}
time.Sleep(500 * time.Millisecond)
http.Redirect(w, r, "/posts/"+strconv.FormatInt(key.IntID(), 10), http.StatusFound)
}
示例5: addTestData
func addTestData(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
e := DiaryEntry{
Author: "Julian",
Content: []byte(`Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.`),
Date: (time.Now()).Add(time.Hour * 24),
CreationTime: time.Now(),
}
_, _ = datastore.Put(c, datastore.NewIncompleteKey(c, "DiaryEntry", nil), &e)
e = DiaryEntry{
Author: "Julian",
Content: []byte("It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)."),
Date: time.Now(),
CreationTime: time.Now(),
}
_, _ = datastore.Put(c, datastore.NewIncompleteKey(c, "DiaryEntry", nil), &e)
w.Header().Set("Status", "302")
w.Header().Set("Location", "/")
}
示例6: SavePost
func SavePost(context appengine.Context, title string, content appengine.BlobKey, tags []string, postdate time.Time) (*datastore.Key, error) {
// transaction
temppostkey := datastore.NewIncompleteKey(context, "post", nil)
p1 := Post{
Title: title,
Content: content,
Postdate: postdate,
StickyUrl: conv_title_to_url(title),
Tags: tags,
}
postkey, err := datastore.Put(context, temppostkey, &p1)
if err != nil {
return nil, err
}
tagkey := datastore.NewIncompleteKey(context, "tagindices", postkey)
t1 := TagIndex{
Tags: tags,
Postdate: postdate,
}
_, err = datastore.Put(context, tagkey, &t1)
if err != nil {
return nil, err
}
tagcounts, err := CalculateTagCounts(context)
if err != nil {
return nil, err
}
var name []string
var count []int
for k, v := range tagcounts {
name = append(name, k)
count = append(count, v)
}
taggggkey := datastore.NewKey(context, "tagcounts", "", 1, nil)
t2 := TagCounts{
Name: name,
Count: count,
}
_, err = datastore.Put(context, taggggkey, &t2)
if err != nil {
return nil, err
}
// end transaction
return postkey, nil
}
示例7: initStock
func initStock(c appengine.Context, w http.ResponseWriter, stocks []Stock) {
if len(stocks) == 0 {
googleStock := &Stock{Empresa: "Google", Puntos: 1000}
amazonStock := &Stock{Empresa: "Amazon", Puntos: 900}
keyGoogle := datastore.NewIncompleteKey(c, "Stock", nil)
keyAmazon := datastore.NewIncompleteKey(c, "Stock", nil)
if _, err := datastore.Put(c, keyGoogle, googleStock); err != nil {
c.Errorf("Error al inicializar los valores de google. %v", err)
}
if _, err := datastore.Put(c, keyAmazon, amazonStock); err != nil {
c.Errorf("Error al inicializar los valores de amazon. %v", err)
}
c.Debugf("datastore inicializado con los valores de prueba inciales")
}
}
示例8: signupPost
func signupPost(w http.ResponseWriter, r *http.Request) {
responseType, client, err := params(r)
if err != nil {
err.WriteTo(w)
return
}
email, password := r.FormValue("email"), r.FormValue("password")
emailRegexp := regexp.MustCompile(`^[a-z0-9._%\-+][email protected][a-z0-9.\-]+\.[a-z]+$`)
msgs := make([]string, 0, 5)
if !emailRegexp.MatchString(email) {
msgs = append(msgs, "Invalid email address")
}
if len(password) < 6 {
msgs = append(msgs, "Password is too short")
}
// Also check if email already exists
user := model.NewUser(email)
context := appengine.NewContext(r)
countExists, e := datastore.NewQuery("User").Filter("EmailHash =", user.EmailHash).Count(context)
if e != nil {
context.Errorf("%v", e)
http.Error(w, e.String(), http.StatusInternalServerError)
return
}
if countExists > 0 {
msgs = append(msgs, "Email already exists")
}
if msgsLen := len(msgs); msgsLen > 0 {
http.RedirectHandler("/oauth2/signup?response_type="+url.QueryEscape(responseType)+"&client_id="+
url.QueryEscape(client.Id)+"&msgs="+url.QueryEscape(strings.Join(msgs, "|")), 303).ServeHTTP(w, r)
} else {
userKey, err := datastore.Put(context, datastore.NewIncompleteKey(context, "User", nil), user)
if err != nil {
context.Errorf("Error saving: %v", err)
w.Write([]byte("Error saving: " + err.String()))
return
}
auth := model.NewPasswordAuth(userKey, password)
if _, err = datastore.Put(context, datastore.NewIncompleteKey(context, "Authentication", nil), auth); err != nil {
context.Errorf("Error saving: %v", err)
w.Write([]byte("Error saving: " + err.String()))
return
}
key := newCodeKey(userKey.StringID(), client.Id, context)
http.RedirectHandler(client.redirectUrl(key), 303).ServeHTTP(w, r)
}
}
示例9: doCreateNew
func doCreateNew(w http.ResponseWriter, r *http.Request) {
user := r.FormValue("user")
if user == "" {
//empty values or variables not sended. Very basic prevention
fmt.Fprintf(w, "<html>Error: error in arguments. Go <a href='/login.do' >Back</a></html>")
return
}
c := appengine.NewContext(r)
q := datastore.NewQuery("User").
Filter("Username = ", user)
if count, _ := q.Count(c); count > 0 { //Verify the previous existence of the user
fmt.Fprintf(w, "<html>Username already exists. <a href='/login.docreate' >Go back</a></html>")
return
}
var theuser User
theuser.Username = user
theuser.Creation = time.Now()
theuser.Tok3nKey = ""
key := datastore.NewIncompleteKey(c, "User", nil)
key, err := datastore.Put(c, key, &theuser)
if err != nil {
fmt.Fprintf(w, "Error: %v", err)
return
}
fmt.Fprintf(w, "<html>New user (%s) added. <a href='/login.do'>Go login now</a>.</html>", user)
}
示例10: getAndStoreTerms
func getAndStoreTerms(context appengine.Context) ([]Term, error) {
responseBody, err := runApiRequest(context, "/Terms")
if err != nil {
context.Infof("Failed loading the terms!")
context.Infof(err.Error())
return nil, err
}
context.Infof("About to unmarshal: %s", string(responseBody))
var termsResponse TermsOverallResponse
err = json.Unmarshal(responseBody, &termsResponse)
if err != nil {
context.Infof("Couldn't unmarshal the terms response")
context.Infof(err.Error())
return nil, err
}
termsQuery := datastore.NewQuery("Term").KeysOnly()
termKeys, err := termsQuery.GetAll(context, nil)
if err != nil {
context.Infof("There was a problem loading the existing terms from the datastore")
context.Infof(err.Error())
return nil, err
}
for _, termKey := range termKeys {
datastore.Delete(context, termKey)
}
for _, term := range termsResponse.OverallResponse.Terms {
datastore.Put(context, datastore.NewIncompleteKey(context, "Term", nil), &term)
}
return termsResponse.OverallResponse.Terms, nil
}
示例11: key
func (o *Purchaser) key(c appengine.Context) *datastore.Key {
if o.Id == 0 {
o.Created = time.Now()
return datastore.NewIncompleteKey(c, "Purchaser", defaultPurchaserList(c))
}
return datastore.NewKey(c, "Purchaser", "", int64(o.Id), defaultPurchaserList(c))
}
示例12: NewItem
// req: POST /items/ {"Title": "Buy bread"}
// resp: 201
func NewItem(w http.ResponseWriter, r *http.Request) error {
req := struct{ Title string }{}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return badRequest{err}
}
if req.Title == "" {
return fmt.Errorf("Empty title!")
}
newItem := newDefaultItem()
newItem.Title = req.Title
c := appengine.NewContext(r)
itemKey, e := datastore.Put(c, datastore.NewIncompleteKey(c, "Item", nil), newItem)
if e != nil {
return e
}
newItem.ID = itemKey.IntID()
_, e = datastore.Put(c, itemKey, newItem)
// log.Println("newItem.ID -> ", newItem.ID)
if e != nil {
return e
}
newUrl := r.URL.Path + strconv.FormatInt(newItem.ID, 10)
w.Header().Set("Location", newUrl)
w.WriteHeader(http.StatusCreated)
return nil
}
示例13: key
func (q *Quote) key(ctx appengine.Context) *datastore.Key {
if q.ID == 0 {
q.Created = time.Now()
return datastore.NewIncompleteKey(ctx, "Quote", defaultQuotes(ctx))
}
return datastore.NewKey(ctx, "Quote", "", q.ID, defaultQuotes(ctx))
}
示例14: handleNewSong
func handleNewSong(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
song := parseSongForm(w, r)
_, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Song", nil), &song)
handleErr(err, w)
}
示例15: insert
// POST http://localhost:8080/profiles
// {"first_name": "Ivan", "nick_name": "Socks", "last_name": "Hawkes"}
//
func (u *ProfileApi) insert(r *restful.Request, w *restful.Response) {
c := appengine.NewContext(r.Request)
// Marshall the entity from the request into a struct.
p := new(Profile)
err := r.ReadEntity(&p)
if err != nil {
w.WriteError(http.StatusNotAcceptable, err)
return
}
// Ensure we start with a sensible value for this field.
p.LastModified = time.Now()
// The profile belongs to this user.
p.Email = user.Current(c).String()
k, err := datastore.Put(c, datastore.NewIncompleteKey(c, "profiles", nil), p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Let them know the location of the newly created resource.
// TODO: Use a safe Url path append function.
w.AddHeader("Location", u.Path+"/"+k.Encode())
// Return the resultant entity.
w.WriteHeader(http.StatusCreated)
w.WriteEntity(p)
}