Uploading file to AWS S3 through Chalice API call

后端 未结 1 923
不知归路
不知归路 2021-02-05 17:45

I\'m trying to upload a file to my S3 bucket through Chalice (I\'m playing around with it currently, still new to this). However, I can\'t seem to get it right.

I have A

相关标签:
1条回答
  • 2021-02-05 18:19

    I got it running and this works for me as app.py in an AWS Chalice project:

    from chalice import Chalice, Response
    import boto3
    
    app = Chalice(app_name='helloworld')
    
    BUCKET = 'mybucket'  # bucket name
    s3_client = boto3.client('s3')
    
    
    @app.route('/upload/{file_name}', methods=['PUT'],
               content_types=['application/octet-stream'])
    def upload_to_s3(file_name):
    
        # get raw body of PUT request
        body = app.current_request.raw_body
    
        # write body to tmp file
        tmp_file_name = '/tmp/' + file_name
        with open(tmp_file_name, 'wb') as tmp_file:
            tmp_file.write(body)
    
        # upload tmp file to s3 bucket
        s3_client.upload_file(tmp_file_name, BUCKET, file_name)
    
        return Response(body='upload successful: {}'.format(file_name),
                        status_code=200,
                        headers={'Content-Type': 'text/plain'})
    

    You can test this with curl and its --upload-file directly from the command line with:

    curl -X PUT https://YOUR_API_URL_HERE/upload/mypic.jpg --upload-file mypic.jpg --header "Content-Type:application/octet-stream"
    

    To get this running, you have to manually attach the policy to write to s3 to the role of your lambda function. This role is auto-generated by Chalice. Attach the policy (e.g. AmazonS3FullAccess) manually next to the existing policy in the AWS IAM web interface to the role created by your Chalice project.

    Things to mention:

    • You cannot write to the working directory /var/task/ of the Lambda functions, but you have some space at /tmp/, see this answer.
    • You have to specify the accepted content-type 'application/octet-stream' for the @app.route (and upload the file accordingly via curl).
    • HTTP PUT puts a file or resource at a specific URI, so to use PUT this file has to be uploaded to the API via HTTP.
    0 讨论(0)
提交回复
热议问题