Technology Blog Posts by Members
cancel
Showing results for 
Search instead for 
Did you mean: 
900

There is a lot of information available about creating and debugging Node.js services in SAP BTP. However, in some cases, we might need to use Python instead — for example, for tasks involving AI or data processing.

In this article, I’ll show you how to debug a Python-based SAP BTP service using VS Code (Visual Studio Code) locally.

Prerequisites

Create an SAP BTP Trial Account. Please follow this tutorial for detailed information. 

Add HANA to your SAP BTP trial account if you haven’t already.

To do this, refer to the section ‘Create an SAP HANA Cloud Instance’ of this tutorial.

Note: One of the steps in the tutorial above requires the Space ID.
If you're not sure where to find it, navigate to your space in the SAP BTP Cockpit and copy the Space ID from the URL.

take_space_from_url.png

Install Visual Studio Code (VS Code). You can download it from this page.

Install the SAP Cloud Foundry CLI. Refer to this guide on installing the cf CLI for detailed instructions.

Install the Python interpreter. Version 3.13 or higher is recommended.

Install the necessary extensions for VS Code:

  • Python extension by Microsoft
  • Python debugger extension by Microsoft

vscode_extensions.PNG

Note: When installing the first extension (Python), the second one (Python Debugger) may be installed automatically. If not, you can install it manually.

Steps to create a service

Our service will not include authorization for the sake of simplicity, but it will use an SAP HANA service to demonstrate how to call a BTP service from the local environment. We will use the initial setup from this tutorial.

In the following sections, I will replicate some of the steps from that tutorial in this blog post, with a few minor adjustments.

  • In your local file system, create a new folder –  for example, python-debug.
  • In Visual Studio Code, open the python-debug folder.
  • Create a file named manifest.yml with the following content:
---
applications:
  - name: python-debug
    random-route: true
    path: ./
    memory: 128M
    buildpacks:
      - python_buildpack
    command: python server.py
    services:
      - python-debug-hana
​

IMPORTANT: Make sure you don’t already have another application named python-debug in your space. If you do, use a different name and update the entire tutorial accordingly.

  • Specify the Python runtime version your application will use. To do this, create a file named runtime.txt with the following content:
python-3.13.x​
  • This application will be a web server utilizing the Flask web framework. To specify Flask as a dependency, create a file named requirements.txt with the following content:
Flask==2.3.*
cfenv==0.5.3
hdbcli==2.17.*
  • Create a file named server.py with the following application logic:
import os
from flask import Flask
from cfenv import AppEnv
from hdbcli import dbapi

app = Flask(__name__)
env = AppEnv()

hana_service = 'hana'
hana = env.get_service(label=hana_service)

port = int(os.environ.get('PORT', 3000))
@app.route('/')
def hello():
    if hana is None:
        return "Can't connect to HANA service '{}' – check service name?".format(hana_service)
    else:
        conn = dbapi.connect(address=hana.credentials['host'],
                             port=int(hana.credentials['port']),
                             user=hana.credentials['user'],
                             password=hana.credentials['password'],
                             encrypt='true',
                             sslTrustStore=hana.credentials['certificate'])

        cursor = conn.cursor()
        cursor.execute("select CURRENT_UTCTIMESTAMP from DUMMY")
        ro = cursor.fetchone()
        cursor.close()
        conn.close()

        return "Current time is: " + str(ro["CURRENT_UTCTIMESTAMP"])

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port)
​

This is a simple server that will return the result of a basic HANA SQL query when requested (in our case, the current UTC time).

  • Log in to Cloud Foundry using the following command in the command line:
cf login​

When prompted, enter your API endpoint. You can find it on the Account Overview page in your SAP BTP account.

btp_subaccount_overview.png

Also, enter the registration email and password for your SAP BTP trial account.

  • Create a HANA service using the following command:
cf create-service hana hdi-shared python-debug-hana​
  • Deploy the application on Cloud Foundry. To do that, run the following command inside the python-debug directory:
cf push​

Note: If you make any changes to the service file and want to deploy again, simply run the ‘cf push’ command again.

  • After successful deployment, the python-debug application should start automatically, and its details will be displayed in the command console.
    VSCode_address.PNG
  • Open a browser and enter the application’s generated URL (you can find it under “routes”)
    For example: python-debug-zany-buffalo-zz.cfapps.us10-001.hana.ondemand.com
    service_results.PNG

Steps to debug the service locally

Local debugging of applications running on SAP Business Technology Platform (SAP BTP) is not only possible, but also practical in many cases. Here’s why:

  • Globally Accessible Services:
    In SAP BTP,  most service endpoints use globally routable addresses. This means that your application can access these services from any location, not just from within the SAP BTP environment. As a result, you can run and test your application locally while still interacting with cloud services such as databases, messaging queues, or authentication providers.
  • Minimal Environmental Differences:
    SAP BTP does not provide a highly customized runtime environment. Apart from environment variables—which you can replicate locally—there are no special runtime conditions. This allows developers to simulate the production environment with high fidelity on their local machines by simply setting the appropriate environment variables.
  • If you encounter an issue where an SAP BTP service address is not globally reachable and a connection error occurs (e.g., when testing a task that calls an on-premise OData service through the Cloud Connector), please refer to this blog for possible resolution.

