我想制作一个DailyPost实体。但是,当我同时发出两个请求时,有两个DailyPost实体。
我该如何限制?
环境:
Google App Engine
运行时:Python27
datastore:ndb
def get_today():
return datetime.datetime.combine(datetime.date.today(), datetime.time())
class DailyPost(ndb.Model):
user = ndb.KeyProperty(kind=User)
content = ndb.StringProperty()
created = ndb.DateTimeProperty(auto_now_add=True)
class GetOrCreateHandler(webapp2.RequestHandler):
def get(self):
user = session.get_user() # user from session (pseudo code)
post = DailyPost.query(DailyPost.created >= get_today(),
DailyPost.user==user.key).get()
if not post:
# Delay to test. (or time.sleep)
for i in range(30000):
print 1
post = DailyPost(content='some text..', user=user.key)
post.put()
self.response.write(post.content)
答案 0 :(得分:0)
只需使用get_or_insert方法将每天的唯一值用作关键字:
import datetime
class DailyPost(ndb.Model):
user = ndb.KeyProperty(kind=User)
content = ndb.StringProperty()
#created = ndb.DateTimeProperty(auto_now_add=True)
class GetOrCreateHandler(webapp2.RequestHandler):
def get(self):
user = self.session.get_user() # user from session (pseudo code)
_id = '%s.%s' % (user.id, datetime.date.today().strftime('%s'))
DailyPost.get_or_insert(_id, user=user, content='bla')
self.response.write(post.content)