├── .gitattributes ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── README.md ├── example.py ├── lambdify ├── __init__.py ├── data │ └── container.py ├── decorators.py └── deployment.py ├── requirements.txt ├── setup.py └── tests ├── __init__.py └── test_lambda.py /.gitattributes: -------------------------------------------------------------------------------- 1 | lambdify/_version.py export-subst 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: python 3 | python: 4 | - '3.6' 5 | script: 6 | - echo "skipping tests" 7 | deploy: 8 | provider: pypi 9 | user: dijkstra 10 | password: 11 | secure: br8mW7XiomgRfcxJUSXd59MqY02ub6Q2nFncUP5wzpAqaM0gwmeIILvC9vfnx0pngyaZVvEIvFbag66Y0est7Rep0HEHTQ2UbOxwfniI2OaNWO7PO4MNnU03FW4HBXGEv/Vo8vaSNKNr6R1rOLI+DE4PaEVFZUA0FOao52ZmOARKOG+is6FkSysVBHgqfm/gCA6k/X9LfKi+25RNHt56q6fhT2dlapdUg/UP9nBzUjRvHb/WdGtFMSD6iNRrVCaN5JWMT3zfEOdhNoWgu40xlotRzDt+1v4jMLPDHUHRVIxfw+CaHqFev1tM8/eUzrcbZqIz6w/gpFXWtrIXU3edmFxprt3Bh36ij1j0XuCTfjPsEomBSjxOX2rwvKA9HY/hMopUcFqbndXWFP5Y/XgkWe6q0hZWzIpTK89xRFUGrMi4cKN9+vnO1o6hv1zlMghXGH/9izr8UW+sLpXgw5v1mwgNt8VhaDAv7FwFvpoZiG9XeNXrkQKPQZ/qMm3jwO+ux0AxO9EamYUnfvKKsvYSQUDOWjvKor29IuINpIe2YzTIkbyadHM9LQkwoe22leP1E4SF07o7ncuMXAh9dOfc1IjXSEIcSXMKr6gXFaMiaaMpo9W7y4FWdXfCS9T4pDlvJVssc1XXVGAF/mtEEhOQaLywm80WHSPVu/Aj1SJzke4= 12 | on: 13 | tags: true 14 | branch: master 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include versioneer.py 2 | include lambdify/_version.py 3 | include README.md requirements.txt 4 | recursive-include tests *.py 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # λambdify - because code is the only thing that matters 2 | [![Build Status](https://travis-ci.org/ZhukovAlexander/lambdify.svg?branch=master)](https://travis-ci.org/ZhukovAlexander/lambdify) 3 | [![PyPI version](https://badge.fury.io/py/lambdify.svg)](https://badge.fury.io/py/lambdify) 4 | 5 | ### ***DISCLAIMER: lambdify is just a POC, it's not actively maintained and is not suitable for production use at the moment*** 6 | 7 | **lambdify** is a tool that turns any python callable into an AWS Lambda function. Create, update and call your lambdas directly from python. 8 | 9 | Just like that: 10 | 11 | install *lambdify*... 12 | ```bash 13 | $pip install lambdify 14 | ``` 15 | ...create AWS Lambda with 4 lines of code: 16 | ```python 17 | from lambdify import Lambda 18 | 19 | 20 | @Lambda.f(name='echo') 21 | def echo(*args, **kwargs): 22 | return args, kwargs 23 | 24 | echo.create() 25 | 26 | if __name__ == '__main__': 27 | import getpass 28 | echo(msg='Hello, {user}!'.format(user=getpass.getuser())) 29 | ``` 30 | 31 | Now you can head over to your [AWS Lambda console](https://console.aws.amazon.com/lambda/) and behold your **echo** function. 32 | Could creating a serverless program be any easier? 33 | 34 | # The goal 35 | 36 | Lambdify aims to unite convenient task queues API (i.e. [Celery](http://www.celeryproject.org/), [Hue](http://huey.readthedocs.org/en/latest/#huey-s-api), [RQ's @job decorator](http://python-rq.org/docs/)) with AWS Lambda service coolest features. Ultimately, **lambdify** should be capable to become a good alternative to Celery or any other task queue. 37 | 38 | At present, there are some solutions, that allow you to create and deploy lambdas, like [Zappa](https://github.com/Miserlou/Zappa), [lambda-uploader](https://github.com/rackerlabs/lambda-uploader), [lambder](https://github.com/LeafSoftware/python-lambder) etc., but they still have limitations of not being able to interact directly with a python program. 39 | lambdify overcomes such limitations by using the following algorithm: 40 | 41 | 1. Serialize the callable with it's globals using [dill](https://github.com/uqfoundation/dill) 42 | 43 | 2. Upload the ```.lambda.dump``` file containing the serialized function along with the rest of the package 44 | 45 | 3. Special ```container.py``` module will look for the ```.lambda.dump``` file and inject deserialized function into it's namespace 46 | 47 | 4. ???? 48 | 49 | 5. Profit 50 | 51 | # Documentation 52 | ```python 53 | >>>from lambdify import Lambda 54 | >>>help(Lambda) 55 | ``` 56 | 57 | #Usecases and features 58 | 59 | * ***Workerless task queue replacement*** 60 | 61 | The simpliest task queue ever 62 | ```python 63 | @Lambda.f(name='my_job') 64 | def add(a, b): 65 | return a + b 66 | ``` 67 | 68 | 69 | * ***Distributed computing*** 70 | 71 | Lambdas can create and call other lambdas: 72 | ```python 73 | @Lambda.f(name='child') 74 | def child_function(x, y): 75 | return x * y 76 | 77 | @Lambda.f(name='parent') 78 | def parent_function(y): 79 | # this will actually call the cloud instance of 80 | # child_function 81 | return child_function(2, y) 82 | 83 | parent_function(42) 84 | ``` 85 | * ***Cloud Functional Reactive Programming*** 86 | * ***Dynamic and realtime lambda-function management*** 87 | 88 | 89 | ***P.S. Lambdify is a POC, and at the time allows your lambda to only use site-packages, all local files won't be packaged, so each user-defined dependency should be contained withing the same file.*** 90 | 91 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | from lambdify import Lambda, UPDATE_EXPLICIT 2 | 3 | 4 | @Lambda.f(name='echo') 5 | def echo(*args, **kwargs): 6 | return args, kwargs 7 | -------------------------------------------------------------------------------- /lambdify/__init__.py: -------------------------------------------------------------------------------- 1 | from .decorators import Lambda, UPDATE_EXPLICIT, UPDATE_ON_INIT, UPDATE_LAZY 2 | 3 | from pkg_resources import get_distribution, DistributionNotFound 4 | try: 5 | __version__ = get_distribution(__name__).version 6 | except DistributionNotFound: 7 | # package is not installed 8 | pass 9 | -------------------------------------------------------------------------------- /lambdify/data/container.py: -------------------------------------------------------------------------------- 1 | import os 2 | import dill 3 | 4 | with open('.lambda.dump', 'r') as serialized: 5 | lambda_handler = dill.load(serialized) 6 | -------------------------------------------------------------------------------- /lambdify/decorators.py: -------------------------------------------------------------------------------- 1 | import json 2 | import functools 3 | from contextlib import contextmanager 4 | 5 | import boto3 6 | import botocore 7 | import dill 8 | 9 | from .deployment import DeploymentPackage 10 | 11 | dill.settings['recurse'] = True 12 | 13 | 14 | # this flags allow you to control the point in time at which to create/update your function 15 | # It is needed due to the expensive transfer of a zip file with packed environment 16 | # when updating/creating a function code 17 | UPDATE_EXPLICIT = 0 # you'll have to create your lambda explicitly 18 | UPDATE_ON_INIT = 1 # perform update on Lambda initialization 19 | UPDATE_LAZY = 2 # perform update just before invoking the function 20 | CREATE_ONCE = 4 # create the function, if it doesn't exist 21 | 22 | 23 | class Lambda(object): 24 | """Wrapper class around a callable 25 | 26 | This wrapper basically replaces the original function with it's AWS Lambda instance. 27 | When called, the instance of this class will route the call to the AWS Instance, instead of 28 | calling a local function. 29 | 30 | 31 | """ 32 | _was_updated = False 33 | 34 | _context = None 35 | _inv_type = 'RequestResponse' 36 | 37 | version = '$LATEST' 38 | 39 | def __init__(self, func, name='', role='', description='', vps_config=None, package=None, flags=UPDATE_EXPLICIT): 40 | """ 41 | Main Lambda constructor 42 | 43 | :param func: function to make an AWS Lambda from. This will be the actual lambda handler 44 | :param name: 45 | :param role: AWS role ARN 46 | :param description: function description 47 | :param vps_config: vps configuration 48 | :param package: deployment package for this function 49 | :param flags: this flags allow you to control the point in time, when to make an actual call to aws to create 50 | the function 51 | 52 | Usage: 53 | 54 | >>>from lambdify import Lambda 55 | >>> 56 | >>>func = Lambda(lambda x: x) 57 | >>>func.name 58 | '__main__.' 59 | >>>func.create() 60 | {...} 61 | """ 62 | self.client = boto3.client('lambda', region_name='us-west-2') 63 | 64 | self.name = name or '{}.{}'.format(func.__module__, func.__name__) 65 | self.role = role 66 | if not role: 67 | iam = boto3.client('iam') 68 | role = iam.get_role(RoleName='lambda_s3_exec_role') 69 | self.role = role['Role']['Arn'] 70 | 71 | self.description = description 72 | self.vps_config = vps_config or {} 73 | self.package = package or DeploymentPackage(self) 74 | self.create_options = flags 75 | self._context = {} 76 | 77 | # here we need to adapt the signature of the function to the AWS Lambda signature 78 | # according to https://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html 79 | # TODO: allow different adapters. This will require changes to the __call__ method 80 | @functools.wraps(func) 81 | def adapter(event, context): 82 | args = event.pop('args', []) 83 | return func(*args, **event) 84 | 85 | self.functor = adapter 86 | 87 | # serialize function early, otherwise dill could pick up global variable, not meant to be used 88 | # by this function 89 | self.dumped_code = dill.dumps(self.functor) 90 | 91 | if self.create_options & UPDATE_ON_INIT == UPDATE_ON_INIT: 92 | self._create_or_update() 93 | 94 | @classmethod 95 | def f(cls, name='', role='', description='', vps_config=None, package=None, flags=UPDATE_EXPLICIT): 96 | """ 97 | Alternative constructor factory to allow this class to be used as a decorator 98 | 99 | 100 | :param name: lambda function name 101 | :param role: role ARN 102 | :param description: function description 103 | :param vps_config: vps configuration 104 | :param package: deployment package for this function 105 | :param flags: this flags allow you to control the point in time, when to make an actual call to aws to create 106 | the function 107 | :return: function decorator 108 | """ 109 | 110 | def initialize(func): 111 | return cls(func, 112 | name=name, 113 | role=role, 114 | description=description, 115 | vps_config=vps_config, 116 | package=package, 117 | flags=flags) 118 | return initialize 119 | 120 | @contextmanager 121 | def call_context(self, version=None, inv_type=None, context=None): 122 | """Context managers, that allows the Lambda to be called with a 123 | specific version, context and invocation type 124 | 125 | :param version: lambda function will use this version 126 | :param inv_type: invocation type 127 | :param context: lambda context 128 | 129 | >>>l = Lambda(lambda x: x, name='foo') 130 | >>> 131 | >>>with l.call_context(version='42', context={'bar': 'bar'}, inv_type='Event'): 132 | ...print l.version, l._context, l._inv_type 133 | ('42', {'bar': 'bar'}, 'Event') 134 | >>> 135 | >>>print l.version, l._context, l._inv_type 136 | ('$LATEST', {}, 'RequestResponse') 137 | 138 | """ 139 | _version_orig, _inv_type_orig, _context_orig = self.version, self._inv_type, self._context.copy() 140 | try: 141 | self.version = version or self.version 142 | self._inv_type = inv_type or self._inv_type 143 | self._context = context or self._context 144 | yield 145 | finally: 146 | self.version, self._inv_type, self._context = _version_orig, _inv_type_orig, _context_orig 147 | 148 | def __call__(self, *args, **kwargs): 149 | kwargs.update({'args': args}) 150 | resp = self.invoke(kwargs, self._context, version=self.version, inv_type=self._inv_type) 151 | return json.loads(resp['Payload'].read()) 152 | 153 | def _create_or_update(self): 154 | try: 155 | self.get() 156 | self.update() 157 | except botocore.exceptions.ClientError as e: 158 | if e.response['Error']['Code'] == 'ResourceNotFoundException': 159 | self.create() 160 | else: 161 | raise 162 | 163 | self._was_updated = True 164 | 165 | def create(self): 166 | """Create lambda function in AWS""" 167 | response = self.client.create_function( 168 | FunctionName=self.name, 169 | Runtime='python2.7', 170 | Role=self.role, 171 | Handler='container.lambda_handler', 172 | Code={ 173 | 'ZipFile': self.package.zip_bytes(self.dumped_code), 174 | 175 | }, 176 | Description=self.description, 177 | Timeout=123, 178 | MemorySize=128, 179 | Publish=True, 180 | 181 | ) 182 | 183 | return response 184 | 185 | def get(self, version=None): 186 | """Get the lambda instance details from AWS 187 | 188 | :param version: function version to get 189 | """ 190 | return self.client.get_function(FunctionName=self.name, Qualifier=version or self.version) 191 | 192 | def update(self): 193 | """Update the lambda instance""" 194 | response = self.client.update_function_code( 195 | FunctionName=self.name, 196 | ZipFile=self.package.zip_bytes(self.dumped_code), 197 | # Publish=True|False 198 | ) 199 | 200 | return response 201 | 202 | def invoke(self, event, context, inv_type=None, log_type='None', version=None): 203 | """Invoke the lambda function This is basically a low-level lambda interface. 204 | In most cases, you won't need to use this by yourself. 205 | 206 | :param event: lambda input 207 | :param context: lambda execution client context 208 | :param inv_type: invocation type 209 | :param log_type: log type 210 | :param version: version 211 | """ 212 | if not self._was_updated and self.create_options & UPDATE_LAZY == UPDATE_LAZY: 213 | self._create_or_update() 214 | 215 | params = dict( 216 | FunctionName=self.name, 217 | InvocationType=inv_type or self._inv_type, 218 | LogType=log_type, 219 | ClientContext=json.dumps(context), 220 | Payload=json.dumps(event), 221 | ) 222 | if version: 223 | params['Qualifier'] = version 224 | 225 | return self.client.invoke(**params) 226 | 227 | @property 228 | def versions(self): 229 | """List all versions for this Lambda""" 230 | return self.client.list_versions_by_function(FunctionName=self.name)['Versions'] 231 | -------------------------------------------------------------------------------- /lambdify/deployment.py: -------------------------------------------------------------------------------- 1 | import os 2 | import zipfile 3 | 4 | 5 | class DeploymentPackage(object): 6 | def __init__(self, lambda_function, path=None): 7 | self.lambda_function = lambda_function 8 | if path: 9 | self.env_cache = path 10 | else: 11 | default = '/tmp/easy_lambda' 12 | if not os.path.isdir(default): 13 | os.mkdir(default) 14 | self.env_cache = '{}/{}.cache'.format(default, lambda_function.name) 15 | 16 | def copy_env(self, destination, venv_path=None): 17 | """ 18 | Compies a python environment to the specified destination zip 19 | 20 | :param destination 21 | :type destination zipfile.ZipFile 22 | :param venv_path path to the virtualenv root 23 | :type venv_path str 24 | """ 25 | 26 | venv = venv_path or os.environ['VIRTUAL_ENV'] 27 | 28 | site_packages = os.path.join(venv, 'lib', 'python2.7', 'site-packages') 29 | 30 | def take_pyc(root_dir): 31 | # If there is a .pyc file in this package, 32 | # we can skip the python source code as we'll just 33 | # use the compiled bytecode anyway. 34 | return lambda f_name: not ( 35 | f_name.endswith('.py') and os.path.isfile(os.path.join(root_dir, f_name) + 'c') 36 | ) 37 | 38 | for root, dirs, files in os.walk(site_packages): 39 | for filename in filter(take_pyc(root), files): 40 | destination.write( 41 | os.path.join(root, filename), 42 | os.path.join(os.path.relpath(root, site_packages), filename) 43 | ) 44 | 45 | def get_zipped_env(self): 46 | if not os.path.isfile(self.env_cache): 47 | with zipfile.ZipFile(self.env_cache, 'w', zipfile.ZIP_DEFLATED) as archive: 48 | path = os.path.join(os.path.dirname(__file__), 'data') 49 | for filename in os.listdir(path): 50 | archive.write(os.path.join(path, filename), filename) 51 | 52 | # package your environment 53 | self.copy_env(archive) 54 | 55 | return zipfile.ZipFile(self.env_cache, 'a', zipfile.ZIP_DEFLATED) 56 | 57 | def to_bytes(self, lambda_code): 58 | archive = self.get_zipped_env() 59 | 60 | # add serialized lambda function 61 | # make sure to add correct permissions 62 | # 63 | info = zipfile.ZipInfo('.lambda.dump') 64 | info.external_attr = 0o777 << 16 # give full access to included file 65 | archive.writestr(info, lambda_code) 66 | archive.close() 67 | return open(self.env_cache).read() 68 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | dill 2 | boto3 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | import os 3 | 4 | with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements: 5 | install_requires = requirements.readlines() 6 | 7 | setup(name='lambdify', 8 | install_requires=install_requires, 9 | setup_requires=['setuptools_scm'], 10 | use_scm_version=True, 11 | author='Alexander Zhukov', 12 | author_email='zhukovaa90@gmail.com', 13 | url='https://github.com/ZhukovAlexander/lambdify', 14 | keywords='aws lambda task queue distributed computing', 15 | classifiers=['Development Status :: 3 - Alpha', 16 | 'Intended Audience :: Developers', 17 | 'License :: OSI Approved :: Apache Software License', 18 | 'Operating System :: OS Independent', 19 | 'Programming Language :: Python :: 2.7', 20 | 'Topic :: Software Development :: Libraries :: Python Modules', 21 | 'Topic :: System :: Distributed Computing', 22 | 'Topic :: Utilities'] 23 | ) 24 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZhukovAlexander/lambdify/e291c15bacffc871cd1c10aefe9f132420259dfd/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_lambda.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import zipfile 3 | from StringIO import StringIO 4 | import tempfile 5 | import shutil 6 | 7 | import boto3 8 | import dill 9 | import moto 10 | import mock 11 | import pip 12 | 13 | from easy_lambda.deployment import Lambda, DeploymentPackage 14 | 15 | 16 | @moto.mock_lambda 17 | class Test(unittest.TestCase): 18 | def setUp(self): 19 | super(Test, self).setUp() 20 | self.client = boto3.client('lambda', region_name='us-west-2') 21 | @mock.patch('easy_lambda.deployment.DeploymentPackage.copy_env') 22 | def test_create(self, mock): 23 | 24 | value = 1 25 | function_name = 'test_function' 26 | 27 | @Lambda(name=function_name, bucket='test', key='test', client=self.client) 28 | def foo(): 29 | return value 30 | 31 | package = DeploymentPackage(foo) 32 | 33 | zfp = zipfile.ZipFile(StringIO(package.zip_bytes(foo.dumped_code)), "r") 34 | func = dill.load(zfp.open('.lambda.dump')) 35 | self.assertEqual(func(), value) 36 | 37 | resp_create = foo.create() 38 | self.assertEqual(resp_create['FunctionName'], function_name) 39 | 40 | # moto doesn't support ZipFile only lambda deployments, while 41 | # aws doen't allow other arguments when scpesifying ZipFile argument 42 | #resp_get = foo.get() 43 | #self.assertEqual(resp_get['Configuration']['FunctionName'], function_name) 44 | 45 | 46 | 47 | 48 | 49 | 50 | @unittest.skip('slow') 51 | class PackageTestCase(unittest.TestCase): 52 | 53 | def setUp(self): 54 | self.venv = tempfile.mkdtemp() 55 | # 56 | pip.main(['install', 'requests', '-t', self.venv]) 57 | shutil.copytree(self.venv, self.venv + '/lib/python2.7/site-packages') 58 | 59 | def test_copy_env(self): 60 | package = DeploymentPackage(None, None, None) 61 | with zipfile.ZipFile(StringIO(), 'w', zipfile.ZIP_DEFLATED) as dest: 62 | package.copy_env(dest, venv_path=self.venv) 63 | self.assertTrue(dest.namelist(), 'For now just test that it is not empty') 64 | 65 | def tearDown(self): 66 | shutil.rmtree(self.venv) 67 | 68 | --------------------------------------------------------------------------------