boto3相关(aws dynamodb/s3/sqs python用法)

1、安装boto3

pip install boto3
python -m pip install boto3

2、dynamodb使用

官方例子:Amazon DynamoDB — Boto3 Docs 1.24.60 documentation

#! /usr/bin/env python
#coding=utf-8

import boto3
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError

table_name = "alan_test"

def print_item(item):
  # id
  id_ = item['id'] if 'id' in item else 0
  # name
  name_ = item['name'] if 'name' in item else ''
  # age
  age_ = item['age'] if 'age' in item else 0
  # class
  class_ = item['class'] if 'class' in item else 0
  print("id: %s, name: %s, age: %s, class: %s" % (id_, name_, age_, class_))

def run():
  # init dynamodb
  if(raw_input("init dynamodb: [y/n]") != 'y'):
    return
  session_args = {} # Found credentials in ~/.aws/credentials [default]
  #session_args = {'profile_name': 'alan'}
  #session_args = {
  #  'aws_access_key_id': 'A1b1C1',
  #  'aws_secret_access_key': 'A+B2c2',
  #}
  session = boto3.session.Session(**session_args)
  dynamodb = session.resource('dynamodb', region_name='cn-northwest-1') # region_name 使用哪个区域的aws服务
  # dynamodb = session.resource('dynamodb', region_name='cn-northwest-1', endpoint_url='http://localhost:8000') # endpoint_url dynamodb位置
  

  # list table
  if(raw_input("list table: [y/n]") != 'y'):
    return
  for table in dynamodb.tables.all():
    print(table.name)


  # create table
  if(raw_input("create table: [y/n]") != 'y'):
    return
  try:
    dynamodb.create_table(
        TableName=table_name, # 表名
        KeySchema=[ # 主键
            {
                'AttributeName': 'id',
                'KeyType': 'HASH'  # Partition key 分区键
            },
            {
                'AttributeName': 'name',
                'KeyType': 'RANGE'  # Sort key 排序键
            }
        ],
        AttributeDefinitions=[ # 主键数据类型
            {
                'AttributeName': 'id',
                'AttributeType': 'N' # Number
            },
            {
                'AttributeName': 'name',
                'AttributeType': 'S' # String
            },

        ],
        BillingMode='PAY_PER_REQUEST',
        Tags=[
            {
                "Key": "Owner",
                "Value": "alan"
            }
        ]
    )
    # Wait until the table exists.
    dynamodb.Table(table_name).meta.client.get_waiter(
        'table_exists').wait(TableName=table_name)
  except Exception, e:
    print('failed to create table [%s].' % table_name)


  # check table
  if(raw_input("check table: [y/n]") != 'y'):
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值