python - GAE 和 Python : My dictionary values return None instead of an object

标签 python google-app-engine

我正在使用 Python 和 GAE,并且我正在尝试创建一个字典,其中键是用户 ID,值是“学生”对象。但是,我的字典的值是 None 而不是学生对象。

{'60': , '59': }

如果有人能指出我正确的方向,我将非常感激!

学生.py

class Student:

def __init__(self, name, s_id, rew = {}):
    self.name = name.strip()
    self.rewards = {"Creativity": 0, "Helping Others":0, "Participation":0, "Insight":0}
    self.totalRewardPoints = 0   
    self.s_id = s_id

Main.py(我只包含了相关代码)

class PageHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
    self.response.out.write(*a, **kw)

def initialize(self, *a, **kw):
    webapp2.RequestHandler.initialize(self, *a, **kw)

def create_students(self):
    user = db.GqlQuery("SELECT * FROM User WHERE position='student'")

    for u in user:

        temp_id = str(u.key().id())
        self.students[temp_id] = student.Student(u.name, temp_id)

class MainPage(PageHandler):

students = {}

def get(self):

    user = db.GqlQuery("SELECT * FROM User WHERE position='student'")

    for u in user:

        temp_id = str(u.key().id())
        self.students[temp_id] = student.Student(u.name, temp_id)

    self.write(self.students)

app = webapp2.WSGIApplication([('/', MainPage)], debug=True)

最佳答案

对于初学者,您的 Student 类需要继承一些实现 appengine 数据存储区持久性的模型类。如果您使用原始数据存储 api,则使用 db.Model,如果使用 ndb,则使用 nbd.Model。

其次,您还没有展示如何将学生实体写入 (put()) 到数据存储区。基于您没有从(db 或 ndb)继承的事实,您不太可能将任何内容保存到数据存储中。

当然,除非您不包含实际的代码。如果您使用 db.Model 作为基类,那么您的奖励字段将不起作用。您可能应该将 ndb 作为替代起点并使用结构化属性。

您可能需要通过 View 文档 https://developers.google.com/appengine/docs/python/datastore/overview#Python_Datastore_API 阅读有关应用程序引擎存储数据的信息。您的代码看起来一点也不像 GAE(Google Appengine 代码)

您的学生类(class)应该看起来像这样(如果您希望奖励字段具有某种结构)

class Reward(ndb.Model):
    reward = ndb.StringProperty()
    value = ndb.IntegerProperty()

class Student(ndb.Model):
    name = ndb.StringProperty(required=True)
    rewards = ndb.StructuredProperty(Reward, repeated=True)
    total_reward_points = ndb.IntegerProperty()
    s_id = ndb.StringProperty()

否则,如果您使用 db.Model,则奖励将是 db.BlobProperty(),然后您将在保存数据时使用 pickle.dumps 或 json.dumps 使用 json 来编码奖励字典。

关于python - GAE 和 Python : My dictionary values return None instead of an object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12227036/

相关文章:

python - 如何限制python pandas dataframes的操作区域?

python - Python 的列表、元组和字典的 Node.js 等效数据类型

google-app-engine - 向 Objectify 查询添加排序会导致空结果

node.js - Google App Engine 标准 Node JS 如何运行构建脚本?

python - 使用 google app engine 作为 smtp 服务器

google-app-engine - 常驻实例似乎不起作用

python - 在 Pandas 中调用多行

python - 在 `self` 中返回 `__enter__` 以外的值是反模式吗?

python - 通过 Beatbox、Python 将附件上传到 Salesforce API

google-app-engine - GAE Golang - OAuth 和 OAuth2?