pyrfc

The pyrfc package.

Connection

class pyrfc.Connection

A connection to an SAP backend system

Instantiating an pyrfc.Connection object will automatically attempt to open a connection the SAP backend.

Parameters:
  • config (dict or None (default)) –

    Configuration of the instance. Allowed keys are:

    dtime
    returns datetime types (accepts strings and datetimes), default is False
    rstrip
    right strips strings returned from RFC call (default is True)
    return_import_params
    importing parameters are returned by the RFC call (default is False)
  • params (Keyword parameters) –

    SAP connection parameters. The parameters consist of client, user, passwd, lang, trace and additionally one of

    • Direct application server logon: ashost, sysnr.
    • Logon with load balancing: mshost, msserv, sysid, group. msserv is needed only, if the service of the message server is not defined as sapms<SYSID> in /etc/services.
    • When logging on with SNC, user and passwd are to be replaced by snc_qop, snc_myname, snc_partnername, and optionally snc_lib. (If snc_lib is not specified, the RFC library uses the “global” GSS library defined via environment variable SNC_LIB.)
Raises:

RFCError or a subclass thereof if the connection attempt fails.

call(func_name, params)

Invokes a remote-enabled function module via RFC.

Parameters:
  • func_name (string) – Name of the function module that will be invoked.
  • options (dictionary) – Call options, like ‘skip’, to deactivate certain parameters.
  • params (keyword arguments) – Parameter of the function module. All non optional IMPORT, CHANGING, and TABLE parameters must be provided.
Returns:

Dictionary with all EXPORT, CHANGING, and TABLE parameters. The IMPORT parameters are also given, if Connection.config.return_import_params is set to True.

Raises:

RFCError or a subclass thereof if the RFC call fails.

close()

Explicitly close the connection.

Note that this is usually not necessary as the connection will be closed automatically upon object destruction. However, if the the object destruction is delayed by the garbage collection, problems may occur when too many connections are opened.

confirm_unit(unit)

Confirm the current unit in the backend.

This also destroys the unit.

Parameters:unit – a unit descriptor as returned by initialize_unit().
Raises:RFCError or a subclass thereof if the connection attempt fails.
destroy_unit(unit)

Destroy the current unit.

E.g. if the completed unit could not be recorded in the frontend.

Parameters:unit – a unit descriptor as returned by initialize_unit().
Raises:RFCError or a subclass thereof if the connection attempt fails.
fill_and_submit_unit(unit, calls[, queue_names=None[, attributes=None]])

Fills a unit with one or more RFC and submits it to the backend.

Fills a unit for this connection, prepare the invocation of multiple RFC function modules in it, and submits the unit to the backend.

Afterwards, the unit is still attached to the connection object, until confirm_unit() or destroy_unit() is called. Until one of these methods are called, no other unit could be filled and submitted.

Parameters:
  • unit – a unit descriptor as returned by initialize_unit().
  • calls – a list of call descriptions. Each call description is a tuple that contains the function name as the first element and the function arguments in form of a dictionary as the second element.
  • queue_names (list of strings or None (default)) –

    If the unit uses the background protocol, various queue names can be given (leading to a asynchronous unit, type ‘Q’). If parameter is an empty list or None, a synchronous unit (type ‘T’) is created.

    If the unit does not use the background protocol, the queue name may be a list with exactly one element, leading to a qRFC, or an empty list or None, leading to a tRFC.

  • attributes (dict or None (default)) –

    optional argument for attributes of the unit – only valid if the background protocol is used. The attributes dict may contain the following keywords:

    keyword default type description
    kernel_trace 0 int If != 0, the backend will write kernel traces, while executing this unit.
    sat_trace 0 int If != 0, the backend will write statistic records, while executing this unit.
    unit_history 0 int If != 0, the backend will keep a “history” for this unit.
    lock 0 int Used only for type Q: If != 0, the unit will be written to the queue, but not processed. The unit can then be started manually in the ABAP debugger.
    no_commit_check 0 int Per default the backend will check during execution of a unit, whether one of the unit’s function modules triggers an explicit or implicit COMMITWORK. In this case the unit is aborted with an error, because the transactional integrity of this unit cannot be guaranteed. By setting “no_commit_check” to true (!=0), this behavior can be suppressed, meaning the unit will be executed anyway, even if one of it’s function modules “misbehaves” and triggers a COMMIT WORK.
    user current operating system user String, len 12 Sender User (optional).
    client ”000” String, len 3 Sender Client (“Mandant”) (optional).
    t_code ”“ String, len 20 Sender Transaction Code (optional).
    program current executable name String, len 40 Sender Program (optional).
Raises:

RFCError or a subclass thereof if an error occurred. In this case, the unit is destroyed.

get_connection_attributes()

Get connection details

Returns:Mapping of connection information keys:
  • active_unit: True if there is a filled and submitted unit w/o being confirmed or destroyed.
  • dest: RFC destination
  • host: Own host name
  • partnerHost: Partner host name
  • sysNumber: R/3 system number
  • sysId: R/3 system ID
  • client: Client (“Mandant”)
  • user: User
  • language: Language
  • trace: Trace level (0-3)
  • isoLanguage: 2-byte ISO-Language
  • codepage: Own code page
  • partnerCodepage: Partner code page
  • rfcRole: C/S: RFC Client / RFC Server
  • type: 2/3/E/R: R/2,R/3,Ext,Reg.Ext
  • partnerType: 2/3/E/R: R/2,R/3,Ext,Reg.Ext
  • rel: My system release
  • partnerRe: Partner system release
  • kernelRel: Partner kernel release
  • cpicConvId: CPI-C Conversation ID
  • progName: Name calling APAB program (report, module pool)
  • partnerBytesPerChar: Bytes per char in backend codepage.
  • partnerSystemCodepage: Partner system code page
  • reserved: Reserved for later use

Note: all values, except active_unit are right stripped string values.

Raises:RFCError or a subclass thereof if the RFC call fails.
get_function_description(func_name)

Returns a function description of a function module.

Parameters:func_name (string) – Name of the function module whose description will be returned.
Returns:A FunctionDescription object.
get_unit_state(unit)

Retrieves the processing status of the given background unit.

Note

Only available for background units.

Parameters:unit – a unit descriptor as returned by initialize_unit().
Returns:The state of the current bgRFC unit. Possible values are: RFC_UNIT_NOT_FOUND RFC_UNIT_IN_PROCESS RFC_UNIT_COMMITTED RFC_UNIT_ROLLED_BACK RFC_UNIT_CONFIRMED
initialize_unit([background=True])

Initializes a logical unit of work (LUW), shorthand: unit

Warning

The background protocol (bgRFC) is not working in the current version. Please use only tRFC/qRFC protocols.

Parameters:background (boolean) – The bgRFC protocol will be used. If set to False, the t/qRFC protocol will be used. Note that the bgRFC protocol has extended functionality. Default: True
Returns:A dictionary describing the unit.
ping()

Send a RFC Ping through the current connection

Returns nothing.

Raises:RFCError or a subclass thereof if the RFC Ping fails.
reset_server_context()

Resets the SAP server context (“user context / ABAP session context”) associated with the given client connection, but does not close the connection

Raises:RFCError or a subclass thereof in case resetting the server context fails. (Better close the connection in that case.). sapnwrf2.CommunicationError if no conversion was found for the

Server

class pyrfc.Server

An SAP server

An instance of Server allows for installing Python callback functions and serve requests from SAP systems.

Parameters:
  • config (dict or None (default)) –

    Configuration of the instance. Allowed keys are:

    rstrip
    right strips strings passed to Python callback functions. (default is True)
    debug
    For testing/debugging operations. If True, the server behaves more permissive, e.g. allows incoming calls without a valid connection handle. (default is False)
  • params (Keyword parameters) – Parameters for registering the server. The parameters may contain the following keywords: GWHOST, GWSERV, PROGRAM_ID, TRACE, and SAPROUTER.
Raises:

RFCError or a subclass thereof if the connection attempt fails.

rstrip

If True, strings passed to the callback functions are right stripped. For details see rstrip.

debug

If True, the server behaves more permissive, e.g. allows incoming calls without a valid connection handle.

close()

Explicitly close the registration.

Note that this is usually not necessary as the registration will be closed automatically upon object destruction. However, if the the object destruction is delayed by the garbage collection, problems may occur when too many servers are registered.

install_function(func_name, callback)

Installs a function in the server.

Parameters:
  • func_desc – A function description object of FunctionDescription
  • callback – A callback function that implements the logic. The function must accept a request_context parameter and all IMPORT, CHANGING, and TABLE parameters of the given func_desc.
Raises:

TypeError if a function with the name given is already installed.

serve(timeout)

Serves for a given timeout. Note: internally this function installs a generic server function and registers the server at the gateway (if required).

Parameters:timeout – Number of seconds to serve or None (default) for no timeout.
Raises:RFCError or a subclass thereof if the installation or the registration attempt fails.

FunctionDescription

Note

Actually, the FunctionDescription class does not support exceptions.

class pyrfc.FunctionDescription

A function description

This class wraps the RFC_FUNCTION_DESC_HANDLE as e.g. returned by RfcGetFunctionDesc() and used for server functionality.

Warning

Actually, the function description does not support exceptions (cf. RfcAddException() etc.)

Parameters:name – Name of the function.

Attributes and methods

name
The name of the function.
parameters
The parameters as a list of dicts.
add_parameter(name, parameter_type, direction, nuc_length, uc_length[, decimals=0[, default_value=""[, parameter_text=""[, optional=False[, type_description=None]]]]])

Adds a parameter to the function description.

Parameters:
  • name (string (30)) – Parameter name
  • parameter_type (string) – Type of the parameter
  • direction (string) – Direction (RFC_IMPORT, RFC_EXPORT, RFC_CHANGING, RFC_TABLES)
  • nuc_length (int) – NUC length
  • uc_length (int) – UC length
  • decimals (int) – Decimals (default=0)
  • default_value (string (30)) – Default value (default=”“)
  • parameter_text (string (79)) – Parameter text (default=”“)
  • optional (bool) – Is the parameter optional (default=False)
  • type_description (object of class TypeDescription) – An object of class TypeDescription or None (default=None)

TypeDescription

class pyrfc.TypeDescription

A type description

This class wraps the RFC_TYPE_DESC_HANDLE as e.g. contained in a parameter description of a function description.

Parameters:
  • name – Name of the type.
  • nuc_length – Length of the type in non unicode systems.
  • uc_length – Length of the type in unicode systems.

Attributes and methods

name
The name of the function.
nuc_length
The length in bytes if chars are non unicode.
uc_length
The length in bytes if chars are unicode.
fields
The fields as a list of dicts.
add_field(name, field_type, nuc_length, uc_length, nuc_offset, uc_offset[, decimals=0[, type_description=None]])

Adds a field to the type description.

Parameters:
  • name (string (30)) – Field name
  • field_type (string) – Type of the field
  • nuc_length (int) – NUC length
  • uc_length (int) – UC length
  • nuc_offset (int) – NUC offset.
  • uc_offset (int) – UC offset.
  • decimals (int) – Decimals (default=0)
  • type_description (object of class TypeDescription) – An object of class TypeDescription or None (default=None)

Errors

If a problem occurs in the Python connector or in an underlying component (e.g. C connector, SAP system, ABAP code, …), an exception is raised. The class of the exception indicates where the problem occurred.

  1. RFCError: This error is raised, if a problem occurred in the Python connector.
  2. RFCLibError: This error is raised, if a problem occurred in the C connector.
  3. All other errors represent errors with the RFC call to the SAP backend system. For these errors, the errorInfo struct of the C connector is wrapped, e.g. for a given exception e, the error code is available in e.code. The class of the error depends on the group of the error.
Inheritance of errors: Exception->RFCError->RFCLibError->specific errors
exception pyrfc.RFCError

Exception base class

Indicates that there was an error in the Python connector.

exception pyrfc.RFCLibError(message=None, code=None, key=None, msg_class=None, msg_type=None, msg_number=None, msg_v1=None, msg_v2=None, msg_v3=None, msg_v4=None)

RFC library error

Base class for exceptions raised by the local underlying C connector (sapnwrfc.c).

exception pyrfc.LogonError(message=None, code=2, key=u'RFC_LOGON_FAILURE', msg_class=None, msg_type=None, msg_number=None, msg_v1=None, msg_v2=None, msg_v3=None, msg_v4=None)

Logon error

This exception is raised if a RFC call returns an RC code greater than 0 and the error object has an RFC_ERROR_GROUP value of LOGON_FAILURE.

exception pyrfc.CommunicationError(message=None, code=None, key=None, msg_class=None, msg_type=None, msg_number=None, msg_v1=None, msg_v2=None, msg_v3=None, msg_v4=None)

Communication error

This exception is raised if a RFC call returns an RC code greater than 0 and the error object has an RFC_ERROR_GROUP value of COMMUNICATION_FAILURE.

exception pyrfc.ABAPApplicationError(message=None, code=None, key=None, msg_class=None, msg_type=None, msg_number=None, msg_v1=None, msg_v2=None, msg_v3=None, msg_v4=None)

ABAP application error

This exception is raised if a RFC call returns an RC code greater than 0 and the error object has an RFC_ERROR_GROUP value of ABAP_APPLICATION_FAILURE.

exception pyrfc.ABAPRuntimeError(message=None, code=None, key=None, msg_class=None, msg_type=None, msg_number=None, msg_v1=None, msg_v2=None, msg_v3=None, msg_v4=None)

ABAP runtime error

This exception is raised if a RFC call returns an RC code greater than 0 and the error object has an RFC_ERROR_GROUP value of ABAP_RUNTIME_FAILURE.

exception pyrfc.ExternalAuthorizationError(message=None, code=None, key=None, msg_class=None, msg_type=None, msg_number=None, msg_v1=None, msg_v2=None, msg_v3=None, msg_v4=None)

External authorization error

This exception is raised if a RFC call returns an RC code greater than 0 and the error object has an RFC_ERROR_GROUP value of EXTERNAL_AUTHORIZATION_FAILURE.

exception pyrfc.ExternalRuntimeError(message=None, code=None, key=None, msg_class=None, msg_type=None, msg_number=None, msg_v1=None, msg_v2=None, msg_v3=None, msg_v4=None)

External runtime error

This exception is raised if a RFC call returns an RC code greater than 0 and the error object has an RFC_ERROR_GROUP value of EXTERNAL_RUNTIME_FAILURE.

exception pyrfc.ExternalApplicationError(message=None, code=None, key=None, msg_class=None, msg_type=None, msg_number=None, msg_v1=None, msg_v2=None, msg_v3=None, msg_v4=None)

External application error

This exception is raised if a RFC call returns an RC code greater than 0 and the error object has an RFC_ERROR_GROUP value of EXTERNAL_APPLICATION_FAILURE.

Error types, codes, groups, and classes

Schmidt and Li (2009a) describe four possible error types on the basis of the return code (i.e. error code) of a RFM invocation:

  • ABAP exception,
  • system failure,
  • ABAP messages, and
  • communication failure.

However, there are in total roughly 30 possible return codes that indicate some kind of error. As each error information struct provides an error group information with seven possible groups, which was taken as the basis for the exception classes.

The following table should facilitate the matching between the different error representations.

type (SPJ) code [numeric] (C) group (C) class (Python)
ABAP exception RFC_ABAP_EXCEPTION [5] ABAP_APPLICATION_FAILURE ABAPApplicationError
system failure RFC_ABAP_RUNTIME_FAILURE [3] ABAP_RUNTIME_FAILURE ABAPRuntimeError
ABAP message RFC_ABAP_MESSAGE [4] ABAP_RUNTIME_FAILURE ABAPRuntimeError
communication failure RFC_COMMUNICATION_FAILURE [1] COMMUNICATION_FAILURE CommunicationError
RFC_LOGON_FAILURE [2] LOGON_FAILURE LogonError