如何使用python在AWS Lambda中进行HTTP REST调用? [英] How to make a HTTP rest call in AWS lambda using python?

查看:91
本文介绍了如何使用python在AWS Lambda中进行HTTP REST调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要使用python进行http调用,我的方法是使用 requests .

To make an http call using python my way was to use requests.

但是 requests 并未安装在lambda上下文中.使用导入请求导致未找到模块错误.

But requests is not installed in lambda context. Using import requests resulted in module is not found error.

另一种方法是使用来自botocore.vendored导入请求的提供的库 .但是AWS不推荐使用此库.

The other way is to use the provided lib from botocore.vendored import requests. But this lib is deprecated by AWS.

我想避免将依赖项打包在我的lambda zip文件中.

I want to avoid to package dependencies within my lambda zip file.

在基于python的lambda中进行REST调用的最聪明的解决方案是什么?

What is the smartest solution to make a REST call in python based lambda?

推荐答案

解决方案1)

由于不赞成使用botocore.vendored导入请求中的 ,因此推荐的方法是安装依赖项.

Since from botocore.vendored import requests is deprecated the recomended way is to install your dependencies.

$ pip install requests

import requests
response = requests.get('https://...')

另请参阅. https://aws.amazon.com/de/blogs/developer/remove-the-vendored-version-of-requests-from-botocore/

但是您必须注意将依赖项打包到lambda zip中.

But you have to take care for packaging the dependencies within your lambda zip.

解决方案2)

我的首选解决方案是使用 urllib .它在您的lambda执行上下文中.

My preferred solution is to use urllib. It's within your lambda execution context.

https://repl.it/@SmaMa/DutifulChocolateApplicationprogrammer

import urllib.request
import json

res = urllib.request.urlopen(urllib.request.Request(
        url='http://asdfast.beobit.net/api/',
        headers={'Accept': 'application/json'},
        method='GET'),
    timeout=5)

print(res.status)
print(res.reason)
print(json.loads(res.read()))

解决方案3)

使用 http.client ,它也在lambda执行上下文中.

Using http.client, it's also within your lambda execution context.

https://repl.it/@SmaMa/ExoticUnsightlyAstrophysics

import http.client

connection = http.client.HTTPSConnection('fakerestapi.azurewebsites.net')
connection.request('GET', '/api/Books')

response = connection.getresponse()
print(response.read().decode())

这篇关于如何使用python在AWS Lambda中进行HTTP REST调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