尝试从AWS Lambda查询API

我正在尝试查询一个开源API,该API通过发送带有IP的GET请求来返回IP地理位置信息。

我正在使用包含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",headers=headers)

  print(response.text)

theFunction()
daiandy001 回答:尝试从AWS Lambda查询API

您的代码正在使用requests模块,该模块未随AWS Lambda一起安装。

您可以将其打包以与AWS Lambda函数一起使用(请参阅python - Cannot use Requests-Module on AWS Lambda - Stack Overflow),但是使用urllib(它是标准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"
}
本文链接:https://www.f2er.com/3131398.html

大家都在问