为AWS Lambda在子目录打包Python依赖的问题求助
Hey Harry, let’s troubleshoot this together— I’ve dealt with the exact same frustration when trying to use a vendored directory for Lambda dependencies with Serverless. Here are the most common fixes that should get your imports working:
1. Add the Vendored Directory to Python’s Path
AWS Lambda doesn’t automatically include the vendored folder in Python’s system path. You need to explicitly add it at the very top of your handler file (before importing any external dependencies):
import sys import os # Insert the vendored directory at the start of the path sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'vendored')) # Now your regular imports will work from pynamodb.models import Model
This tells Python to look for modules in the vendored folder first, which is where your pip-installed packages live.
2. Match Your Local Python Version to Lambda’s Runtime
If you installed dependencies with a different Python version than what your Lambda uses, you’ll run into import errors (even if the folder structure looks right).
- First, check your Lambda runtime in
serverless.yml(look for theruntimefield underfunctions— e.g.,python3.9). - Then install dependencies using the matching pip version. For example, if Lambda uses Python 3.9:
pip3.9 install -t vendored/ -r requirements.txt - If you don’t have the exact Python version locally, use a virtual environment with the correct version (via
pyenvorvirtualenv) to avoid compatibility issues.
3. Verify Serverless is Packaging the Vendored Directory
Double-check your serverless.yml to make sure the vendored folder isn’t being excluded during packaging. Here’s a safe package configuration:
package: exclude: - node_modules/** - .git/** - venv/** - .env # Explicitly include the vendored folder to be safe include: - vendored/** - handler.py # Replace with your main handler file
If you’re using the serverless-python-requirements plugin, note that it might override manual packaging— if you want to stick with the vendored approach, make sure the plugin is disabled or configured to respect your setup.
4. Validate the Vendored Directory Structure
Sometimes pip fails to install packages correctly (due to network issues or permissions). Navigate to vendored and check that:
- The package folders (like
pynamodb) exist - Each package has the necessary
__init__.pyfiles - There are no broken symlinks (common on macOS/Linux if you installed with
--userbefore)
If something looks off, delete the vendored folder entirely and re-run the pip install command with --no-cache-dir to avoid stale packages:
rm -rf vendored/ pip install --no-cache-dir -t vendored/ -r requirements.txt
内容的提问来源于stack exchange,提问作者Harry

