以下是我在嘗試測驗 Lambda 函式時遇到的錯誤
"errorMessage": "Unable to import module 'app': No module named 'requests'",
"errorType": "Runtime.ImportModuleError",
"requestId": "baef5cbe-c542-4ae0-9d3e-bda4ee80f0b9",
"stackTrace": []
}
這也是我的python代碼
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)
我注意到的一件事是 lambda 表示它支持最高版本為 3.9 的 python 并且我的代碼是使用 3.10.2 撰寫的,這可能是導致此錯誤的原因嗎?運行時設定為 3.9,我嘗試將其切換為 3.7 和 3.8,但我得到不同的錯誤,但我無法執行 3.10.2
我應該創建一個 docker 容器并在那里運行它嗎?這會幫助解決我的問題還是只是我的代碼有問題?
uj5u.com熱心網友回復:
您必須將requests庫與您的應用程式捆綁在一起。AWS 檔案詳細解釋了如何做到這一點。
您必須為 lambda 的每個依賴項都這樣做,或者如果您有很多依賴項,則使用lambda 容器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/430953.html
標籤:Python 亚马逊网络服务 码头工人 aws-lambda
上一篇:這個api網關ARN有什么問題?
下一篇:“errorMessage”:“無法匯入模塊'app':沒有名為'app'的模塊”,“errorType”:“Runtime.ImportModuleError
