【问题标题】:How to send a JSON file to Amazon SQS queue using BOTO如何使用 BOTO 将 JSON 文件发送到 Amazon SQS 队列
【发布时间】:2016-08-16 22:28:23
【问题描述】:

我需要向 AWS SQS 队列服务发送几个 .json 文件。有人可以告诉我使用 boto 的确切代码将完成此操作吗?

【问题讨论】:

    标签: amazon-web-services boto amazon-sqs


    【解决方案1】:

    类似的东西应该可以工作: (你可以先检查语法,我没有测试过)

    import boto.sqs
    import json
    
    queue_name = 'YOUR-QUEUE'
    sqs = boto.sqs.connect_to_region('us-east-1')
    queue = sqs.get_queue(queue_name)
    
    [queue.write(queue.new_message(json.load(i))) for i in ['file1.json', 'file2.json']]
    

    【讨论】:

    • 它抛出:回溯(最近一次调用最后):文件“some_cooljso.py”,第 14 行,在 [queue.write(queue.new_message(json.load(i))) for i in ['emp.json', 'emp2.​​json']] 文件“/usr/lib/python2.7/json/__init__.py”,第 286 行,在加载返回加载(fp.read(),AttributeError : 'str' 对象没有属性 'read'
    • 我需要在将文件放入 for 循环之前打开文件
    • 在依赖“副作用”的同时使用列表推导感觉很恶心。
    【解决方案2】:

    Boto 的 new_message() 调用需要一个字符串作为其参数。您的文件已经以字符串格式存储 JSON。您不需要 JSON 模块。只是不要忘记去掉你的行尾 - Windows (CRLF) 上的 \r\n 和 Unix (LF) 上的 \n

    但是,如果您有一个 JSON 对象,那就另当别论了。使用json.dumps 获取您的 JSON 对象并将其转储为字符串。

    From the boto (not version 3) docs on connect_to_region()

    At this point the variable conn will point to an SQSConnection object in the US-WEST-2 region. Bear in mind that just as any other AWS service, SQS is region-specific. In this example, the AWS access key and AWS secret key are passed in to the method explicitly. Alternatively, you can set the environment variables:
    
    AWS_ACCESS_KEY_ID - Your AWS Access Key ID
    AWS_SECRET_ACCESS_KEY - Your AWS Secret Access Key
    

    我在 python 2.7.12 和 boto(不是 boto 3)上对此进行了测试,并且成功了。

    import boto.sqs
    import sys
    
    # either use environment variables for your access keys, or the flags here
    conn = boto.sqs.connect_to_region("us-west-2", aws_access_key_id="the_key", aws_secret_access_key="the_secret_key")
    q = conn.get_queue('the_queue_name')
    
    if not q:
      print "unable to locate queue!  exiting..."
      sys.exit()
    
    for src_file in ['myfile1.json', 'myfile2.json']:
      with open(src_file, 'r') as json_file:
        for line in json_file:
          print "writing %s" % line
          q.write(q.new_message(line.rstrip('\r\n')))
    

    【讨论】:

      猜你喜欢
      • 2017-02-07
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 2012-03-09
      相关资源
      最近更新 更多