python - 如何使用 mturk 迭代 boto3 中的结果

标签 python amazon-web-services boto mechanicalturk

我是 boto 的新手,我尝试迭代我可以获得的结果。

特别是,我想统计具有给定资格的​​所有 worker 。但是,限制是 100,我不明白它如何与 NextToken 一起使用。有人可以帮助我吗?

# next_token = 1
qualification_count = 0
while True:
    response = s3.list_workers_with_qualification_type(
        QualificationTypeId=qualification_id,
        Status='Granted',
        MaxResults=100,
        NextToken=next_token
    )
    next_token = response['NextToken']
    qualification_count += response['NumResults']

显然 next_token 不正确,但我不知道它应该是什么

最佳答案

有一些事情可能会让你搞砸。第一个(次要的)是您使用的客户端名为 s3。这可能只是您为 MTurk 选择的变量名称,但值得确保您不会尝试针对 AWS S3 客户端调用它。

第二个是您在第一次调用 While 循环时引用 next_token (变量)。问题是它不会在你第一次初始化时初始化,因此注定会失败。同样,这可能只是您所显示的简短代码片段的残余,而不是真正的问题。

但无论如何,下面的代码应该可以工作。请注意,您可以配置要返回的页面大小(我相信最多 100)。但重要的是,它永远不会传递未初始化的 NextToken,并且它会正确设置 MTurk 客户端。这段代码对我来说有效。如果您遇到任何问题,请告诉我。很高兴能进一步提供帮助。

import boto3

region_name = 'us-east-1'
aws_access_key_id = 'YOUR_ACCESS_KEY'
aws_secret_access_key = 'YOUR_SECRET_KEY'

PAGE_SIZE = 20

endpoint_url = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com'

client = boto3.client('mturk',
    endpoint_url = endpoint_url,
    region_name = region_name,
    aws_access_key_id = aws_access_key_id,
    aws_secret_access_key = aws_secret_access_key,
)

qualification_id='9W4ZQKNWM3FZ5HGM2070'

response = client.list_workers_with_qualification_type(
        QualificationTypeId=qualification_id,
        Status='Granted',
        MaxResults=PAGE_SIZE
    )
next_token = response['NextToken']

qualification_count = response['NumResults']
while (response['NumResults'] == PAGE_SIZE):
    print "Using next token of {}".format(next_token)
    response = client.list_workers_with_qualification_type(
            QualificationTypeId=qualification_id,
            Status='Granted',
            MaxResults=PAGE_SIZE,
            NextToken=next_token
    )
    next_token = response['NextToken']
    qualification_count += response['NumResults']

print "There are {} Workers in Qualification {}".format(qualification_count, qualification_id)

关于python - 如何使用 mturk 迭代 boto3 中的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43922317/

相关文章:

python 博托 : How do you specify a subnet id AND a security group?

amazon-web-services - Appsync 响应映射模板 json 键名称更改

python - 在 python 3 中使用 boto

Python 3,如何设置 Visual Studio C++ 2015 编译器?

python - Django:删除未使用的文件

amazon-web-services - 通过 ssh 连接到 aws rds 实例所需的参数

api - 迁移 - 零停机时间更改 DNS 中记录的 IP

python - 如何读取describe_stack输出属性

python - 查找另一个列表中每个子列表的超集索引

python - 适用于 Python 的 Azure ADAL - 面临 acquire_token_with_username_password 方法的问题