How to setup AWS SAM local debugging with Python on Visual Studio Code?

2.9k views Asked by At

I was trying to use the debugging function for lambda (python) in Visaul Studio Code. I was following the instructions on AWS Docs, but I could not trigger the python applicaion in debug mode.

Please kindly see if you know the issue and if I have setup anything incorrectly, thanks.

Reference: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-debugging.html

Observation

  • Start application

Seems application was not started on the debug port specified?

Start_server_with_debug_mode

  • Request call

The endpoint could not be reached and python application was not entered

Not_ok_with_port_5890

If accessed through port 3000, application could complete successfully

OK_with_port_3000

Setup performed

  1. Initialize the project and install ptvsd as instructed
  2. Enable ptvsd on the python code
  3. Add launch configuration

Project structure

Project_Structure

Python source

This is basically just the offical helloworld sample for python

import json

# import requests
import ptvsd

# Enable ptvsd on 0.0.0.0 address and on port 5890 that we'll connect later with our IDE
ptvsd.enable_attach(address=('localhost', 5890), redirect_output=True)
ptvsd.wait_for_attach()

def lambda_handler(event, context):
    """Sample pure Lambda function

    Parameters
    ----------
    event: dict, required
        API Gateway Lambda Proxy Input Format

        Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format

    context: object, required
        Lambda Context runtime methods and attributes

        Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html

    Returns
    ------
    API Gateway Lambda Proxy Output Format: dict

        Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
    """

    # try:
    #     ip = requests.get("http://checkip.amazonaws.com/")
    # except requests.RequestException as e:
    #     # Send some context about this error to Lambda Logs
    #     print(e)

    #     raise e

    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello world",
            # "location": ip.text.replace("\n", "")
        }),
    }

Launch configuration

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
    {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "console": "integratedTerminal"
    },
    {
        "name": "SAM CLI Python Hello World",
        "type": "python",
        "request": "attach",
        "port": 5890,
        "host": "localhost",
        "pathMappings": [
            {
                "localRoot": "${workspaceFolder}/hello_world/build",
                "remoteRoot": "/var/task"
            }
        ]
    }
    ]
}
1

There are 1 answers

0
Patrick C. On BEST ANSWER

It seems I was editing the python file at "python-debugging/hello_world/build" following the guideline of the doc (there is a step in the doc which asks you to copy the python file to "python-debugging/hello_world/build").

But then when you run "sam local start-api", it actually runs the python file at the location specifed by the CloudFormation template (tempalted.yaml), which is at "python-debugging/hello_world" (check the "CodeUri" property).

When I moved all the libriaries to the same folder as the python file it works.

So I suppose you have to make sure which python (or lambda) script you are running, and ensure the libraries are together with the python script (if you are not using layers).

Folder structure

Folder_Structure

Entering debugging mode in Visual studio code

Step 1: Invoke and start up the local API gateway

  • Server

Start_API_Gateway

Step 2: Send a test request

  • Client

Test_Request

Step 3: Request received, lambda triggered, pending activating debug mode in Visual Studio Code

  • Server

Lambda_Triggered

Step 4: Lambda function triggered, entering debug mode in Visual Studio Code

In the IDE, open the "Run" perspective, select the launch config for this file ("SAM CLI Python Hello World"). Start the debug.

Entering_Debug_Mode

Step 5: Step through the function, return response

  • Server

Lambda_Completed

  • Client

enter image description here