cloudbud
cloudbud

Reputation: 3288

get request failing in boto3 python 3.8 lambda

I am trying to write a lambda function in 3.8 version but I am getting error while doing a get requests

[ERROR] AttributeError: module 'botocore.vendored.requests' has no attribute 'get' Traceback (most recent call last):   File "/var/task/lambda_function.py"

import json
from botocore.vendored import requests

def lambda_handler(event, context):

    request = event['Records'][0]['cf']['request']
    print (request)
    print(request['headers'])
    token = request['headers']['cookie'][0]['value'].partition("=")[2]
    print (token)
    print(type(request['uri']))
    consumer_id = request['uri'].rpartition('/')[-1]
    print (consumer_id)

    #Take the token and send it somewhere
    token_response = requests.get(url = 'https://url/api/files/'  + consumer_id, params = {'token': token})
    print (token_response)

    return request

I tried following this blog https://aws.amazon.com/blogs/compute/upcoming-changes-to-the-python-sdk-in-aws-lambda/

but not able to identify which layer to add. Could anyone please help

Upvotes: 3

Views: 5107

Answers (3)

xxl
xxl

Reputation: 21

I found a solution on Python runtime 3.9, so this isn't guaranteed to work for any other versions. I do not claim that this is the best solution, but it worked for me and may point others towards a better solution as the currently available answers do not solve the problem.

  1. Create a local directory for your Lambda function code and dependencies.

  2. Create your Lambda function code in a file in your new local directory you made in step #1. Name it lambda_function.py:

    import requests
    from datetime import datetime
    
    def lambda_handler(event, context):
        # Your code goes here
        print(datetime.now())
        response = requests.get('https://api.example.com')
        return response.text
    
  3. Install the requests library in your project directory. This is important for Python runtime in AWS Lambda:

    pip install requests -t ./
    
  4. Compress your local directory into a ZIP file.

  5. Upload your ZIP file to the AWS Lambda function. Ensure your project contents are in the root of the default folder.

Upvotes: 0

40 hunnid messiah
40 hunnid messiah

Reputation: 21

You want to create a layer with a requests installed onto zip file before hand and then use import requests

Upvotes: 0

Marcin
Marcin

Reputation: 238957

According to the link you provided and assuming that request was correctly installed you should be using

import requests

instead of

from botocore.vendored import requests

Upvotes: 2

Related Questions