• Stars
    star
    1,108
  • Rank 41,912 (Top 0.9 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⚡️🐍📦 Serverless plugin to bundle Python packages

Serverless Python Requirements

serverless Github Actions npm code style: prettier

A Serverless Framework plugin to automatically bundle dependencies from requirements.txt and make them available in your PYTHONPATH.


Originally developed by Capital One, now maintained in scope of Serverless, Inc

Capital One considers itself the bank a technology company would build. It's delivering best-in-class innovation so that its millions of customers can manage their finances with ease. Capital One is all-in on the cloud and is a leader in the adoption of open source, RESTful APIs, microservices and containers. We build our own products and release them with a speed and agility that allows us to get new customer experiences to market quickly. Our engineers use artificial intelligence and machine learning to transform real-time data, software and algorithms into the future of finance, reimagined.


Install

sls plugin install -n serverless-python-requirements

This will automatically add the plugin to your project's package.json and the plugins section of its serverless.yml. That's all that's needed for basic use! The plugin will now bundle your python dependencies specified in your requirements.txt or Pipfile when you run sls deploy.

For a more in depth introduction on how to use this plugin, check out this post on the Serverless Blog

If you're on a mac, check out these notes about using python installed by brew.

Cross compiling

Compiling non-pure-Python modules or fetching their manylinux wheels is supported on non-linux OSs via the use of Docker and official AWS build images. To enable docker usage, add the following to your serverless.yml:

custom:
  pythonRequirements:
    dockerizePip: true

The dockerizePip option supports a special case in addition to booleans of 'non-linux' which makes it dockerize only on non-linux environments.

To utilize your own Docker container instead of the default, add the following to your serverless.yml:

custom:
  pythonRequirements:
    dockerImage: <image name>:tag

This must be the full image name and tag to use, including the runtime specific tag if applicable.

Alternatively, you can define your Docker image in your own Dockerfile and add the following to your serverless.yml:

custom:
  pythonRequirements:
    dockerFile: ./path/to/Dockerfile

With Dockerfile the path to the Dockerfile that must be in the current folder (or a subfolder). Please note the dockerImage and the dockerFile are mutually exclusive.

To install requirements from private git repositories, add the following to your serverless.yml:

custom:
  pythonRequirements:
    dockerizePip: true
    dockerSsh: true

The dockerSsh option will mount your $HOME/.ssh/id_rsa and $HOME/.ssh/known_hosts as a volume in the docker container.

In case you want to use a different key, you can specify the path (absolute) to it through dockerPrivateKey option:

custom:
  pythonRequirements:
    dockerizePip: true
    dockerSsh: true
    dockerPrivateKey: /home/.ssh/id_ed25519

If your SSH key is password protected, you can use ssh-agent because $SSH_AUTH_SOCK is also mounted & the env var is set. It is important that the host of your private repositories has already been added in your $HOME/.ssh/known_hosts file, as the install process will fail otherwise due to host authenticity failure.

You can also pass environment variables to docker by specifying them in dockerEnv option:

custom:
  pythonRequirements:
    dockerEnv:
      - https_proxy

🏁 Windows notes

🍰 Pipenv support

Requires pipenv in version 2022-04-08 or higher.

If you include a Pipfile and have pipenv installed, this will use pipenv to generate requirements instead of a requirements.txt. It is fully compatible with all options such as zip and dockerizePip. If you don't want this plugin to generate it for you, set the following option:

custom:
  pythonRequirements:
    usePipenv: false

📝 Poetry support

If you include a pyproject.toml and have poetry installed instead of a requirements.txt this will use poetry export --without-hashes -f requirements.txt -o requirements.txt --with-credentials to generate them. It is fully compatible with all options such as zip and dockerizePip. If you don't want this plugin to generate it for you, set the following option:

custom:
  pythonRequirements:
    usePoetry: false

Be aware that if no poetry.lock file is present, a new one will be generated on the fly. To help having predictable builds, you can set the requirePoetryLockFile flag to true to throw an error when poetry.lock is missing.

custom:
  pythonRequirements:
    requirePoetryLockFile: false

If your Poetry configuration includes custom dependency groups, they will not be installed automatically. To include them in the deployment package, use the poetryWithGroups, poetryWithoutGroups and poetryOnlyGroups options which wrap poetry export's --with, --without and --only parameters.

custom:
  pythonRequirements:
    poetryWithGroups:
      - internal_dependencies
      - lambda_dependencies

Poetry with git dependencies

Poetry by default generates the exported requirements.txt file with -e and that breaks pip with -t parameter (used to install all requirements in a specific folder). In order to fix that we remove all -e from the generated file but, for that to work you need to add the git dependencies in a specific way.

Instead of:

[tool.poetry.dependencies]
bottle = {git = "[email protected]/bottlepy/bottle.git", tag = "0.12.16"}

Use:

[tool.poetry.dependencies]
bottle = {git = "https://[email protected]/bottlepy/bottle.git", tag = "0.12.16"}

Or, if you have an SSH key configured:

[tool.poetry.dependencies]
bottle = {git = "ssh://[email protected]/bottlepy/bottle.git", tag = "0.12.16"}

Dealing with Lambda's size limitations

To help deal with potentially large dependencies (for example: numpy, scipy and scikit-learn) there is support for compressing the libraries. This does require a minor change to your code to decompress them. To enable this add the following to your serverless.yml:

custom:
  pythonRequirements:
    zip: true

and add this to your handler module before any code that imports your deps:

try:
  import unzip_requirements
except ImportError:
  pass

Slim Package

Works on non 'win32' environments: Docker, WSL are included To remove the tests, information and caches from the installed packages, enable the slim option. This will: strip the .so files, remove __pycache__ and dist-info directories as well as .pyc and .pyo files.

custom:
  pythonRequirements:
    slim: true

Custom Removal Patterns

To specify additional directories to remove from the installed packages, define a list of patterns in the serverless config using the slimPatterns option and glob syntax. These patterns will be added to the default ones (**/*.py[c|o], **/__pycache__*, **/*.dist-info*). Note, the glob syntax matches against whole paths, so to match a file in any directory, start your pattern with **/.

custom:
  pythonRequirements:
    slim: true
    slimPatterns:
      - '**/*.egg-info*'

To overwrite the default patterns set the option slimPatternsAppendDefaults to false (true by default).

custom:
  pythonRequirements:
    slim: true
    slimPatternsAppendDefaults: false
    slimPatterns:
      - '**/*.egg-info*'

This will remove all folders within the installed requirements that match the names in slimPatterns

Option not to strip binaries

In some cases, stripping binaries leads to problems like "ELF load command address/offset not properly aligned", even when done in the Docker environment. You can still slim down the package without *.so files with:

custom:
  pythonRequirements:
    slim: true
    strip: false

Lambda Layer

Another method for dealing with large dependencies is to put them into a Lambda Layer. Simply add the layer option to the configuration.

custom:
  pythonRequirements:
    layer: true

The requirements will be zipped up and a layer will be created automatically. Now just add the reference to the functions that will use the layer.

functions:
  hello:
    handler: handler.hello
    layers:
      - Ref: PythonRequirementsLambdaLayer

If the layer requires additional or custom configuration, add them onto the layer option.

custom:
  pythonRequirements:
    layer:
      name: ${self:provider.stage}-layerName
      description: Python requirements lambda layer
      compatibleRuntimes:
        - python3.7
      licenseInfo: GPLv3
      allowedAccounts:
        - '*'

Omitting Packages

You can omit a package from deployment with the noDeploy option. Note that dependencies of omitted packages must explicitly be omitted too.

This example makes it instead omit pytest:

custom:
  pythonRequirements:
    noDeploy:
      - pytest

Extra Config Options

Caching

You can enable two kinds of caching with this plugin which are currently both ENABLED by default. First, a download cache that will cache downloads that pip needs to compile the packages. And second, a what we call "static caching" which caches output of pip after compiling everything for your requirements file. Since generally requirements.txt files rarely change, you will often see large amounts of speed improvements when enabling the static cache feature. These caches will be shared between all your projects if no custom cacheLocation is specified (see below).

Please note: This has replaced the previously recommended usage of "--cache-dir" in the pipCmdExtraArgs

custom:
  pythonRequirements:
    useDownloadCache: true
    useStaticCache: true

Other caching options

There are two additional options related to caching. You can specify where in your system that this plugin caches with the cacheLocation option. By default it will figure out automatically where based on your username and your OS to store the cache via the appdirectory module. Additionally, you can specify how many max static caches to store with staticCacheMaxVersions, as a simple attempt to limit disk space usage for caching. This is DISABLED (set to 0) by default. Example:

custom:
  pythonRequirements:
    useStaticCache: true
    useDownloadCache: true
    cacheLocation: '/home/user/.my_cache_goes_here'
    staticCacheMaxVersions: 10

Extra pip arguments

You can specify extra arguments supported by pip to be passed to pip like this:

custom:
  pythonRequirements:
    pipCmdExtraArgs:
      - --compile

Extra Docker arguments

You can specify extra arguments to be passed to docker build during the build step, and docker run during the dockerized pip install step:

custom:
  pythonRequirements:
    dockerizePip: true
    dockerBuildCmdExtraArgs: ['--build-arg', 'MY_GREAT_ARG=123']
    dockerRunCmdExtraArgs: ['-v', '${env:PWD}:/my-app']

Customize requirements file name

Some pip workflows involve using requirements files not named requirements.txt. To support these, this plugin has the following option:

custom:
  pythonRequirements:
    fileName: requirements-prod.txt

Per-function requirements

Note: this feature does not work with Pipenv/Poetry, it requires requirements.txt files for your Python modules.

If you have different python functions, with different sets of requirements, you can avoid including all the unecessary dependencies of your functions by using the following structure:

├── serverless.yml
├── function1
│      ├── requirements.txt
│      └── index.py
└── function2
       ├── requirements.txt
       └── index.py

With the content of your serverless.yml containing:

package:
  individually: true

functions:
  func1:
    handler: index.handler
    module: function1
  func2:
    handler: index.handler
    module: function2

The result is 2 zip archives, with only the requirements for function1 in the first one, and only the requirements for function2 in the second one.

Quick notes on the config file:

  • The module field must be used to tell the plugin where to find the requirements.txt file for each function.
  • The handler field must not be prefixed by the folder name (already known through module) as the root of the zip artifact is already the path to your function.

Customize Python executable

Sometimes your Python executable isn't available on your $PATH as python2.7 or python3.6 (for example, windows or using pyenv). To support this, this plugin has the following option:

custom:
  pythonRequirements:
    pythonBin: /opt/python3.6/bin/python

Vendor library directory

For certain libraries, default packaging produces too large an installation, even when zipping. In those cases it may be necessary to tailor make a version of the module. In that case you can store them in a directory and use the vendor option, and the plugin will copy them along with all the other dependencies to install:

custom:
  pythonRequirements:
    vendor: ./vendored-libraries
functions:
  hello:
    handler: hello.handler
    vendor: ./hello-vendor # The option is also available at the function level

Manual invocations

The .requirements and requirements.zip(if using zip support) files are left behind to speed things up on subsequent deploys. To clean them up, run sls requirements clean. You can also create them (and unzip_requirements if using zip support) manually with sls requirements install.

Invalidate requirements caches on package

If you are using your own Python library, you have to cleanup .requirements on any update. You can use the following option to cleanup .requirements everytime you package.

custom:
  pythonRequirements:
    invalidateCaches: true

🍎🍺🐍 Mac Brew installed Python notes

Brew wilfully breaks the --target option with no seeming intention to fix it which causes issues since this uses that option. There are a few easy workarounds for this:

OR

  • Create a virtualenv and activate it while using serverless.

OR

Also, brew seems to cause issues with pipenv, so make sure you install pipenv using pip.

🏁 Windows dockerizePip notes

For usage of dockerizePip on Windows do Step 1 only if running serverless on windows, or do both Step 1 & 2 if running serverless inside WSL.

  1. Enabling shared volume in Windows Docker Taskbar settings
  2. Installing the Docker client on Windows Subsystem for Linux (Ubuntu)

Native Code Dependencies During Build

Some Python packages require extra OS dependencies to build successfully. To deal with this, replace the default image with a Dockerfile like:

FROM public.ecr.aws/sam/build-python3.9

# Install your dependencies
RUN yum -y install mysql-devel

Then update your serverless.yml:

custom:
  pythonRequirements:
    dockerFile: Dockerfile

Native Code Dependencies During Runtime

Some Python packages require extra OS libraries (*.so files) at runtime. You need to manually include these files in the root directory of your Serverless package. The simplest way to do this is to use the dockerExtraFiles option.

For instance, the mysqlclient package requires libmysqlclient.so.1020. If you use the Dockerfile from the previous section, add an item to the dockerExtraFiles option in your serverless.yml:

custom:
  pythonRequirements:
    dockerExtraFiles:
      - /usr/lib64/mysql57/libmysqlclient.so.1020

Then verify the library gets included in your package:

sls package
zipinfo .serverless/xxx.zip

If you can't see the library, you might need to adjust your package include/exclude configuration in serverless.yml.

Optimising packaging time

If you wish to exclude most of the files in your project, and only include the source files of your lambdas and their dependencies you may well use an approach like this:

package:
  individually: false
  include:
    - './src/lambda_one/**'
    - './src/lambda_two/**'
  exclude:
    - '**'

This will be very slow. Serverless adds a default "&ast;&ast;" include. If you are using the cacheLocation parameter to this plugin, this will result in all of the cached files' names being loaded and then subsequently discarded because of the exclude pattern. To avoid this happening you can add a negated include pattern, as is observed in serverless/serverless#5825.

Use this approach instead:

package:
  individually: false
  include:
    - '!./**'
    - './src/lambda_one/**'
    - './src/lambda_two/**'
  exclude:
    - '**'

Contributors

More Repositories

1

serverless

⚡ Serverless Framework – Use AWS Lambda and other managed cloud services to build apps that auto-scale, cost nothing when idle, and boast radically low maintenance.
JavaScript
46,101
star
2

examples

Serverless Examples – A collection of boilerplates and examples of serverless architectures built with the Serverless Framework on AWS Lambda, Microsoft Azure, Google Cloud Functions, and more.
JavaScript
11,353
star
3

serverless-graphql

Serverless GraphQL Examples for AWS AppSync and Apollo
JavaScript
2,720
star
4

components

The Serverless Framework's new infrastructure provisioning technology — Build, compose, & deploy serverless apps in seconds...
JavaScript
2,306
star
5

event-gateway

React to any event with serverless functions across clouds
Go
1,647
star
6

plugins

Serverless Plugins – Extend the Serverless Framework with these community driven plugins –
JavaScript
970
star
7

aws-ai-stack

AWS AI Stack – A ready-to-use, full-stack boilerplate project for building serverless AI applications on AWS
JavaScript
911
star
8

serverless-graphql-blog

A Serverless Blog leveraging GraphQL to offer a REST API with only 1 endpoint using Serverless v0.5
JavaScript
793
star
9

serverless-plugin-typescript

Serverless plugin for zero-config Typescript support
TypeScript
776
star
10

github-action

⚡:octocat: A Github Action for deploying with the Serverless Framework
Dockerfile
642
star
11

scope

🔭 Scope - Create a birdeye's view of your Github project and embed on your site
JavaScript
456
star
12

guide

Serverless Guide - An open-source definitive guide to serverless architectures.
Shell
439
star
13

serverless-kubeless

This plugin enables support for Kubeless within the Serverless Framework.
JavaScript
302
star
14

serverless-google-cloudfunctions

Serverless Google Cloud Functions Plugin – Adds Google Cloud Functions support to the Serverless Framework
JavaScript
272
star
15

serverless-azure-functions

Serverless Azure Functions Plugin – Add Azure Functions support to the Serverless Framework
TypeScript
266
star
16

post-scheduler

Schedule posts & content updates for static websites (Jekyll, Hugo, Gatsby, Phenomic etc)
JavaScript
191
star
17

serverless-starter

A boilerplate for new Serverless Projects
JavaScript
190
star
18

blog

serverless.com/blog – Posts from the Serverless community & core team. Contributions welcome!
JavaScript
183
star
19

serverless-client-s3

A plugin to deploy front-end assets to S3 via the Serverless Framework
JavaScript
171
star
20

serverless-websockets-plugin

Websocket support for Serverless Framework on AWS
JavaScript
149
star
21

serverless-openwhisk

Adds Apache OpenWhisk support to the Serverless Framework!
JavaScript
143
star
22

typescript

TypeScript definitions for Serverless Framework service configuration
TypeScript
140
star
23

serverless-slackbot

[Deprecated] A Serverless Module to create your own SlackBot without servers/websockets via Slash Commands
JavaScript
135
star
24

cloud

Serverless Cloud makes building, deploying, and managing serverless applications easier and more accessible to everyone.
HTML
112
star
25

compose

Orchestrate Serverless Framework in monorepos
JavaScript
109
star
26

event-gateway-example

JavaScript
104
star
27

serverless-optimizer-plugin

Serverless Optimizer Plugin: Optimizers for reducing Lambda file sizes and improving their performance -
JavaScript
102
star
28

enterprise

Documentation for the Serverless Framework Enterprise Edition –
95
star
29

multicloud

The serverless @multicloud library provides an easy way to write your serverless handlers 1 time and deploy them to multiple cloud providers include Azure & AWS.
TypeScript
90
star
30

aws-event-mocks

JavaScript
83
star
31

emulator

Serverless Emulator which lets you run serverless functions locally
JavaScript
78
star
32

serverless-local-schedule

⚡️🗺️⏰ Schedule AWS CloudWatch Event based invocations in local time(with DST support!)
JavaScript
72
star
33

event-mocks

TypeScript
72
star
34

fdk

This library is deprecated. Please use https://github.com/serverless/event-gateway-sdk instead.
JavaScript
69
star
35

serverless-open-runtime

WIP - An extensible, community-driven, open-runtime for serverless compute
Go
68
star
36

serverless-runtime-babel

Babel runtime for v.0.5 of the Serverless Framework
JavaScript
68
star
37

forms-service

Serverless Forms Service to collect form data with Admin UI
JavaScript
66
star
38

serverless-secrets-plugin

JavaScript
66
star
39

serverless-golang

Serverless Template for Golang
Go
64
star
40

serverless-tencent

⚡️ 🐧 Serverless Tencent CLI 及中文讨论社区
JavaScript
63
star
41

serverless-slack

A Serverless Module featuring pre-written Slack functions from authorization to slash commands!
JavaScript
49
star
42

dashboard-plugin

The Serverless Framework Dashboard plugin
JavaScript
49
star
43

event-gateway-getting-started

Walkthrough application for using the Event Gateway. -- https://www.serverless.com
JavaScript
48
star
44

workshop

A complete full-stack application and walkthrough for learning the features of the Serverless Framework.
CSS
45
star
45

desktop

A native GUI application that makes it easy to explore and test Serverless Framework applications built on AWS Lambda.
45
star
46

serverless-swagger-plugin

JavaScript
44
star
47

serverless-meta-sync

Secure syncing of serverless project meta data across teams
JavaScript
44
star
48

event-gateway-sdk

Event Gateway JavaScript SDK
JavaScript
43
star
49

safeguards-plugin

Serverless Framework Plugin to enforce safeguard policies
JavaScript
33
star
50

serverless-graphql-relay

Serverless GraphQL Boilerplate using Relay – Ready to be deployed to production within minutes …
JavaScript
32
star
51

utils

General serverless utilities
JavaScript
29
star
52

serverless-event-gateway-plugin

Event Gateway plugin for Serverless Framework
JavaScript
28
star
53

eslint-config

Common ESLint & Prettier config for Serverless projects
JavaScript
27
star
54

serverless-knative

Serverless Knative Provider Plugin – Adds Knative to the Serverless Framework
JavaScript
25
star
55

serverless-plugin-boilerplate

A Starter Project to help you build Plugins for the Serverless Framework -
JavaScript
24
star
56

dashboard

JavaScript
24
star
57

fullstack-course

The entire fullstack application course as seen on serverless.com/learn
JavaScript
24
star
58

serverless-babel-plugin

A Serverless plugin to compile your JavaScript code with Babel before deployment
JavaScript
23
star
59

serverless-plugin-log-retention

Control the retention of your serverless function's cloudwatch logs.
JavaScript
20
star
60

cloud-computing-conferences

A curated list of all the best cloud computing conferences happening in 2019! Check here to find a serverless or cloud event happening near you.
18
star
61

event-gateway-workshop

Learn what the Event Gateway is, how it works and build your first event-driven multi-cloud application!
JavaScript
18
star
62

fdk-tmp

The Serverless Function Development Kit (FDK)
JavaScript
18
star
63

aws-sdk-extra

The AWS SDK + a handful of extra convenience methods.
JavaScript
18
star
64

platform-sdk

Serverless Platform SDK
JavaScript
17
star
65

meetups

Want to start a Serverless usergroup? We can help you get started and be an official Serverless Usergroup. Join us to be part of the family of many Serverless Usergroups across the world.
17
star
66

boilerplate-googlecloudfunctions-nodejs

A Serverless Framework Boilerplate for Google Cloud Functions support in Node.js
JavaScript
15
star
67

cli

Serverless Components CLI
JavaScript
14
star
68

serverless-helpers-py

Python
12
star
69

tutorial

A tutorial repo with multiple projects designed to help teach users
JavaScript
11
star
70

serverless-helpers-js

Serverless Helpers Node.Js: An NPM module that provides helper functions for Serverless Modules written in Node.js -
JavaScript
11
star
71

template

Compose & provision a collection of Serverless Components
JavaScript
10
star
72

template-package

Repository template for serverless packages
JavaScript
9
star
73

serverlessconf-workshop

JavaScript
9
star
74

serverless-search-engine

Part of the Serverless Live series where we build a very simplistic search engine and spider
JavaScript
9
star
75

artwork

Official design elements of Serverless Inc. and its projects
8
star
76

extensions

Use / make / monetize developer experiences.
JavaScript
8
star
77

event-gateway-connector

Serverless Event Gateway Connector Framework
Go
7
star
78

raffleapp

A serverless raffle app
JavaScript
7
star
79

netlify-landing-page

Components Landing page demo
CSS
7
star
80

compose-example

JavaScript
6
star
81

demo-todo

An example serverless-todo app
JavaScript
5
star
82

serverless-raffle

JavaScript
5
star
83

enterprise-template

JavaScript
5
star
84

workshops

Companion repo for workshops with instructions and code examples
JavaScript
5
star
85

sls-action

GitHub action for Serverless CLI
TypeScript
5
star
86

test

Test setup and utilities for serverless projects
JavaScript
4
star
87

compose-website-example

JavaScript
4
star
88

console

4
star
89

cli-design

Repository to discuss Serverless Framework v3 redesign
HTML
4
star
90

event-gateway-tracer

JavaScript
3
star
91

core

Serverless Components Core
JavaScript
3
star
92

status

The Serverless Status Page
JavaScript
3
star
93

partner-examples

JavaScript
2
star
94

components-core

WIP
TypeScript
2
star
95

azure-build-task

A Serverless build task for Azure Dev Ops
TypeScript
1
star
96

sfe-nodejs-service

JavaScript
1
star
97

inquirer

inquirer with enforced serverless theme
JavaScript
1
star
98

template-getting-started-node-js

Application templates used by the Serverless Platform
1
star
99

serverless-cloud-gitpod

Starter repository for running Serverless Cloud on GitPod
1
star
100

user-testing

Tests of product concepts
JavaScript
1
star