使用boto3在S3中生成签名URL

mea*_*ari 6 amazon-s3 boto amazon-web-services boto3

在Boto中,我曾使用以下函数生成签名的URL.

import boto
conn = boto.connect_s3()
bucket = conn.get_bucket(bucket_name, validate=True)
key = bucket.get_key(key)
signed_url = key.generate_url(expires_in=3600)
Run Code Online (Sandbox Code Playgroud)

我如何在boto3中做同样的事情?
我搜索了boto3 GitHub 代码库但找不到对generate_url的单个引用.
功能名称是否已更改?

Joh*_*ein 13

生成预配URL:

import boto3
import requests

# Get the service client.
s3 = boto3.client('s3')

# Generate the URL to get 'key-name' from 'bucket-name'
url = s3.generate_presigned_url(
    ClientMethod='get_object',
    Params={
        'Bucket': 'bucket-name',
        'Key': 'key-name'
    }
)

# Use the URL to perform the GET operation. You can use any method you like
# to send the GET, but we will use requests here to keep things simple.
response = requests.get(url)
Run Code Online (Sandbox Code Playgroud)

功能参考: generate_presigned_url()

  • 尝试访问在普通浏览器中生成的 url 时,我收到错误“不支持您提供的授权机制 InvalidRequest” (3认同)
  • @TheGuardener 您应该_永远_在代码中添加您的访问密钥和秘密密钥。如果代码在 Amazon EC2 实例上运行,只需为该实例分配 IAM 角色即可。如果代码在您自己的计算机上运行,​​请使用 [AWS 命令​​行界面 (CLI)](http://aws.amazon.com/cli/) `aws configure` 命令将凭证存储在配置文件中。在这两种情况下,代码都会自动查找凭据。 (3认同)
  • 你好。我应该在这段代码中的哪里添加“access_key”、“secret_key”?我对此很陌生。我想它们是必需的。 (2认同)

小智 8

\n

当尝试访问普通浏览器中生成的 url \xe2\x80\x93 Aseem 2019 年 4 月 30 日 5:22 时,我收到错误 InvalidRequestThe授权机制不支持您提供的授权机制

\n
\n\n

由于没有太多信息,我假设您遇到签名版本问题,如果没有,也许它会帮助其他人!:P

\n\n

为此,您可以从 botocore 导入配置:-

\n\n
from botocore.client import Config\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后让客户端使用此配置并提供签名版本为“s3v4”

\n\n
s3 = boto3.client('s3', config=Config(signature_version='s3v4'))\n
Run Code Online (Sandbox Code Playgroud)\n