我正在尝试为我的项目创建用户注册表格,但是每次尝试将数据放入google数据存储区时,它都不会立即反映在数据库中。
注册完成后,我重定向到欢迎页面。但是我必须在重定向后刷新页面才能为用户获取相应的信息。为了解决这个问题,我两次使用put语句。有人可以告诉我一种更好的方法来解决这个问题吗?
a=User(username=uname, pass_hash=make_secure(str(pswrd)),parent=users_key())
a.put()
a.put()
答案 0 :(得分:0)
要与数据存储NDB客户端库实现高度一致的读取,可以执行“键查找”或“祖先”查询(以防您需要获取多个最近存储的实体)。
下面的示例在 / sign 中存储一个新的Guest,并将请求重定向到具有事件(父)ID和最近创建的实体的url_safe ID的根:
# When accessed /sign we check if an Event with ID 1111 exists
event_key = ndb.Key('Event', 1111)
event = event_key.get()
# If it does not exist we create one
if event is None:
event = Event(key=event_key, title=’Party’)
event.put()
# We store a new Guest
name = '<SOME_RANDOM_STRING>'
guest = Guest(name=name, parent=event_key)
guest.put()
print(guest)
# And redirect the request to the main route with the information we need to fetch these entities
# You could use the urlsafe() method for both, I chose to use separate methods just as an example
self.redirect('/?' + urllib.urlencode(
{
'event_id': event_key.id(),
'guest_id': guest.key.urlsafe()
}))
将用户重定向到主路由后:
event_id = self.request.get('event_id')
# If the url comes with an event ID, then we proceed with querying for Guests
if event_id:
# We generate a key with the ID
event_key = ndb.Key('Event', int(event_id))
# And we execute an Ancestor query to fetch all guests of that event
guests = Guest.query(ancestor=event_key).fetch()
print(guests)
# Here we do a basic “Key Lookup” just to fetch the newly created guest
guest_id = self.request.get('guest_id')
if guest_id:
guest_key = ndb.Key(urlsafe=guest_id)
guest = guest_key.get()
print(guest)
self.response.out.write('Check your Logs!')