问题
I've got a Python script for an AWS Lambda function that does HTTP POST requests to another endpoint. Since Python's urllib2.request
, https://docs.python.org/2/library/urllib2.html, can only handle data in the standard application/x-www-form-urlencoded
format and I want to post JSON data, I used the Requests library, https://pypi.org/project/requests/2.7.0/.
That Requests library wasn't available at AWS Lambda in the Python runtime environment, so had to be imported via from botocore.vendored import requests
. So far, so good.
Today, I get a deprecation warning on that:
DeprecationWarning: You are using the post() function from 'botocore.vendored.requests'.
This is not a public API in botocore and will be removed in the future.
Additionally, this version of requests is out of date. We recommend you install the
requests package, 'import requests' directly, and use the requests.post() function instead.
This was mentioned in this blog post from AWS too: https://aws.amazon.com/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/.
Unfortunately, changing from botocore.vendored import requests
into import requests
results in the following error:
No module named 'requests'
Why is requests
not available for the Python runtime at AWS Lambda? And how can I use / import it?
回答1:
Specify the plugin in serverless.yml
plugins:
- serverless-python-requirements
At the directory root create file requirements.txt
requirements.txt
requests==2.22.0
This will install the requests and packages mentioned.
回答2:
requests is NOT part of core python. See https://docs.aws.amazon.com/en_pv/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html about packaging a Lambda having external dependencies (in your case the requests library)
回答3:
I succeeded sending HTTP POST requests using the urllib3
library, which is available at AWS Lambda without the requirements for additional installation instructions.
import urllib3
http = urllib3.PoolManager()
response = http.request('POST',
url,
body = json.dumps(some_data_structure),
headers = {'Content-Type': 'application/json'},
retries = False)
回答4:
pip install requests
and then import requests
to use.
来源:https://stackoverflow.com/questions/58445984/python-at-aws-lambda-requests-from-botocore-vendored-deprecated-but-request