Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python in AWS Lambda: "module 'requests' has no attribute 'get'"

I'm currently trying to use the Python requests module in an AWS Lambda function. Here are the steps that I've taken so far:

I created a new directory, and installed the requests module in it, using the command pip3 install requests -t .

I then wrote a simple Python script, test_requests.py, within the directory, which looks like this:

import requests
def my_handler(event, context):
    r = requests.get("http://google.com")
    return r

I zipped the entire directory, including the requests module, using zip test_requests.zip *

I then uploaded the function to AWS with the following command: aws lambda create-function --function-name test_requests --zip-file fileb://test_requests.zip --handler test_requests.my_handler --runtime python3.6 --region us-east-1 --role xxxMY_ROLE_ARNxxx

Finally, I invoked the function with this command: aws lambda invoke --function-name test-requests --payload {} --region us-east-1 lambda_response.txt

When I made this command, I got an unhandled exception back from Lambda. The output file, lambda_response.txt contained this: {"errorMessage": "module 'requests' has no attribute 'get'", "errorType": "AttributeError", "stackTrace": [["/var/task/test_requests.py", 3, "my_handler", "r = requests.get('http://google.com')"]]}

I've seen several questions regarding AWS lambda, and being unable to import modules properly. Those questions all seemed focused around lambda being unable to find the module. In this case, it seems that lambda has found requests, but is unable to access all of its attributes.

like image 949
Belgabad Avatar asked Jul 23 '17 14:07

Belgabad


People also ask

Does Python lambda have requests?

Update (April 26, 2022): The Lambda runtimes for Python 3.8 and later do not include the 'requests' module.

Can I use Python packages with AWS Lambda?

Lambda supports Python, which is a great option if you've got experience using it. However, one of the downsides to Lambda is that by default you won't be able to import your trusted packages, like Pandas. I'm going to show you the easiest way of importing any package you need for your Lambda function.


1 Answers

I figured out what I was doing wrong. zip test.zip * only zips the top level of the directory structure. I needed the -r flag in order to capture everything.

like image 99
Belgabad Avatar answered Nov 13 '22 14:11

Belgabad