python - 将数据放入谷歌数据存储后必须刷新
问题描述
我正在尝试为我的项目创建一个用户注册表单,但每次我尝试将数据放入谷歌数据存储时,它都不会立即反映在数据库中。
注册完成后,我重定向到欢迎页面。但是我必须在重定向后刷新页面才能为用户获取相应的信息。为了解决这个问题,我使用了两次 put 语句。有人可以告诉我一个更好的方法来解决这个问题吗?
a=User(username=uname, pass_hash=make_secure(str(pswrd)),parent=users_key())
a.put()
a.put()
解决方案
要使用 Datastore NDB 客户端库实现高度一致的读取,您可以执行“Key Lookup”或 Ancestor 查询(以防您需要获取多个最近存储的实体)。
下面的示例在/sign中存储了一个新的访客,并将请求重定向到具有事件(父)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!')
推荐阅读
- vb.net - 打印完成后如何关闭 PrintPreviewDialog?
- python - 用 Pandas 过滤
- android - 运行 Android 8 的三星 S7 Edge 上的“FirebaseInstallations.java”后台崩溃大幅飙升
- typescript - 如何在打字稿中重载可选参数?
- ajax - 使用查询字符串将 Apache URL 重写为 ajax url
- python - 为垃圾箱制作新列有效,但在所有行中只提供一个垃圾箱
- python - 如何防止seaborn将字符串转换为浮点数?
- python - Python3:类组合和派生方法
- android-studio - 为什么android studio 将Nexus 6 改为sdk gphone x86 arm?
- html - CSS下拉菜单悬停在页面加载或刷新时闪烁