解决方法如下:
import boto3
def lambda_handler(event, context):
s3 = boto3.client('s3')
bucket_name = 'your-bucket-name'
file_name = 'your-file-name'
response = s3.get_object(Bucket=bucket_name, Key=file_name)
file_contents = response['Body'].read().decode('utf-8')
return {
'statusCode': 200,
'body': file_contents
}
import boto3
def create_rest_api():
client = boto3.client('apigateway')
# 创建REST API
api_name = 'MyAPI'
response = client.create_rest_api(
name=api_name,
description='My API'
)
api_id = response['id']
# 创建资源
response = client.create_resource(
restApiId=api_id,
parentId='root',
pathPart='read-file'
)
resource_id = response['id']
# 创建方法
response = client.put_method(
restApiId=api_id,
resourceId=resource_id,
httpMethod='GET',
authorizationType='NONE'
)
# 配置Lambda集成
uri = 'arn:aws:apigateway:your-region:lambda:path/2015-03-31/functions/your-lambda-function-arn/invocations'
response = client.put_integration(
restApiId=api_id,
resourceId=resource_id,
httpMethod='GET',
type='AWS',
integrationHttpMethod='POST',
uri=uri
)
# 部署API
response = client.create_deployment(
restApiId=api_id,
stageName='prod'
)
# 获取API的URL
url = f"https://{api_id}.execute-api.your-region.amazonaws.com/prod/read-file"
return url
# 创建API网关并获取URL
api_url = create_rest_api()
print(api_url)
这样,你就可以通过访问api_url
来从S3中读取文件了。