If you're writing a Lambda function in Python, you may want to use a third-party library inside your Lambda function. However, Lambda does not allow you to install libraries using pip. This time, I will introduce a method that is useful in such a situation.
Specifically, use the file upload function provided by Lambda. This means that you can use the library from within your Lambda function by uploading a third-party library when you upload the file.
This time I'll try using requests, Python's HTTP library.
Please refer to the following article for the basic method of creating a Lambda function.
First, create a working directory. Let's call it workspace. After creating the directory, move into it.
$ mkdir workspace
$ cd workspace
Once inside the workspace, use pip to install the library. Do the following:
$ pip install requests -t .
You can specify the installation location of the library by adding the t option. This time, it is installed in the current directory (workspace).
After installing the library, it's time to write the Lambda function. The file name should be ** lambda_function.py ** and the function name should be ** lambda_handler **. Remember the file and function names for later use.
lambda_function.py
import requests
def lambda_handler(event, context):
res = requests.get("http://www.yahoo.co.jp/")
return res.status_code
The code looks like the above. The content is as simple as GET the top page of Yahoo and return the status code. If the page can be acquired normally, 200 will be returned as the status code.
>>> from lambda_function import lambda_handler
>>> lambda_handler(None, None)
200
>>>
Use the zip command to zip all the files in the workspace. The name of the file to be compressed is ** upload.zip **.
$ zip -r upload.zip *
After compressing with the zip command, upload the compressed file to Lambda. There is a "Code entry type" in the item "Lambda function code" in the function setting screen. The default is "Edit code inline", but select "Upload a .ZIP file" here. When you select it, the "Upload" button will appear, so upload the file you created earlier (upload.zip).
After uploading the file, set the function to be used in ** Handler **. Functions can be specified in the format "filename.functionname". The file name of the Lambda function created earlier was ** lambda_function **, and the function name was ** lambda_handler **, so specify "lambda_function.lambda_handler".
This completes the settings. Select the "Next" button and "Create function" button to create the function.
Try testing from the test screen. If the status code is returned, it is successful. Thank you for your hard work.
Recommended Posts