首页 > 解决方案 > 在 Python 中使用 AWS DynamoDB CRUD 函数的问题

问题描述

我在为 DynamoDB 创建 CRUD API 时遇到问题。我不断收到 500 个删除和更新操作的代码错误。不过,我没有遇到 GET 请求的任何问题(它使用查询)。我的代码如下: -

PATCH(用于更新操作)

    elif request.method == 'PATCH':
        data = request.get_json()
        key = {
               'id': data['id'],
               'timestamp': data['timestamp']
        }
        try:
            response = table.update_item(
                Key = key,
                UpdateExpression = "SET title=:t, blurb=:b, category=:c, img=:i",
                ExpressionAttributeValues = {
                    ':t': data['title'],
                    ':b': data['blurb'],
                    ':c': data['category'],
                    ':i': data['img']
                }, # TYPE BOOK CONTAINS OTHER FIELDS ALSO
                ReturnValues = "UPDATED_NEW"
            )
            return jsonify(response)
        except ClientError as e:
            print("ITEM NOT UPDATED")

我在键条件中定义了两个键,因为我的主键包含两个值。同样,DELETE 的代码如下:

    elif request.method == 'POST':
        data = request.get_json()
        key = {
            'id': data['id'],
            'timestamp': data['timestamp']
        }
        try:
            response = table.delete_item(
                Key = key,
                ReturnValues = "DELETED"
            )
            return jsonify(response)
        except ClientError as e:
            print("ITEM NOT DELETED")
            return jsonify("ITEM NOT DELETED")

我得到的输出如下(在我的应用程序中打印(request.body)):

I/flutter (21896): <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
I/flutter (21896): <title>500 Internal Server Error</title>
I/flutter (21896): <h1>Internal Server Error</h1>
I/flutter (21896): <p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>

任何解决此问题的帮助将不胜感激。我试图寻找线索,但网上显示的任何东西似乎都不起作用。在没有 DynamoDB 命令的情况下,烧瓶似乎可以按预期工作。

标签: amazon-web-servicesflaskamazon-dynamodbcrud

解决方案


问题在这里:

            response = table.delete_item(
                Key = key,
                ReturnValues = "DELETED"
            )

在删除操作的情况下,应省略 ReturnValues。此外 DELETED 不是 DynamoDB 中 ReturnValues 表达式的允许关键字。


推荐阅读