python - AWS DynamoDB Python - 不从 table.scan() 返回属性
问题描述
我正在使用 Python 将数据添加到名为 Courses 的 DynamoDB 表中,并为用户提供一个命令界面,以通过输入主题和目录号来搜索课程描述。
期望的结果:
Welcome to the Course Title Navigator
Enter Subject: SDEB
Enter Catalog Number: 452
Inaccurate search or No records found. Please try again!
Enter Subject: SDEV
Enter Catalog Number: 450
SDEV 450 is Advanced Programming
Would you like to search for another title? Y or N
N
Thank you for using the Course Title Navigator
我的程序在 table.scan() 之后没有返回表属性时遇到问题。似乎将响应读取为 0 并打印错误消息。我认为我的 table.scan 存在问题,但我不确定是什么问题。我最初使用的是查询,但我遇到了很多问题,我读到扫描更适合我的应用程序。
def check_class_info(Subject, CatalogNbr, Title, dynamodb=None): # checks if class info exists
if not dynamodb:
dynamodb = boto3.resource('dynamodb')
while True:
Subject = ""
CatalogNbr = ""
while Subject == "":
Subject = input ("Enter Subject: ")
CatalogNbr = ""
while CatalogNbr == "":
CatalogNbr = input("Enter Catalog Number: ")
CatalogNbr = int(CatalogNbr)
response = table.scan(FilterExpression=Attr("Subject").eq(Subject) & Attr("CatalogNbr").eq(CatalogNbr))
# print(response)
if response["Count"] == 0:
print ("Inaccurate search or No records found. Please try again!")
return end_main()
else:
print(response["Items"][0]["title"])
return end_main()
这是我的表的详细信息:
aws dynamodb describe-table --table-name Courses
{
"Table": {
"TableArn": "arn:aws:dynamodb:us-east-1:399520938535:table/Courses",
"AttributeDefinitions": [
{
"AttributeName": "CourseID",
"AttributeType": "S"
},
{
"AttributeName": "Subject",
"AttributeType": "S"
}
],
"ProvisionedThroughput": {
"NumberOfDecreasesToday": 0,
"WriteCapacityUnits": 50,
"ReadCapacityUnits": 50
},
"TableSizeBytes": 753,
"TableName": "Courses",
"TableStatus": "ACTIVE",
"TableId": "d62be64f-949d-454c-b716-93ff18968d58",
"KeySchema": [
{
"KeyType": "HASH",
"AttributeName": "CourseID"
},
{
我还在学习 DynamoDB,所以我正在努力解决这个错误。我非常感谢您能提供的任何帮助。
解决方案
扫描操作可以以两种方式运行
response = table.scan(FilterExpression=Attr("Subject").eq(Subject) & Attr("CatalogNbr").eq(CatalogNbr))
或者
response = table.scan(
FilterExpression= 'Subject=:subject AND CatalogNbr=:catalogNbr',
ExpressionAttributeValues= {
':subject': Subject ,
':catalogNbr': CatalogNbr,
} )
在这两种类型的语法中,我们都必须传递正确的类型。根据评论,在这种情况下 CatalogNbr 是数据库中的字符串,必须作为字符串传递。因此删除CatalogNbr = int(CatalogNbr)
线起作用了。
推荐阅读
- java - 从 Firebase 实时数据库获取计数器值的问题
- c++ - 如何从文件中正确加载完整变量数据集的值?
- ios - 如何在 Swift 中修复“UIAlertController 的 ActionSheet 具有冲突约束”错误
- sql - CLR 程序集可能会给 SQL Server 实例带来安全漏洞
- javascript - 图表未水平对齐
- jpa - 使用 JPA 定义动态数据库配置
- validation - 有没有办法为多行创建数据验证脚本
- android - 使用 Google 提供的 SHA1 指纹生成新的密钥库
- ios - 在 `UISearchbar` 中搜索名称或号码
- node.js - 模糊搜索中的“未定义正则表达式”错误