Skip to main content
 首页 » 编程设计

python之GAE 数据存储使用 Python 过滤不返回任何数据

2025年05月04日9bonelee

db 模式文件在 db/d.py 文件中定义如下:

from google.appengine.ext import db 
class D(db.Model): 
    did = db.StringProperty(required = True) 
    sample_tm = db.DateTimeProperty(auto_now_add = True) 
    weekday = db.IntegerProperty(required = False) 

并且已经有大量数据使用此模式插入到数据存储中,正如我可以从 App Engine 中的数据存储查看器中看到的那样。

但是,当我尝试使用 python 查询处理程序 python 脚本中的数据时出现问题。

from db import d 
class WaitTimeQuery(webapp2.RequestHandler): 
 
    def post(self): 
        self.response.headers['Content-Type'] = 'text/html'          
        q = d.D.all() 
        print q.get() 

每次它只会打印一个None。为什么不能以这种方式获取这些数据?

我还尝试在 python 中使用嵌入式 gql,它再次没有返回任何结果,但是在执行时:

select * from D

在数据查看器中,可以正确显示结果

请您参考如下方法:

首先如 Remco Haszing 所说,在编写新应用程序时使用 ndb 而不是 db。在编写遗留应用程序时,可以使用 db,但您应该迁移到 ndb。 ;-)

required=False 也不是必需的,这是默认的。 ;-)

from google.appengine.ext import ndb 
 
class D(ndb.Model): 
    did = ndb.StringProperty(required=True) 
    sample_tm = ndb.DateTimeProperty(auto_now_add=True) 
    weekday = ndb.IntegerProperty() 

创建一个实例并放置它:

d = D(did='spam') 
d_key = d.put()  # Stores the instance. 

d_key 是您可以用来从数据存储中取回实例的 Key。

当您有可能进行查找而不是查询时:

d = d_key.get() 
assert d.did == 'spam' 

全局查询 (D.query()) 的问题在于无法保证一定会有结果。参见 the docs了解详情。

NDB writes data in steps:

  • In the Commit phase, the underlying Datastore service records the changes.
  • NDB invalidates its caches of the affected entity/entities. Thus, future reads will read from (and cache) the underlying Datastore instead of reading stale values from the cache.
  • Finally, perhaps seconds later, the underlying Datastore applies the change. It makes the change visible to global queries and eventually-consistent reads.

在数据存储中应用更改后,您可以使用全局查询:

results = D.query().fetch()  # results will be a list with D instances