Skip to content

Instantly share code, notes, and snippets.

@arabold
Created October 6, 2022 15:15
Show Gist options
  • Save arabold/68532e04625ed1e43d8644fb61d652a5 to your computer and use it in GitHub Desktop.
Save arabold/68532e04625ed1e43d8644fb61d652a5 to your computer and use it in GitHub Desktop.
Run Serverless Offline and Serverless Python Requirements together
#!/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