Created
October 6, 2022 15:15
-
-
Save arabold/68532e04625ed1e43d8644fb61d652a5 to your computer and use it in GitHub Desktop.
Run Serverless Offline and Serverless Python Requirements together
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
"use strict"; | |
const path = require("path"); | |
const fs = require("fs"); | |
/** | |
* Custom Serverless plugin to fix an issue with Serverless Offline not resolving the requirements | |
* path of the Serverless Python Requirements plugin. | |
* | |
* @see https://github.com/serverless/serverless-python-requirements/issues/311#issuecomment-976317821 | |
*/ | |
class PythonOfflineFix { | |
constructor(serverless, options) { | |
this.hooks = { | |
"before:offline:start:init": () => this.setRequirementsPythonPath(serverless), | |
"before:requirements:install:install": () => this.includeAllRequirements(serverless), | |
}; | |
} | |
async includeAllRequirements(serverless) { | |
// Include all dependencies when running manual installation | |
serverless.service.custom.pythonRequirements.noDeploy = []; | |
} | |
async setRequirementsPythonPath(serverless) { | |
for (const func of Object.values(serverless.service.functions)) { | |
const runtime = func.runtime || serverless.service.provider.runtime; | |
if (runtime.match(/python/i) && func.handler) { | |
if (func.module) { | |
func.handler = `${func.module}/${func.handler}`; | |
delete func.module; | |
} | |
if (!func.environment) { | |
func.environment = {}; | |
} | |
if (serverless.service.package?.individually) { | |
func.environment.PYTHONPATH = fs.realpathSync( | |
path.join(".serverless", path.dirname(func.handler), "requirements") | |
); | |
} else { | |
func.environment.PYTHONPATH = fs.realpathSync(path.join(".serverless", "requirements")); | |
} | |
} | |
} | |
} | |
} | |
module.exports = PythonOfflineFix; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment