Here are the errors I got when trying to test my Lambda function
"errorMessage": "Unable to import module 'app': No module named 'requests'",
"errorType": "Runtime.ImportModuleError",
"requestId": "baef5cbe-c542-4ae0-9d3e-bda4ee80f0b9",
"stackTrace": []
}
Here is also my python code
import requests
import os
import smtplib
from datetime import datetime
# https://openweathermap.org/api/one-call-api
# empire state building
lat = '40.75009231913161'
lon = '-73.98638285425646'
exclude = 'minutely,hourly,alerts'
url = (
'https://api.openweathermap.org/data/2.5/onecall?'
'lat={lat}&lon={lon}&exclude={exclude}&appid={API_key}&units=imperial'
)
if os.path.isfile('.env'):
from dotenv import load_dotenv
load_dotenv()
def __send_email(msg: str) -> None:
gmail_user = os.getenv('EMAIL_USER')
gmail_password = os.getenv('EMAIL_PASSWORD')
# Create Email
mail_from = gmail_user
mail_to = gmail_user
mail_subject = f'Weather Today {datetime.today().strftime("%m/%d/%Y")}'
mail_message = f'Subject: {mail_subject}\n\n{msg}'
# Send Email
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(gmail_user, gmail_password)
server.sendmail(mail_from, mail_to, mail_message)
server.close()
def handler(event, context):
response = requests.get(url.format(
lat=lat,
lon=lon,
exclude=exclude,
API_key=os.getenv('WEATHER_API_KEY')
))
data = response.json()
rain_conditions = ['rain', 'thunderstorm', 'drizzle']
snow_conditions = ['snow']
today_weather = data['daily'][0]['weather'][0]['main'].lower()
if today_weather in rain_conditions:
msg = 'Pack an umbrella!'
elif today_weather in snow_conditions:
msg = 'Pack your snow boots!'
else:
msg = 'Clear skies today!'
__send_email(msg)
handler(None, None)
One thing I noticed is that lambda says it supports up to python version 3.9 and my code was written using 3.10.2, is that a possible reason for this error? The runtime is set to 3.9 and I tried switching it to 3.7 and 3.8 and I just get different errors, but I'm unable to do 3.10.2
Should I just create a docker container and run it on there? Would that help solve my issue or is it just something wrong with my code?
CodePudding user response:
You have to bundle requests
library with your application. AWS docs explain in details how to do it.
You have to do it for every dependency of your lambda, or use lambda containers if you have lots of dependencies.