简体   繁体   English

无法使用 python 将数据插入 dynamodb

[英]not able to insert data into dynamodb using python

I am new to the serverless framework and I am trying to put data into my dynamodb using python.我是无服务器框架的新手,我正在尝试使用 python 将数据放入我的 dynamodb。 But not able to insert the data.但无法插入数据。 Even I am not getting any error.即使我没有收到任何错误。

I have tried all the setting for.yml file but no progress我已经尝试了 .yml 文件的所有设置,但没有任何进展

.yml .yml

provider:
  name: aws
  runtime: python3.7

  environment:
    DYNAMODB_TABLE: employee
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}"

  stage: dev
  region: us-east-1


functions:
   create:
    handler: functions/create.create
    events:
     - http:
         path: employee
         method: post
         cors: true
         authorizer: aws_iam
   get:
    handler: functions/get.get
    events:
     - http:
         path: employee/{id}
         method: get
         cors: true
         authorizer: aws_iam

resources:
  Resources:
    employee:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          - AttributeName: employeeId
            AttributeType: S
        KeySchema:
          - AttributeName: employeeId
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.DYNAMODB_TABLE}

.py file .py 文件

import json
import os
import logging

import boto3
dynamodb = boto3.resource('dynamodb')

logger = logging.getLogger("handler_logger")
logger.setLevel(logging.DEBUG)

def create(event, context):
    data = json.loads(event['body'])

    table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
    logger.info(table)

    item = {
        'employeeId': "2",
        'employeeName': "Singhs",
    }

    # write the todo to the database
    table.put_item(Item=item)

    # create a response
    response = {
        "statusCode": 200,
        "body": json.dumps(item)
    }

    return response

I'm not sure why the insert isn't working, the code looks correct.我不确定为什么插入不起作用,代码看起来正确。 You can get more info if you get the response from put_item though.如果您收到put_item的回复,您可以获得更多信息。 For example:例如:

    # write the todo to the database
    put_response = table.put_item(Item=item)

    # create a response
    response = {
        "statusCode": 200,
        "body": json.dumps(put_response)
    }

I've deployed your project and with just small modifications, it works.我已经部署了您的项目,只需稍作修改,它就可以工作。 Means that basically your code is working but as there might be other problems like your iAM role, it would be better if you can provide the result of your POST request.意味着您的代码基本上可以正常工作,但由于您的 iAM 角色可能存在其他问题,如果您可以提供 POST 请求的结果会更好。

Mine is like below:我的如下:

  1. file structure - You're using functions/create.create so it may be different from yours but with given files, but just to make it work, I needed to make it as a simple serverless project.文件结构 - 您正在使用functions/create.create ,因此它可能与您的不同,但使用给定的文件,但为了使其正常工作,我需要将其作为一个简单的无服务器项目。
.
├── serverless.yml
└── handler.py
  1. serverless.yml - added 'service' property and removed your authorizer to call it without any authorization. serverless.yml - 添加“服务”属性并删除您的授权人以在未经任何授权的情况下调用它。
service: stack1
provider:
  name: aws
  runtime: python3.7

  environment:
    DYNAMODB_TABLE: employee
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}"

  stage: dev
  region: us-east-1

functions:
  create:
    handler: handler.create
    events:
      - http:
        path: employee
        method: post
        cors: true
  get:
    handler: functions/get.get
    events:
      - http:
        path: employee/{id}
        method: get
        cors: true

resources:
  Resources:
    employee:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
        Properties:
          AttributeDefinitions:
            - AttributeName: employeeId
              AttributeType: S
          KeySchema:
            - AttributeName: employeeId
              KeyType: HASH
          ProvisionedThroughput:
            ReadCapacityUnits: 1
            WriteCapacityUnits: 1
          TableName: ${self:provider.environment.DYNAMODB_TABLE}
  1. handler.py - same with your.py file. handler.py - 与 your.py 文件相同。

  2. result结果

~/prj/temp/stack> curl -X POST -H "Content-Type: application/json" -d "{}" https://u85k6*****.execute-api.us-east-1.amazonaws.com/dev/employee
{"employeeId": "2", "employeeName": "Singhs"}%

在此处输入图像描述

Suggestion建议

It seems like your code does not have any critical flaws but there're still bunch of points you can have errors from.看起来您的代码没有任何严重缺陷,但仍有很多点可能会导致错误。 These two suggestions might help:这两个建议可能会有所帮助:

1) Catch any exceptions and print out If you use functions like below, you can easily catch what happens there and hints for debugging. 1) 捕捉任何异常并打印出来如果你使用下面的函数,你可以很容易地捕捉到那里发生的事情和调试提示。

import sys
import traceback
import os


def printException(exception, writer=None):
    if writer is None:
        writer = print
    top = traceback.extract_tb(sys.exc_info()[2])[-1]
    writer(", ".join([type(exception).__name__, str(sys.exc_info()[1]), os.path.basename(top[0]), str(top[1])]))```


if __name__ == "__main__":
    try:
        1/0 # just to raise an exception and see how this functions works
    except Exception as e:
        printException(e)

The exception will be printed so you can see it in your Cloudwatch logs.将打印异常,以便您可以在 Cloudwatch 日志中看到它。

2) Enable access logs and see logs in Cloudwatch - from serverless framework v1.42.0, you can enable access logs in the framework. 2)在Cloudwatch中启用访问日志并查看日志——从无服务器框架v1.42.0开始,您可以在框架中启用访问日志。 Just set below properties:只需设置以下属性:

...
provider:
  ...
  logs:
    restApi:
      level: INFO
...

Then you'll be easy to find any api endpoint-related error like authentication, validation or lambda response format errors.然后,您将很容易找到任何与 api 端点相关的错误,例如身份验证、验证或 lambda 响应格式错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM