SAP and Python integration or how to take data from SAP easier

Good afternoon, Habr!

I want to share the experience of an interesting task on how to easily interact with SAP systems using Python - no matter which module or version of the platform.

If only the technical solution is interesting, then skip all the lyrics and see the implementation example.

Lyrics


It all boiled down to the fact that one of the customers needed to upload data from their SAP ERP system, by means of manipulations, to create reports and send them to interested people by email, as well as other actions.

Actually, when discussing the solution of such a task, we, as a contractor, proposed various options and one of the most obvious is to do it all with the help of internal SAP functionality, in a simple way among the “sappers” for “Zeating” all with the help of ABAP.

The first thing we are faced with is not completely transparent from the customer's words the criteria for selecting data, namely, the data of which tables, why, why, what actions should be taken with them. To give an example, the customer needed to unload attendance of office staff, with data in the context of time sheets and vacations. It was also necessary to create reports on employee performance with analytics of his time at the workplace, I will not go into details, but I would say that the amount of time spent affects productivity, but to find out, you need to calculate the amount of time at work with the result of work and much another. This is just one example of a report, and the customer generated a lot during the discussions.

After long conversations, we realized that SAP Query or BI \ BO could be such a solution, but the customer was not very satisfied with the calculated cost of the solution and not the most convenient flexibility.

Python solution


Then on my head I remembered one article on the resource about the pyrfc library and so, like me, not being a python programmer, but having read about it once I decided to study this article at home, and to my surprise, I can easily be at home being an amateur This programming language has found it incredibly easy to connect to any SAP system; moreover, it takes 20 minutes.

Twenty minutes KARL !!!

Just imagine that you can set up a connection interface with the ERP system of SAP without using data buses and PI \ XI for all that tiny time.

Implementation


Finally, making sure that this is a working solution and satisfies the customer, I studied several platforms (I studied implied I read about 10 minutes for each) I chose the Odoo platform among other things being equal, since it is easier to deploy and it has all the necessary properties, such as: Good interface, system of access rights, mobile application, mail server, good interface with database (psql).

Then everything is very simple.

Install on the Odoo customer's virtual machine (I took version 8) because it is the easiest at the moment, I know that version 12 is already, but the task does not require all the cool new products.

Installed all the necessary libraries, in particular pyrfc - link to the article dedicated to installation and connection .

Further, it was only necessary to write a small module in the Odoo platform itself, for the connection, and it has plenty of tools for visualizing data.

Connect to customer system:

from pyrfc import Connection
user = 'user'
passwd = 'secretuser'
saprouter = '/H/192.168.0.140/S/3297'
conn = Connection(user=user, passwd=password,
                  mshost='CLient',
                  msserv='192.168.0.140',
                  sysid='01',
                  group="SPACE",
                  saprouter=saprouter, 
                  client=‘900')

Call BAPI to get information about the user

b_result = conn.call('BAPI_USER_GET_DETAIL',
                     USERNAME = 'user',
                     CACHE_RESULTS  = ' ')

Change user

updated_address['CITY'] = u'Moscow'
r = conn.call('BAPI_USER_CHANGE',
               USERNAME='user',
               ADDRESS=updated_address)

The most important tool for getting data from SAP, if we are talking about tables, is the function module RFC_READ_TABLE, there are other modules in the SAP platform that can be accessed; they must be set up, which means that they can be called up by RFC.

For example:

from pyrfc import Connection, ABAPApplicationError, ABAPRuntimeError, LogonError, CommunicationError
from ConfigParser import ConfigParser
from pprint import PrettyPrinter
defmain():try:
        config = ConfigParser()
        config.read('sapnwrfc.cfg') - #читаем конфиг, где лежат данные о логоне в систему SAP ERP
        params_connection = config._sections['connection']
        conn = Connection(**params_connection) #создаем коннект с системой
        options = [{ 'TEXT': "FCURR = 'USD'"}]
        pp = PrettyPrinter(indent=4)
        ROWS_AT_A_TIME = 10 
        rowskips = 0whileTrue:
            printu"----Begin of Batch---"
            result = conn.call('RFC_READ_TABLE', \
                                QUERY_TABLE = 'TCURR', \
                                OPTIONS = options, \
                                ROWSKIPS = rowskips, ROWCOUNT = ROWS_AT_A_TIME)
            pp.pprint(result['DATA'])
            rowskips += ROWS_AT_A_TIME
            if len(result['DATA']) < ROWS_AT_A_TIME:
                breakexcept CommunicationError:
        printu"Could not connect to server."raiseexcept LogonError:
        printu"Could not log in. Wrong credentials?"raiseexcept (ABAPApplicationError, ABAPRuntimeError):
        printu"An error occurred."raise

Result


In this picture is a list of reports that are downloaded by this method, and an example of one of them.



Total


By and large, this method opens up tremendous opportunities to replace very expensive SAP tools and others with more flexible and open.

Code examples are taken from open sources because I do not have rights to use the customer code in the article, and I am not a Python programmer, I could have made a mistake somewhere.

I want to add that we already use this tool in a very large range of tasks related to KPI Calculation, outputting data to other sources (websites, suppliers and customers databases), sending information from systems based on data from SAP and much more.
For me, in general, it became a discovery in general, such an opportunity, if anyone has a similar experience, I would love to hear it.

PS I did not touch on the issue of licensing, so I can’t say anything about this.
Thank!

Link to Habr
C Respect, SAP Consultant

Also popular now: