【问题标题】:How to print the S3 key name in python如何在python中打印S3键名
【发布时间】:2021-08-19 06:45:05
【问题描述】:

我为所有新对象的 put 添加了 S3 触发器并调用 AWS Lambda。

我的 Lambda 是用 Python 3.8 编写的,用于解析关键对象和文件并获取文件名。

import urllib.parse
import boto3

print('Loading function')

s3 = boto3.client('s3')


def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
    try:
        print(key)

一旦我上传 mys3bucket/jsonfiles/2021/05/31/file.json

我的代码打印 jsonfiles/2021/05/31/file.json, 我想打印的是。

key1 as 2021/05/31/, omitting the jsonfiles prefix
and
key2 as file.json, printing just the file name.

我的代码应该是什么样的?

【问题讨论】:

    标签: python json amazon-s3 aws-lambda python-3.8


    【解决方案1】:

    获得key 后,进行一些字符串解析并从中获取所需的数据,

    >>> s = "mys3bucket/jsonfiles/2021/05/31/file.json"
    >>> s.split("jsonfiles/")
    ['mys3bucket/', '2021/05/31/file.json']
    >>> req = s.split("jsonfiles/")[1]
    >>> ind = req.rfind('/')
    >>> req[:ind]
    '2021/05/31'
    >>> req[ind + 1:]
    'file.json'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      相关资源
      最近更新 更多