Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serverless Framework - Python and Requirements.txt

Using the serverless framework v1.0.0, I have a 'requirements.txt' in my service root with the contents being the list of dependant python packages. (e.g. requests).

However my resulting deployed function fails as it seems these dependencies are not installed as part of the packaging

'Unable to import module 'handler': No module named requests'

I assume it is serverless that does the pip install, but my resulting zip file is small and clearly its not doing it, either by design or my fault as I am missing something? Is it because its Lambda that does this? If so what am I missing?)

Is there documentation on what is required to do this and how it works? Is it serverless that pip installs these or on aws lambda side?

like image 741
Kurt Maile Avatar asked Oct 16 '16 13:10

Kurt Maile


People also ask

Does the Serverless Framework support Python?

The native language of the Serverless Framework is Javascript, since that's both the default runtime for Lambda and the language the serverless command-line tool is written in. But since version 0.2. 1 Serverless has supported deploying services written in Python 3.6 (or 2.7), . NET core, and Java 8 to Lambda.

What is Serverless Framework in Python?

Serverless is a deployment architecture where servers are not explicitly provisioned by the deployer. Code is instead executed based on developer-defined events that are triggered, for example when an HTTP POST request is sent to an API a new line written to a file.

Where is requirements TXT Python?

It also stores all files and packages on which that project is dependent or requires to run. Typically this file "requirement. txt" is stored (or resides) in the root directory of your projects.


1 Answers

You need to install serverless-python-requirements and docker

$ npm install serverless-python-requirements

Then add the following to your serverless.yml

plugins:
   - serverless-python-requirements

custom:
  pythonRequirements:
     dockerizePip: non-linux

Make sure you have your python virtual environment active in CLI:

$ source venv/bin/activate

Install any dependencies with pip - note that in CLI you can tell if venv is active by the venv to the left of the terminal text

(venv) $ pip install <NAME>
(venv) $ pip freeze > requirements.txt

Make sure you have opened docker then deploy serverless as normal

$ serverless deploy

What will happen is that serverless-python-requirements will build you python packages in docker using a lambda environment, and then zip them up ready to be uploaded with the rest of your code.

Full guide here

like image 59
GWed Avatar answered Sep 29 '22 06:09

GWed