[英]Import Query String from AWS API Gateway into Lambda Python Function
[英]Trying to query an API from AWS Lambda
我正在嘗試通過發送帶有 IP 的 GET 請求來查詢返回 IP 地理位置信息的開源 API。
我正在使用包含 IP 地址(位於key1
中)的密鑰測試代碼。 我正在嘗試在發送請求后獲取信息,但我不確定我做錯了什么。
我嘗試將 IP 附加到 url 的末尾(如 geoip API 指示),但我不斷收到語法錯誤。
import json
from botocore.vendored import requests
def lambda_handler(resp, requests, event):
event = event.key1
url = "https://freegeoip.app/json/" +event
headers = {
'accept': "application/json",
'content-type': "application/json"
}
response = requests.request("GET", url, headers=headers)
print(response.text)
我的代碼在下面的常規 python 語法中工作,只是不知道如何讓它與 lambda 一起工作
import requests
userIP = '54.81.183.174'
def theFunction():
url = "https://freegeoip.app/json/" + userIP
headers = {
'accept': "application/json",
'content-type': "application/json"
}
response = requests.request("GET", url, headers=headers)
print(response.text)
theFunction()
您的代碼正在使用requests
模塊,該模塊未隨 AWS Lambda 一起安裝。
You can package it for use with an AWS Lambda function (see python - Cannot use Requests-Module on AWS Lambda - Stack Overflow ), but it is simpler to use urllib
, which is part of standard Python3.
這是一些有效的代碼:
import urllib.request
import json
def lambda_handler(event, context):
ip = event['ip']
with urllib.request.urlopen("https://freegeoip.app/json/" + ip) as f:
data = json.loads(f.read())
print(data)
print(data['city'])
您可以使用測試數據觸發它:
{
"ip": "54.81.183.174"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.