I am fairly new to AWS and I am having some issues. Here is my code:
from __future__ import print_function from urllib2 import Request, urlopen, URLError import requests import boto3 import json def lambda_handler(event, context): url = "https://globalcurrencies.xignite.com/xGlobalCurrencies.json/GetHistoricalRatesRange?Symbol=BTCUSD&PriceType=Mid&StartDate=01/01/2017&EndDate=10/27/2017&PeriodType=Daily&FixingTime=22:00&_token=some_token_xyz" response = requests.get(url).json() # print json.dumps(response, indent=4) # gives a syntax error return response
Name of the file is lambda_function.py; I have checked similar problems on stackoverflow and some mentioned that I have to change the file naming. But it didn't help. Here is how python method was named:
Here is the error I am getting: START RequestId: cf24e9be-bbef-11e7-97b4-d9b586307f3e Version: $LATEST Unable to import module 'lambda_function': No module named requests
And when try to print it gives me a syntax error. Sorry for the formatting. Any suggestions?
The Lambda runtimes for Python 3.8 and later do not include the 'requests' module.
To resolve this error, create a deployment package or Lambda layer that includes the libraries that you want to use in your Python code for Lambda. Important: Make sure that you put the library that you import for Python inside the /python folder.
requests is not a standard library in AWS lambda.
So two ways to solve this:
1- Import it from the Botocore libraries stack as: (Option to be deprecated after the answer was given)
from botocore.vendored import requests
Here there is a list of all the available libraries to import in lambda
2- Create a deployment package with virtualenv.
If you want to include libraries which are not part of Python's standard library, such as requests
, you can use lambda's layers.
1. Create the zip
This is a zip which contains all the libraries you want the lambda function to use. First, create a folder called python
:
$ mkdir python $ cd python
then, install the Python libraries you need in there. You can do this either with a single library:
$ pip install --target . requests
or with a list of libraries (requirements.txt)
$ pip install --target . -r requirements.txt
finally, zip up everything.
... in Bash:
$ zip -r dependencies.zip ../python
... in Powershell:
$ Compress-Archive -Path . -DestinationPath dependencies.zip
2. Create a layer
You can do this either in the AWS console or in the CLI. Follow these instructions.
3. Add the layer to the lambda function
You can do this either with the Add a layer
option in the lambda page, or in the CLI. Follow these instructions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With