How to setup a PyRFC server program easily

PyRFC is a Python package that provides users with the ability to connect to the SAP Netweaver RFC library. In doing so, ABAP modules are able to call Python modules and vice versa. This is advantageous when attempting to setup a lightweight Python server to handle SAP ETL jobs. Today, we will walk you through the steps we took to setup our PyRFC server.

Prerequisites

Before being able to successfully run a PyRFC server, you will need the following:

PyRFC Server

Inside of the PyRFC repo, there is an example of a PyRFC server that is provided. The code provided in this example is a great starting point for your server. Within this sample code, there are a few things we would like to point out.

  1. On line 11, there is reference to a config file which should be included in the same directory as your server. This file contains the credentials necessary to connect to SAP, retrieve function descriptions, install functions on the server, and to register with the RFC gateway. All of which can be seen on lines 23 – 31.
  2. The “my_stfc_connection” function, on line 14, is the only function that will execute on this server. It takes two parameters, the “request_context” (which is mandatory for all callback functions) and “REQUTEXT”. “REQUTEXT” is an import parameter from SAP. The name of import parameters must be identical within your function definition and SAP.
  3. In the return statement of  “my_stfc_connection” you will find the export parameters for the function. These also must be identical with the export parameters defined in SAP. The difference between import and export parameters is that mismatch import parameters will cause a failure, as mismatch export parameters will just cause for nothing to be returned to SAP.
  4. A function must be setup in SAP and installed on the server in order to be executed (line 31). If a function is not installed and an ABAP module attempts to call it, a function not found error will occur.

Conclusion

At this point, you should have enough insight to rename/modify the stfc connection function to handle your specific needs. However, there are a few tweaks we made to the main code prior to developing our callback functions.

First we placed lines 22 – 33 into a try block, since exceptions can be thrown connecting to SAP, registering/installing a function, and starting the server. Next, we imported ABAPApplicationError, LogonError, and CommunicationError from pyrfc so that we can gracefully handle these errors. We also ensured to handle TypeError, as this is seen when you attempt to register the same function twice. Lastly, we added a finally block to make sure all connections are closed prior to the program exiting.

Having issues setting up your PyRFC server? Contact us with any of your questions. Otherwise, if you are looking for help with containerizing your application read our blog post explaining how we created our pyrfc dockerfile.

About the author