Thanks to these two factors, local development and debugging in SAP BTP is straightforward. It enables faster development cycles and easier troubleshooting without the need to redeploy for every change.

To enable local debugging of a Python-based service, follow these steps:

  • Since the SAP BTP environment provides necessary configuration through environment variables, you need to replicate them locally. In order to load local environment data, insert the following changed code to your Python server script:
import os
from flask import Flask
from cfenv import AppEnv
from hdbcli import dbapi
from dotenv import load_dotenv
load_dotenv()

app = Flask(__name__)
env = AppEnv()

hana_service = 'hana'
hana = env.get_service(label=hana_service)

port = int(os.environ.get('PORT', 3000))
@app.route('/')
def hello():
    if hana is None:
        return "Can't connect to HANA service '{}' – check service name?".format(hana_service)
    else:
        conn = dbapi.connect(address=hana.credentials['host'],
                             port=int(hana.credentials['port']),
                             user=hana.credentials['user'],
                             password=hana.credentials['password'],
                             encrypt='true',
                             sslTrustStore=hana.credentials['certificate'])

        cursor = conn.cursor()
        cursor.execute("select CURRENT_UTCTIMESTAMP from DUMMY")
        ro = cursor.fetchone()
        cursor.close()
        conn.close()

        return "Current time is: " + str(ro["CURRENT_UTCTIMESTAMP"])

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port)
​

This new logic will let you automatically read the key-value pairs from your .env file and make them available via os.environ, just like in the cloud environment.

  • Update the requirements.txt to include the necessary libraries
Flask==2.3.*
cfenv==0.5.3
hdbcli==2.17.*
python-dotenv​
  • Create a Python Virtual Environment

    Every Python project should run in its own isolated environment to avoid dependency conflicts.

    In VS Code, open the Command Palette (Ctrl+Shift+P), and choose ‘Python: Create Environment…’
    vscode_create_environment.png
  • Then select the option ‘Venv Creates a ‘.venv’ virtual environment in the current workspace’:
    vscode_create_environment2.png
  • Then select a Python Version (Python 3.13.x or higher is recommended):
    vscode_create_environment3.png
  • On the next screen, confirm the option to install the dependencies:
    vscode_create_environment4.png

Note: You can also do this later using the command pip install -r requirements.txt.

  • A new virtual environment will be created in a .venv folder in your workspace:
    venv_created.PNG
  • Set the VCAP_SERVICES environment variable
    Before running the service locally, we need to set the VCAP_SERVICES environment variable, which provides all the necessary information about SAP BTP services.
    To retrieve its contents, use the following command:
cf env python-debug​

Now, copy the contents of the VCAP_SERVICES JSON block to your clipboard.

  • Before we can use the contents of the environment variable, we need to minimize the JSON into a single line. You can use any online JSON minifier tool or the JSTool extension in Notepad++ to do this.
  • Now, create a .env file in your service folder (the same folder where the manifest.yml file is located), and add the environment variable contents to it in the following format:
VCAP_SERVICES=<minimized_json>​

env_file.png

  • Create a configuration in VSCode. Before starting, open the server.py file in the editor.
  • Open the ‘Run and Debug’ section in VSCode and select ‘Create a launch.json file’:
    create_config.PNG

    Note: If you have already created the configuration file, simply open it for edit.

  • From the drop-down list, select ‘Python debugger’
    create_config2.png
  • Select ‘Python File: Debug the currently active Python file’:
    create_config3.png
  • In the created file, delete the commented-out lines starting with // to avoid syntax errors
    delete_comments_launch_json.png
  • Return to the server.py file, and start the debugging session
    run_debug.PNG
  • Start the debug session
    run_debug_session.PNG
  • The debugging session is now running:
    server_executed.PNG
  • Open the following address in a browser
http://127.0.0.1/​

The current date and time from the HANA server will be displayed

open_in_browser.PNG

  • Then, return to VSCode and set a break-point
    set_a_breakpoint.png
  • Refresh the browser again, and the execution will pause at the breakpoint:
    debugger_stopped.PNG

Now, you can use all the Python debugger’s features to debug your program.

2 Comments
Cocquerel
Active Contributor
0 Kudos

Can we do the same using Business Application Studio instead of VSCode ?

Yes, we can do the same in Business Application Studio (BAS); I just double-checked.

Capture.PNG
There are a few small differences:
1. You need to explicitly install the 'Python debugger' extension. Before the installation, you will be asked to confirm that you understand the potential risks.

2. You must use a different port instead of 3000 (e.g., 4000), otherwise you'll encounter an 'address already in use' issue. This port can either be defined in the .env file as the 'PORT' variable or hard-coded in the code.

3. To test your service in the browser, you need to use a specific URL, such as:
https://port4000-workspaces-ws-*....*.us10.trial.applicationstudio.cloud.sap/
You don’t have to memorize this address — just click the button in the bottom-right corner once your script is running.
(This applies to testing any application or service locally in BAS.)

Please refer to this blog for information on how to set up a Python environment in Business Application Studio.