A toolkit for developing and deploying serverless Python code in AWS Lambda.

Overview

python-lambda logo

pypi pypi

Python-lambda is a toolset for developing and deploying serverless Python code in AWS Lambda.

A call for contributors

With python-lambda and pytube both continuing to gain momentum, I'm calling for contributors to help build out new features, review pull requests, fix bugs, and maintain overall code quality. If you're interested, please email me at nficano[at]gmail.com.

Description

AWS Lambda is a service that allows you to write Python, Java, or Node.js code that gets executed in response to events like http requests or files uploaded to S3.

Working with Lambda is relatively easy, but the process of bundling and deploying your code is not as simple as it could be.

The Python-Lambda library takes away the guess work of developing your Python-Lambda services by providing you a toolset to streamline the annoying parts.

Requirements

  • Python 2.7, >= 3.6 (At the time of writing this, these are the Python runtimes supported by AWS Lambda).
  • Pip (~8.1.1)
  • Virtualenv (~15.0.0)
  • Virtualenvwrapper (~4.7.1)

Getting Started

First, you must create an IAM Role on your AWS account called lambda_basic_execution with the LambdaBasicExecution policy attached.

On your computer, create a new virtualenv and project folder.

$ mkvirtualenv pylambda
(pylambda) $ mkdir pylambda

Next, download Python-Lambda using pip via pypi.

(pylambda) $ pip install python-lambda

From your pylambda directory, run the following to bootstrap your project.

(pylambda) $ lambda init

This will create the following files: event.json, __init__.py, service.py, and config.yaml.

Let's begin by opening config.yaml in the text editor of your choice. For the purpose of this tutorial, the only required information is aws_access_key_id and aws_secret_access_key. You can find these by logging into the AWS management console.

Next let's open service.py, in here you'll find the following function:

def handler(event, context):
    # Your code goes here!
    e = event.get('e')
    pi = event.get('pi')
    return e + pi

This is the handler function; this is the function AWS Lambda will invoke in response to an event. You will notice that in the sample code e and pi are values in a dict. AWS Lambda uses the event parameter to pass in event data to the handler.

So if, for example, your function is responding to an http request, event will be the POST JSON data and if your function returns something, the contents will be in your http response payload.

Next let's open the event.json file:

{
  "pi": 3.14,
  "e": 2.718
}

Here you'll find the values of e and pi that are being referenced in the sample code.

If you now try and run:

(pylambda) $ lambda invoke -v

You will get:

# 5.858
# execution time: 0.00000310s
# function execution timeout: 15s

As you probably put together, the lambda invoke command grabs the values stored in the event.json file and passes them to your function.

The event.json file should help you develop your Lambda service locally. You can specify an alternate event.json file by passing the --event-file=<filename>.json argument to lambda invoke.

When you're ready to deploy your code to Lambda simply run:

(pylambda) $ lambda deploy

The deploy script will evaluate your virtualenv and identify your project dependencies. It will package these up along with your handler function to a zip file that it then uploads to AWS Lambda.

You can now log into the AWS Lambda management console to verify the code deployed successfully.

Wiring to an API endpoint

If you're looking to develop a simple microservice you can easily wire your function up to an http endpoint.

Begin by navigating to your AWS Lambda management console and clicking on your function. Click the API Endpoints tab and click "Add API endpoint".

Under API endpoint type select "API Gateway".

Next change Method to POST and Security to "Open" and click submit (NOTE: you should secure this for use in production, open security is used for demo purposes).

At last you need to change the return value of the function to comply with the standard defined for the API Gateway endpoint, the function should now look like this:

def handler(event, context):
    # Your code goes here!
    e = event.get('e')
    pi = event.get('pi')
    return {
        "statusCode": 200,
        "headers": { "Content-Type": "application/json"},
        "body": e + pi
    }

Now try and run:

$ curl --header "Content-Type:application/json" \
       --request POST \
       --data '{"pi": 3.14, "e": 2.718}' \
       https://<API endpoint URL>
# 5.8580000000000005

Environment Variables

Lambda functions support environment variables. In order to set environment variables for your deployed code to use, you can configure them in config.yaml. To load the value for the environment variable at the time of deployment (instead of hard coding them in your configuration file), you can use local environment values (see 'env3' in example code below).

environment_variables:
  env1: foo
  env2: baz
  env3: ${LOCAL_ENVIRONMENT_VARIABLE_NAME}

This would create environment variables in the lambda instance upon deploy. If your functions don't need environment variables, simply leave this section out of your config.

Uploading to S3

You may find that you do not need the toolkit to fully deploy your Lambda or that your code bundle is too large to upload via the API. You can use the upload command to send the bundle to an S3 bucket of your choosing. Before doing this, you will need to set the following variables in config.yaml:

role: basic_s3_upload
bucket_name: 'example-bucket'
s3_key_prefix: 'path/to/file/'

Your role must have s3:PutObject permission on the bucket/key that you specify for the upload to work properly. Once you have that set, you can execute lambda upload to initiate the transfer.

Deploying via S3

You can also choose to use S3 as your source for Lambda deployments. This can be done by issuing lambda deploy-s3 with the same variables/AWS permissions you'd set for executing the upload command.

Development

