使用端点(Python)更新数据存储JSON值

2024-09-27 01:24:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用端点来更新数据存储中的一些JSON值。我在GAE中有以下数据存储。。。在

class UsersList(ndb.Model):
    UserID = ndb.StringProperty(required=True)
    ArticlesRead = ndb.JsonProperty()
    ArticlesPush = ndb.JsonProperty()

一般来说,我对API的处理是让方法接受一个UserID和一个阅读的文章列表(一篇文章由一个字典表示,字典中包含一个ID,一个boolean字段表示用户是否喜欢这篇文章)。我的信息(以这个逻辑为中心)如下。。。在

^{pr2}$

我的API/Endpoint方法正在尝试进行此更新,如下所示。。。在

@endpoints.method(UserIDAndArticles, ArticleList,
                  name='user.update',
                  path='update',
                  http_method='GET')
def get_update(self, request):
    userID = request.id
    articleList = request.items
    queryResult = UsersList.query(UsersList.UserID == userID)

    currentList = []

    #This query always returns only one result back, and this for loop is the only way
    # I could figure out how to access the query results.
    for thing in queryResult:
        currentList = json.loads(thing.ArticlesRead)

    for item in articleList:
        currentList.append(item)

    for blah in queryResult:
        blah.ArticlesRead = json.dumps(currentList)
        blah.put()

    for thisThing in queryResult:
        pushList = json.loads(thisThing.ArticlesPush)

    return ArticleList(items = pushList)

我对这个代码有两个问题。第一个问题是,我似乎不知道(使用localhost googleapisexplorer)如何使用UserIDAndArticles类将文章列表发送到endpoints方法。有没有可能消息.MessageField()作为端点方法的输入?在

另一个问题是我在'废话文章阅读= json.dumps文件(currentList)行。当我尝试用一些随机输入运行这个方法时,我得到以下错误。。。在

TypeError: <Articles
 id: u'hi'
 userLiked: False> is not JSON serializable

我知道我必须自己制作JSON编码器来解决这个问题,但是我不确定传入的格式是什么请求项就像我应该如何编码。在

我对GAE和端点(以及这种类型的服务器端编程)还不熟悉,所以请耐心等待。感谢你的帮助。在


Tags: 方法injsonforrequest文章update端点
1条回答
网友
1楼 · 发布于 2024-09-27 01:24:38

有几件事:

  • http_method绝对应该是POST,或者更好的是PATCH,因为您没有覆盖所有现有的值,而只是修改一个列表,即修补。在
  • 你不需要它。在
  • 您将混合端点消息和NDB模型属性。在

下面是我想出的方法体:

# get UsersList entity and raise an exception if none found.
uid = request.id
userlist = UsersList.query(UsersList.UserID == uid).get()
if userlist is None:
    raise endpoints.NotFoundException('List for user ID %s not found' % uid)

# update user's read articles list, which is actually a dict.
for item in request.items:
    userslist.ArticlesRead[item.id] = item.userLiked
userslist.put()

# assuming userlist.ArticlesPush is actually a list of article IDs.
pushItems = [Article(id=id) for id in userlist.ArticlesPush]
return ArticleList(items=pushItems)

另外,您可能应该在事务中包装此方法。在

相关问题 更多 >

    热门问题