首页 > 解决方案 > 将数据放入谷歌数据存储后必须刷新

问题描述

我正在尝试为我的项目创建一个用户注册表单,但每次我尝试将数据放入谷歌数据存储时,它都不会立即反映在数据库中。

注册完成后,我重定向到欢迎页面。但是我必须在重定向后刷新页面才能为用户获取相应的信息。为了解决这个问题,我使用了两次 put 语句。有人可以告诉我一个更好的方法来解决这个问题吗?

a=User(username=uname, pass_hash=make_secure(str(pswrd)),parent=users_key())
a.put()
a.put()

标签: pythongoogle-app-enginewebapp2

解决方案


要使用 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!')

推荐阅读