gpt4 book ai didi

python - GAE 使用 Python 将数组发布到数据存储(一对多)

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:30 25 4
gpt4 key购买 nike

与 GAE 合作已有几个月了。这是我第一次在这里处理一对多关系。在我开始处理关系之前,一切都已顺利发布到数据存储中。这是第一个。有人可以帮我将这个“帖子”发送到数据存储吗?目前,文档和其他示例非常令人困惑。我知道我 employees=r['Employees'] 做错了, 我只想先写一个简单的帖子。如果你能把它搞砸就更好了!如图所示,我在发帖时收到 BadValueError ;

enter image description here

模型.py

class Project(ndb.Model):
projectID = ndb.IntegerProperty(required=True)
title = ndb.StringProperty(required=True)
description = ndb.StringProperty(required=True)
startAt = ndb.DateTimeProperty(indexed=True)
endAt = ndb.DateTimeProperty()
employees = ndb.KeyProperty(kind='Employees', repeated=True)

class Employees(ndb.Model):
name = ndb.StringProperty()
role = ndb.StringProperty()

handlers.py

 def post(self):
r = json.loads(self.request.body)
print str(r)

g = Project(projectID=int(r['ProjectID']),
description=r['Description'],
title=r['Title'],
employees=r['Employees'],
startAt=datetime.strptime(r['StartAt'], '%d/%m/%Y %H:%M %p'),
endAt=datetime.strptime(r['EndAt'], '%d/%m/%Y %H:%M %p'))

project_key = g.put()
project_key.get()
print project_key

controller.js

    $scope.employees = [
{
name:'mark',
role: 'dev'
},
{
name:'colin',
role: 'dev2'
},
];

更新-------------------------------------------------------- ---------------------------

json 处理程序

class commentsJsonHandler(webapp2.RequestHandler):
@classmethod
def route(cls):
"""
name: index, template: /
"""
return webapp2.Route('/comments', handler=cls, name='_commments_')


def get(self):
recommendations = Project.query()

def date_handler(obj):
if isinstance(obj, datetime):
return obj.isoformat()
else:
raise TypeError

self.response.out.write(json.dumps([dict(rec.to_dict(), **dict(id=rec.key.id())) for rec in recommendations], default=date_handler))

最佳答案

您必须迭代 json 负载中的员工集合,首先创建这些员工实体,然后使用它们的 key 创建项目实体

def post(self):
r = json.loads(self.request.body)
print str(r)
employee_keys = []
for emp in r['Employees']:
employee = Employees(name=emp['name'], role=emp['role'])
employee.put()
employee_keys.append(employee.key)


g = Project(projectID=int(r['ProjectID']),
description=r['Description'],
title=r['Title'],
employees=employee_keys,
startAt=datetime.strptime(r['StartAt'], '%d/%m/%Y %H:%M %p'),
endAt=datetime.strptime(r['EndAt'], '%d/%m/%Y %H:%M %p'))

project_key = g.put()
project_key.get()
print project_key

关于python - GAE 使用 Python 将数组发布到数据存储(一对多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40364722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com