serverless / serverless-python-requirements

⚡️🐍📦 Serverless plugin to bundle Python packages
MIT License
1.11k stars 290 forks source link

serverless-offline #311

Open alikian opened 5 years ago

alikian commented 5 years ago

Is there any support for serverless-offline? it seems serverless-offline doesn't call this plug-in

hugoduncan commented 5 years ago

https://github.com/dherault/serverless-offline/issues/580

dschep commented 5 years ago

I recommend creating & activating a virtualenv, installing your dependencies, then using sls offline

JamesKyburz commented 2 years ago

When each function had separate dependencies I created a local plugin to make it work offline, the plugin modifies sys.path and makes sure even boto3 and friends are installed. For this to work npx sls requirements install needs to be run first.

#!/usr/bin/env node

'use strict'

const path = require('path')
const fs = require('fs')

class PythonOfflineFix {
  constructor(serverless, options) {
    this.hooks = {
      'before:offline:start:init': () => this.fixPaths(serverless)
    }
    if (options.stage === 'local') {
      serverless.service.custom.pythonRequirements.noDeploy = []
    }
  }

  async fixPaths(serverless) {
    for (const func of Object.values(serverless.service.functions)) {
      if (func.runtime.match(/python/)) {
        if (func.module) {
          func.handler = `${func.module}/${func.handler}`
          delete func.module
        }
        if (!func.environment) {
          func.environment = {}
        }
        func.environment.PYTHONPATH = await fs.promises.realpath(
          path.join('.serverless', path.dirname(func.handler), 'requirements')
        )
      }
    }
  }
}

module.exports = PythonOfflineFix
rodrigonehring commented 2 years ago

@JamesKyburz I was almost forking the serverless-offline to modify that module path. Thank you!