![](/img/trans.png)
[英]How to install external modules in a Python Lambda Function created by AWS CDK?
[英]How to call an external API or URL ( python code) in AWS lambda function?
下面提供了我用来在AWS Lambda中调用API的代码。 urlilb3 python库成功上传为zip文件夹。 但是当我尝试访问特定意图时,它显示
当我在AWS lambda(python 3.6)中包含API调用时,我得到了
“无法调用远程端点,或者它返回的响应无效”。
为什么会这样呢? 在python 3.6中包含API调用之前需要完成哪些先决条件。 我使用urllib3 python库并以zip文件夹上传。 还有其他需要做的事情吗?
def get_weather(session):
should_end_session = False
speech_output = " "
reprompt_text = ""
api = "some url ...."
http = urllib3.PoolManager()
response = http.request('GET',api)
weather_status = json.loads(response.data.decode('utf-8'))
for weather in weather_status:
final_weather = weather["WeatherText"]
return build_response(session_attributes, build_speechlet_response(speech_output, reprompt_text, should_end_session))
尝试打印response.data,以便您可以在日志中看到它。 那可能会给你一个线索。 我还将尝试切换到Python请求而不是URLLib3。 您可能还需要根据要调用的API的实现来设置内容类型。
from __future__ import print_function
import json
from botocore.vendored import requests
def lambda_handler(event, context):
print('received request: ' + str(event))
doctor_intent = event['currentIntent']['slots']['doctor']
email_intent = event['currentIntent']['slots']['email']
print(doctor_intent, email_intent)
print(type(doctor_intent), type(email_intent))
utf8string = doctor_intent.encode("utf-8")
utf8string1 = email_intent.encode("utf-8")
print(type(utf8string))
print(type(utf8string1))
car1 = {"business_name": utf8string , "customer_email": utf8string1 }
r = requests.post('https://postgresheroku.herokuapp.com/update',
json=car1)
#print ("JSON : ", r.json())
print(r.json())
data = str(r.json())
print(type(data))
return {
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": "Thank you for booking appointment with {doctor}
{response}".format(doctor=doctor_intent,response=data)
}
}
}
场景:使用第三方API获取天气
import urllib3
def get_weather():
api = "some url ...."
http = urllib3.PoolManager()
response = http.request('GET',api)
weather_status = json.loads(response.data.decode('utf-8'))
for weather in weather_status:
final_weather = weather["WeatherText"] ## The attribute "WeatherText" will varies depending upon the weather API you are using.
return final_weather
get_weather() # simple function call
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.