Development of "python-lambda" is facilitated exclusively on GitHub. Contributions in the form of patches, tests and feature creation and/or requests are very welcome and highly encouraged. Please open an issue if this tool does not function as you'd expect.

Environment Setup

  1. Install pipenv
  2. Install direnv
  3. Install Precommit (optional but preferred)
  4. cd into the project and enter "direnv allow" when prompted. This will begin installing all the development dependancies.
  5. If you installed pre-commit, run pre-commit install inside the project directory to setup the githooks.

Releasing to Pypi

Once you pushed your chances to master, run one of the following:

# If you're installing a major release:
make deploy-major

# If you're installing a minor release:
make deploy-minor

# If you're installing a patch release:
make deploy-patch
Owner
Nick Ficano
Hi, I'm Nick! I develop software and live in Smithtown, New York.
Nick Ficano
Rick Astley Language is a rick roll oriented, dynamic, strong, esoteric programming language.

Rick Roll Language / Rick Astley Language A rick roll oriented, dynamic, strong, esoteric programming language. Prolegomenon The reasons that I made t

Rick Roll Programming Language 658 Jan 09, 2023
Blender Addon for Snapping a UV to a specific part of a Tilemap

UVGridSnapper A simple Blender Addon for easier texturing. A menu in the UV editor allows a square UV to be snapped to an Atlas texture, or Tilemap. P

2 Jul 17, 2022
A command line interface tool converting starknet warp transpiled outputs into readable cairo contracts.

warp-to-cairo warp-to-cairo is a simple tool converting starknet warp outputs (NethermindEth/warp) outputs into readable cairo contracts. The warp out

Michael K 5 Jun 10, 2022
A simple calculator made with tkinter.

Simple Calculator A simple calculator made with tkinter. Requirements None, only you need to have windows 😉 ...Enjoy! Installation Clone this reposit

Abhyush 2 Jan 11, 2022
An attempt at furthering Factorio Calculator to work in more general contexts.

factorio-optimizer Lets do Factorio Calculator but make it optimize. Why not use Factorio Calculator? Becuase factorio calculator is not general. The

Jonathan Woollett-Light 1 Jun 03, 2022
TallerStereoVision Convencion Python Chile 2021

TallerStereoVision Convencion Python Chile 2021 Taller Stereo Vision & Python PyCon.cl 2021 Instalación Se recomienta utilizar Virtual Environment pyt

2 Oct 20, 2022
Cairo hooks for pre-commit

pre-commit-cairo Cairo hooks for pre-commit. See pre-commit for more details Using pre-commit-cairo with pre-commit Add this to your .pre-commit-confi

Fran Algaba 16 Sep 21, 2022
Python bindings for `ign-msgs` and `ign-transport`

Python Ignition This project aims to provide Python bindings for ignition-msgs and ignition-transport. It is a work in progress... C++ and Python libr

Rhys Mainwaring 3 Nov 08, 2022
A simple program which gets a file(CSV/Excel) with tasks and creates different variants

TestMakerProject A simple program which gets a file(CSV/Excel) with tasks and creates different variants The main program is QTengine.py You only have

George 3 Nov 18, 2021
🪄 Auto-generate Streamlit UI from Pydantic Models and Dataclasses.

Streamlit Pydantic Auto-generate Streamlit UI elements from Pydantic models. Getting Started • Documentation • Support • Report a Bug • Contribution •

Lukas Masuch 103 Dec 25, 2022
Find your desired product in Digikala using this app.

Digikala Search Find your desired product in Digikala using this app. با این برنامه محصول مورد نظر خود را در دیجیکالا پیدا کنید. About me Full name: M

Matin Ardestani 17 Sep 15, 2022
Meaningful and minimalist release notes for developers

Managing manual release notes is hard. Therefore, everyone tends to generate release notes from commit messages. But, you won't get a meaningful release note at the end.

codezri 31 Dec 30, 2022
A random cat fact python module

A random cat fact python module

Fayas Noushad 4 Nov 28, 2021
Source code for Learn Programming: Python

This repository contains the source code of the game engine behind Learn Programming: Python. The two key files are game.py (the main source of the ga

Niema Moshiri 25 Apr 24, 2022
ToDo - A simple bot to keep track of things you need to do

ToDo A simple bot to keep track of things you need to do. Installation You will

3 Sep 18, 2022
a pull switch (or BYO button) that gets you out of video calls, quick

zoomout a pull switch (or BYO button) that gets you out of video calls, quick. As seen on Twitter System compatibility Tested on macOS Catalina (10.15

Brian Moore 422 Dec 30, 2022
Windows Task Manager with special features, written in Python.

Killer That damn Chrome ⬇ Download here · 👋 Join our discord Tired of trying to kill processes with the default Windows Task Manager? Selecting one b

Nathan Araújo 49 Jan 03, 2023
✔️ Create to-do lists to easily manage your ideas and work.

Todo List + Add task + Remove task + List completed task + List not completed task + Set clock task time + View task statistics by date Changelog v 1.

Abbas Ataei 30 Nov 28, 2022
tetrados is a tool to generate a density of states using the linear tetrahedron method from a band structure.

tetrados tetrados is a tool to generate a density of states using the linear tetrahedron method from a band structure. Currently, only VASP calculatio

Alex Ganose 1 Dec 21, 2021
A simple method to create strong password.

A simple method to create strong password.

1 Jan 23, 2022