Example #1
1
def get_table_info(**kwargs):
    try:
        host = kwargs["host"]
        sysnr = kwargs["sysnr"]
        client = kwargs["client"]
        user = kwargs["user"]
        pwd = kwargs["pass"]
        table_name = kwargs["table"]
        conn = Connection(ashost=host,
                          sysnr=sysnr,
                          client=client,
                          user=user,
                          passwd=pwd)
        options = [{'TEXT': "TABNAME = '{}'".format(table_name)}]
        fields = [{
            'FIELDNAME': 'TABNAME'
        }, {
            'FIELDNAME': 'FIELDNAME'
        }, {
            'FIELDNAME': 'POSITION'
        }, {
            'FIELDNAME': 'DDTEXT'
        }]
        rows_at_a_time = 100
        row_skips = 0
        print('| TABNAME | FIELDNAME |  POSITION| DDTEXT |')
        print('| --- | --- | --- | --- |')
        while True:
            result = conn.call('RFC_READ_TABLE',
                               QUERY_TABLE='DD03VT',
                               OPTIONS=options,
                               FIELDS=fields,
                               ROWSKIPS=row_skips,
                               ROWCOUNT=rows_at_a_time,
                               DELIMITER='|')
            for row in result['DATA']:
                print('| ' +
                      ' | '.join([r.strip()
                                  for r in row['WA'].split('|')]) + ' |')

            row_skips += rows_at_a_time
            if len(result['DATA']) < rows_at_a_time:
                break

    except CommunicationError:
        print(u"Could not connect to server.")
        raise
    except LogonError:
        print(u"Could not log in. Wrong credentials?")
        raise
    except (ABAPApplicationError, ABAPRuntimeError):
        print(u"An error occurred.")
        raise
Example #2
1
from pyrfc import Server, Connection, RFCError, RFCLibError, \
                      ABAPApplicationError, ABAPRuntimeError, \
                      ExternalRuntimeError
from pyrfc._pyrfc import _Testing

from ConfigParser import ConfigParser
import sys

config = ConfigParser()
config.read('sapnwrfc.cfg')
params_connection = config._sections['connection']
conn = Connection(**params_connection)
test = _Testing()

# Instantiate server
params_gateway = config._sections['gateway']
# server = Server(config={'debug': True}, **params_gateway)
server = Server(config={'debug': True}, **params_gateway)

# Create callback functions and retrieve correspondent descriptions
#def my_stfc_connection(**kwargs):
#    print "my_stfc_connection was called with arguments: {}".format(kwargs)
#    return {
#        'ECHOTEXT': kwargs['REQUTEXT'],
#        'RESPTEXT': u"Local server here."
#    }
def my_stfc_connection(request_context, REQUTEXT=""):
    #print "my_stfc_connection was called with arguments: {}".format(kwargs)
    return {
        'ECHOTEXT': REQUTEXT,
        'RESPTEXT': u"Local server here."
def get_data_by_batch(batch_count):
    """
    分批获取SAP数据,batch_count作为RFC_READ_TABLE的rowcount,
    rowskips也依据该参数变化
    """
    ROWS_AT_A_TIME = batch_count
    row_skips = 0

    try:
        logon_params = get_sap_logon_params()
        sapconn = Connection(**logon_params)

        while True:
            result = sapconn.call('RFC_READ_TABLE',
                                  QUERY_TABLE='TSTCT',
                                  DELIMITER=',',
                                  ROWSKIPS=row_skips,
                                  ROWCOUNT=ROWS_AT_A_TIME)

            print(row_skips)
            row_skips += ROWS_AT_A_TIME
            yield result["DATA"]
            if len(result['DATA']) < ROWS_AT_A_TIME:
                break
    except CommunicationError:
        print("Could not connect to server.")
        raise
    except LogonError:
        print("Could not log in. Wrong credentials?")
        raise
    except (ABAPApplicationError, ABAPRuntimeError):
        print("An error occurred.")
        raise
Example #4
0
class AbapRfc:
    def __init__(self, router):
        self.imp = ConfigFile(router)
        #ssh parameter
        self.ahost = self.imp.parameter('RFC-CONFIG', 'ashost')
        self.sysnr = self.imp.parameter('RFC-CONFIG', 'sysnr')
        self.client = self.imp.parameter('RFC-CONFIG', 'client')
        self.user = self.imp.parameter('RFC-CONFIG', 'user')
        self.password = self.imp.parameter('RFC-CONFIG', 'password')

    def rfc_connect(self):
        try:
            self.conn = Connection(ashost=self.ahost,
                                   sysnr=self.sysnr,
                                   client=self.client,
                                   user=self.user,
                                   passwd=self.password)
        except Exception as e:
            print('call rfc failure!')

    # run command action
    def run(self, rfc, title, fix_format, command_arg, output):
        if rfc == 'ENQUE_REPORT':
            result = self.conn.call(rfc, GCLIENT='', GUNAME='')
        else:
            result = self.conn.call(rfc)
        Show_Formatter(fix_format, result, title, command_arg, output)
Example #5
0
 def __init__(self):
     self.conn = Connection(user='******',
                            passwd='PASS',
                            ashost='AHOST',
                            sysnr='SYSNR',
                            client='CLIENT',
                            lang='EN')
def main(function_name):
    config = ConfigParser()
    config.read('sapnwrfc.cfg')
    params_connection = config._sections['connection']

    try:
        connection = Connection(**params_connection)
        func_desc = connection.get_function_description(function_name)
        print u"Parameters of function: {0}".format(function_name)

        parameter_keys = [u'name', u'parameter_type', u'direction',
                          u'nuc_length', u'uc_length', u'decimals',
                          u'default_value', u'optional',
                          u'type_description', u'parameter_text']
        parameter_widths = [20, 17, 11, 10, 9, 9, 15, 10, 15, 20]
        for key, width in zip(parameter_keys, parameter_widths):
            sys.stdout.write(u"{0}".format(key).ljust(width).upper() + u" ")
        sys.stdout.write(u"\n")

        for parameter in sorted(func_desc.parameters, key=parameter_key_function):
            for key, width in zip(parameter_keys, parameter_widths):
                if key == u'type_description' and parameter[key] is not None:
                    sys.stdout.write(
                        u"{0}".format(parameter[key].name).ljust(width) + u" "
                    )
                else:
                    sys.stdout.write(
                        u"{0}".format(parameter[key]).ljust(width) + u" "
                    )
            sys.stdout.write(u"\n")
            type_desc = parameter['type_description']
            if type_desc is not None:
                # type_desc of class TypeDescription
                field_keys = [u'name', u'field_type', u'nuc_length',
                              u'nuc_offset', u'uc_length', u'uc_offset',
                              u'decimals', u'type_description']
                field_widths = [20, 17, 10, 10, 9, 9, 10, 15]

                sys.stdout.write(u" " * 4 + u"-----------( Structure of {0.name} (n/uc_length={0.nuc_length}/{0.uc_length})--\n".format(type_desc))
                for key, width in zip(field_keys, field_widths):
                    sys.stdout.write(u"{0}".format(key).ljust(width).upper() + u" ")
                sys.stdout.write(u"\n")

                for field_description in type_desc.fields:
                    for key, width in zip(field_keys, field_widths):
                        sys.stdout.write(u"{0}".format(field_description[key]).ljust(width) + u" ")
                    sys.stdout.write(u"\n")
                sys.stdout.write(u" " * 4 + u"-----------( Structure of {0.name} )-----------\n".format(type_desc))
            sys.stdout.write(u"-" * sum(parameter_widths) + u"\n")
        connection.close()

    except CommunicationError:
        print u"Could not connect to server."
        raise
    except LogonError:
        print u"Could not log in. Wrong credentials?"
        raise
    except (ABAPApplicationError, ABAPRuntimeError):
        print u"An error occurred."
        raise
Example #7
0
def main(function_name):
    config = ConfigParser()
    config.read('sapnwrfc.cfg')
    params_connection = config._sections['connection']

    try:
        connection = Connection(**params_connection)
        func_desc = connection.get_function_description(function_name)
        print (u"Parameters of function: {0}".format(function_name))

        parameter_keys = [u'name', u'parameter_type', u'direction',
                          u'nuc_length', u'uc_length', u'decimals',
                          u'default_value', u'optional',
                          u'type_description', u'parameter_text']
        parameter_widths = [20, 17, 11, 10, 9, 9, 15, 10, 15, 20]
        for key, width in zip(parameter_keys, parameter_widths):
            sys.stdout.write(u"{0}".format(key).ljust(width).upper() + u" ")
        sys.stdout.write(u"\n")

        for parameter in sorted(func_desc.parameters, key=parameter_key_function):
            for key, width in zip(parameter_keys, parameter_widths):
                if key == u'type_description' and parameter[key] is not None:
                    sys.stdout.write(
                        u"{0}".format(parameter[key].name).ljust(width) + u" "
                    )
                else:
                    sys.stdout.write(
                        u"{0}".format(parameter[key]).ljust(width) + u" "
                    )
            sys.stdout.write(u"\n")
            type_desc = parameter['type_description']
            if type_desc is not None:
                # type_desc of class TypeDescription
                field_keys = [u'name', u'field_type', u'nuc_length',
                              u'nuc_offset', u'uc_length', u'uc_offset',
                              u'decimals', u'type_description']
                field_widths = [20, 17, 10, 10, 9, 9, 10, 15]

                sys.stdout.write(u" " * 4 + u"-----------( Structure of {0.name} (n/uc_length={0.nuc_length}/{0.uc_length})--\n".format(type_desc))
                for key, width in zip(field_keys, field_widths):
                    sys.stdout.write(u"{0}".format(key).ljust(width).upper() + u" ")
                sys.stdout.write(u"\n")

                for field_description in type_desc.fields:
                    for key, width in zip(field_keys, field_widths):
                        sys.stdout.write(u"{0}".format(field_description[key]).ljust(width) + u" ")
                    sys.stdout.write(u"\n")
                sys.stdout.write(u" " * 4 + u"-----------( Structure of {0.name} )-----------\n".format(type_desc))
            sys.stdout.write(u"-" * sum(parameter_widths) + u"\n")
        connection.close()

    except CommunicationError:
        print u"Could not connect to server."
        raise
    except LogonError:
        print u"Could not log in. Wrong credentials?"
        raise
    except (ABAPApplicationError, ABAPRuntimeError):
        print u"An error occurred."
        raise
 def __init__(self):
     ASHOST=os.getenv('AHOST')
     CLIENT=os.getenv('CLIENT')
     SYSNR=os.getenv('SYSNR')
     USER=os.getenv('USER')
     PASSWD=os.getenv('PASSWD')
     self.conn = Connection(ashost=ASHOST, sysnr=SYSNR, client=CLIENT, user=USER, passwd=PASSWD)
Example #9
0
class TestTT:
    """
    This test cases cover table types of variable and structure types
    """
    def setup_method(self, test_method):
        self.conn = Connection(**params)
        assert self.conn.alive

    def teardown_method(self, test_method):
        self.conn.close()
        assert not self.conn.alive

    def test_TABLE_TYPE(self):
        result = self.conn.call(
            "/COE/RBP_PAM_SERVICE_ORD_CHANG",
            IV_ORDERID="4711",
            IT_NOTICE_NOTIFICATION=[{
                "": "ABCD"
            }, {
                "": "XYZ"
            }],
        )
        assert len(result["ET_RETURN"]) > 0
        erl = result["ET_RETURN"][0]
        assert erl["TYPE"] == "E"
        assert erl["ID"] == "IWO_BAPI"
        assert erl["NUMBER"] == "121"
        assert erl["MESSAGE_V1"] == "4711"
    def __init__(self, systemid):
        """
        :param systemid: configured in sapnwrfc.cft file
        """

        self.systemid = systemid
        self.sap_connection = Connection(**get_sap_logon_params(systemid))
Example #11
0
def main():
    config = ConfigParser()
    config.read("sapnwrfc.cfg")
    params_connection = config._sections["connection"]

    conn = Connection(**params_connection)
    result = conn.call("STFC_STRUCTURE", IMPORTSTRUCT=imp)
    pprint(result)
Example #12
0
def main():
    config = ConfigParser()
    config.read('sapnwrfc.cfg')
    params_connection = config._sections['connection']

    conn = Connection(**params_connection)
    result = conn.call('STFC_STRUCTURE', IMPORTSTRUCT=imp)
    pprint(result)
Example #13
0
 def rfc_connect(self):
     try:
         self.conn = Connection(ashost=self.ahost,
                                sysnr=self.sysnr,
                                client=self.client,
                                user=self.user,
                                passwd=self.password)
     except Exception as e:
         print('call rfc failure!')
Example #14
0
def run(COUNT):
    conn = Connection(**MME)
    result = conn.call(
        'STFC_PERFORMANCE', **{
            'CHECKTAB': 'X',
            'LGET0332': str(COUNT),
            'LGET1000': str(COUNT)
        })
    return result
Example #15
0
def move_current_variant():
    npl_login.set_target_sys('NPL_DEMO')
    conn = Connection(user=npl_login.get_user_name(),
                      passwd=npl_login.get_pass(),
                      ashost=npl_login.get_host(),
                      sysnr=npl_login.get_sap_num(),
                      client=npl_login.get_sap_mandant())
    result = conn.call('Z_BC009_PY_INPUT', IV_DO_CURRENT=ABAP_TRUE)
    return_msg = result.get('RC_TXT')
    print(return_msg)
Example #16
0
 def __init__(self):
     ASHOST = '10.50.x.x'
     CLIENT = '740'
     SYSNR = '01'
     USER = '******'
     PASSWD = 'pass'
     self.conn = Connection(ashost=ASHOST,
                            sysnr=SYSNR,
                            client=CLIENT,
                            user=USER,
                            passwd=PASSWD)
Example #17
0
class TestOptions:
    def setup_method(self, test_method):
        self.conn = Connection(**params)
        assert self.conn.alive

    def teardown_method(self, test_method):
        self.conn.close()
        assert not self.conn.alive

    def test_pass_when_not_requested(self):
        PLNTY = "A"
        PLNNR = "00100000"
        NOT_REQUESTED = [
            "ET_COMPONENTS",
            "ET_HDR_HIERARCHY",
            "ET_MPACKAGES",
            "ET_OPERATIONS",
            "ET_OPR_HIERARCHY",
            "ET_PRTS",
            "ET_RELATIONS",
        ]
        result = self.conn.call(
            "EAM_TASKLIST_GET_DETAIL",
            {"not_requested": NOT_REQUESTED},
            IV_PLNTY=PLNTY,
            IV_PLNNR=PLNNR,
        )
        assert len(result["ET_RETURN"]) == 0

    def test_error_when_all_requested(self):
        PLNTY = "A"
        PLNNR = "00100000"
        result = self.conn.call("EAM_TASKLIST_GET_DETAIL",
                                IV_PLNTY=PLNTY,
                                IV_PLNNR=PLNNR)
        assert len(result["ET_RETURN"]) == 1
        assert result["ET_RETURN"][0] == {
            "TYPE": "E",
            "ID": "DIWP1",
            "NUMBER": "212",
            "MESSAGE": "Task list A 00100000  is not hierarchical",
            "LOG_NO": "",
            "LOG_MSG_NO": "000000",
            "MESSAGE_V1": "A",
            "MESSAGE_V2": "00100000",
            "MESSAGE_V3": "",
            "MESSAGE_V4": "",
            "PARAMETER": "HIERARCHY",
            "ROW": 0,
            "FIELD": "",
            "SYSTEM": "MMECLNT620",
        }
    def __init__(self):
        self.config = ConfigParser()
        self.config.read(os.environ["HOME"] + '/.config/sap_config.cnf')
        self.creds = self.config['SAP']

        self.conn = Connection(user=self.creds['user'],
                               passwd=self.creds['passwd'],
                               ashost=self.creds['ashost'],
                               sysnr=self.creds['sysnr'],
                               sid=self.creds['sid'],
                               client=self.creds['client'])

        self.preRefresh = PreSystemRefresh()
Example #19
0
def test_utclong_rejects_non_string_or_invalid_format():
    UTCLONG = RFC_MATH["UTCLONG"]
    conn = Connection(**connection_info("QM7"))
    try:
        res = conn.call("ZDATATYPES", IV_UTCLONG=1)
    except Exception as ex:
        assert isinstance(ex, TypeError) is True
        assert ex.args == (
            "an string is required, received",
            1,
            "of type",
            type(1),
            "IV_UTCLONG",
        )

    try:
        res = conn.call("ZDATATYPES", IV_UTCLONG="1")
    except Exception as ex:
        assert isinstance(ex, ExternalRuntimeError) is True
        assert ex.code == 22
        assert ex.key == "RFC_CONVERSION_FAILURE"
        assert ex.message == "Cannot convert 1 to RFCTYPE_UTCLONG : illegal format"

    conn.close()
    #
    # TypeError:

    # res = conn.call("ZDATATYPES", IV_UTCLONG="1")
    # pyrfc._exception.ExternalRuntimeError: RFC_CONVERSION_FAILURE (rc=22): key=RFC_CONVERSION_FAILURE, message=Cannot convert 1 to RFCTYPE_UTCLONG : illegal format [MSG: class=, type=, number=, v1-4:=;;

    conn.close()
Example #20
0
def print_list():
    npl_login.set_target_sys('NPL_DEMO')
    conn = Connection(user=npl_login.get_user_name(),
                      passwd=npl_login.get_pass(),
                      ashost=npl_login.get_host(),
                      sysnr=npl_login.get_sap_num(),
                      client=npl_login.get_sap_mandant())
    result = conn.call('Z_BC009_PY_INPUT', GET_MY_LIST=ABAP_TRUE)
    request_list = result.get('REQ_LIST')

    for request_info in request_list:
        print(f"{request_info.get('TRKORR')} | {request_info.get('AS4TEXT')}")

    return_msg = result.get('RC_TXT')
    print(return_msg)
Example #21
0
class nw:

    def __init__(self):
        # Connect to Netweaver
        self.conn = Connection(ashost=param.bw_ip, sysnr='00', client='001', user='******', passwd=param.bw_passwd)

    def dso_update(self, data):
        # Update DSO
        self.conn.call('Z_UPDATE_BOT_DSO', I_TABLE=data)

    def get_data(self):
        # Get DSO data
        result = self.conn.call('RFC_READ_TABLE', QUERY_TABLE=u'/BIC/AZBOT0100', DELIMITER=u';')
        data = result.get('DATA')
        return data
Example #22
0
class main():
    def __init__(self):
        ASHOST = '10.50.x.x'
        CLIENT = '740'
        SYSNR = '01'
        USER = '******'
        PASSWD = 'pass'
        self.conn = Connection(ashost=ASHOST,
                               sysnr=SYSNR,
                               client=CLIENT,
                               user=USER,
                               passwd=PASSWD)

    def qry(self, Fields, SQLTable, Where='', MaxRows=50, FromRow=0):
        """A function to query SAP with RFC_READ_TABLE"""

        # By default, if you send a blank value for fields, you get all of them
        # Therefore, we add a select all option, to better mimic SQL.
        if Fields[0] == '*':
            Fields = ''
        else:
            Fields = [{'FIELDNAME': x} for x in Fields]  # Notice the format

        # the WHERE part of the query is called "options"
        options = [{'TEXT': x} for x in Where]  # again, notice the format

        # we set a maximum number of rows to return, because it's easy to do and
        # greatly speeds up testing queries.
        rowcount = MaxRows

        # Here is the call to SAP's RFC_READ_TABLE
        tables = self.conn.call("BBP_RFC_READ_TABLE",
                                QUERY_TABLE=SQLTable,
                                DELIMITER='|',
                                FIELDS=Fields,
                                OPTIONS=options,
                                ROWCOUNT=MaxRows,
                                ROWSKIPS=FromRow)

        # We split out fields and fields_name to hold the data and the column names
        fields = []
        fields_name = []

        data_fields = tables["DATA"]  # pull the data part of the result set
        data_names = tables[
            "FIELDS"]  # pull the field name part of the result set

        headers = [x['FIELDNAME'] for x in data_names]  # headers extraction
        long_fields = len(data_fields)  # data extraction
        long_names = len(data_names)  # full headers extraction if you want it

        # now parse the data fields into a list
        for line in range(0, long_fields):
            fields.append(data_fields[line]["WA"].strip())

        # for each line, split the list by the '|' separator
        fields = [x.strip().split('|') for x in fields]

        # return the 2D list and the headers
        return fields, headers
    def _rfcGetSystemTime(self, connection: Connection):
        rfcName = 'BDL_GET_CENTRAL_TIMESTAMP'
        timestampResult = None

        try:
            timestampResult = connection.call(rfcName)
            return timestampResult
        except CommunicationError as e:
            self.tracer.error(
                "[%s] communication error for rfc %s with hostname: %s (%s)",
                self.logTag,
                rfcName,
                self.fqdn,
                e,
                exc_info=True)
        except Exception as e:
            self.tracer.error(
                "[%s] Error occured for rfc %s with hostname: %s (%s)",
                self.logTag,
                rfcName,
                self.fqdn,
                e,
                exc_info=True)

        return None
Example #24
0
 def _connect(self, profile):
     """
     Provides connection to an SAP backend system
     :param profile: path to an SAP connection profile.
     :return: pyrfc.Connection (https://sap.github.io/PyRFC/pyrfc.html)
     """
     return Connection(**self._read_profile(profile))
class ServerGroup:
    connection: Connection = None
    setup_list: list = None

    def __init__(self, host, sysnr, client, user, passwd):
        self.set_connection(host, sysnr, client, user, passwd)

    def set_connection(self, host, sysnr, client, user, passwd):
        self.connection = Connection(ashost=host,
                                     sysnr=sysnr,
                                     client=client,
                                     user=user,
                                     passwd=passwd)

    def call(self, func_name: str, *args, **kargs):
        return self.connection.call(func_name, *args, **kargs)

    def set_up(self, group_type):
        res = self.call('SMLG_GET_SETUP', GROUPTYPE=group_type)
        self.setup_list = res.get('SETUP', [])

    def smlg_modify(self, group_type, classname, applserver, modificatn):
        dst = {
            'CLASSNAME': classname,
            'APPLSERVER': applserver,
            'MODIFICATN': modificatn,
        }
        self.call("SMLG_MODIFY", GROUPTYPE=group_type, MODIFICATIONS=[dst])
    def _rfcGetSmonRunIds(self, connection: Connection,
                          startDateTime: datetime, endDateTime: datetime):
        rfcName = '/SDF/SMON_GET_SMON_RUNS'

        self.tracer.info(
            "[%s] invoking rfc %s for hostname=%s with from_date=%s, to_date=%s",
            self.logTag, rfcName, self.sapHostName, startDateTime.date(),
            endDateTime.date())

        try:
            smon_result = connection.call(rfcName,
                                          FROM_DATE=startDateTime.date(),
                                          TO_DATE=endDateTime.date())
            return smon_result
        except CommunicationError as e:
            self.tracer.error(
                "[%s] communication error for rfc %s with hostname: %s (%s)",
                self.logTag,
                rfcName,
                self.sapHostName,
                e,
                exc_info=True)
        except Exception as e:
            self.tracer.error(
                "[%s] Error occured for rfc %s with hostname: %s (%s)",
                self.logTag,
                rfcName,
                self.sapHostName,
                e,
                exc_info=True)

        return None
    def _rfcGetSwncWorkloadSnapshot(self, connection: Connection,
                                    startDateTime: datetime,
                                    endDateTime: datetime):
        rfcName = 'SWNC_GET_WORKLOAD_SNAPSHOT'

        self.tracer.info((
            "[%s] invoking rfc %s for hostname=%s with read_start_date=%s, read_start_time=%s, "
            "read_end_date=%s, read_end_time=%s"), self.logTag, rfcName,
                         self.sapHostName, startDateTime.date(),
                         startDateTime.time(), endDateTime.date(),
                         endDateTime.time())

        try:
            swnc_result = connection.call(rfcName,
                                          READ_START_DATE=startDateTime.date(),
                                          READ_START_TIME=startDateTime.time(),
                                          READ_END_DATE=endDateTime.date(),
                                          READ_END_TIME=endDateTime.time())
            return swnc_result
        except CommunicationError as e:
            self.tracer.error(
                "[%s] communication error for rfc %s with hostname: %s (%s)",
                self.logTag, rfcName, self.sapHostName, e)
        except Exception as e:
            self.tracer.error(
                "[%s] Error occured for rfc %s with hostname: %s (%s)",
                self.logTag, rfcName, self.sapHostName, e)

        return None
Example #28
0
def move_requests():
    req_line = ''
    req_line = str(input("TR1,TR2?    "))
    if req_line is None:
        return
    if req_line == 'e':
        return
    npl_login.set_target_sys('NPL_DEMO')
    conn = Connection(user=npl_login.get_user_name(),
                      passwd=npl_login.get_pass(),
                      ashost=npl_login.get_host(),
                      sysnr=npl_login.get_sap_num(),
                      client=npl_login.get_sap_mandant())
    result = conn.call('Z_BC009_PY_INPUT', IV_REQ_LIST=req_line)
    return_msg = result.get('RC_TXT')
    print(return_msg)
Example #29
0
 def test_create_with_multiple_connection(self):
     c1 = Connection(**params)
     c2 = Connection(**params)
     throughput = Throughput([c1, c2])
     assert len(throughput.connections) == 2
     throughput = Throughput([c1, c1])
     assert len(throughput.connections) == 1
     c1.close()
     c2.close()
Example #30
0
class TestMRFC:
    """
    This test cases cover selected functions from the MRFC function group.
    """

    def setup_method(self, test_method):
        self.conn = Connection(**params)
        assert self.conn.alive

    def test_info(self):
        connection_info = self.conn.get_connection_attributes()
        assert connection_info["isoLanguage"] == u"EN"

    def teardown_method(self, test_method):
        self.conn.close()
        assert not self.conn.alive

    """
    @unittest.skip("not remote-enabled")
    def test_ABAP4_CALL_TRANSACTION_VB(self):
        # ABAP4_CALL_TRANSACTION_VB
        pass

    @unittest.skip("not remote-enabled")
    def test_IS_VERIRUN_ACTIVE(self):
        # IS_VERIRUN_ACTIVE Determine Whether a Verification Run is Active
        pass

    @unittest.skip("not supported yet (trfc)")
    def test_RFC_CALL_TRANSACTION_USING(self):
        # RFC_CALL_TRANSACTION_USING Verification Program for Execution of RFCs via CALL TRANSACTION USING
        pass

    # ToDo: Class based exceptions
    def test_RFC_CLASS_BASED_EXCP(self):
        # RFC_CLASS_BASED_EXCP RFC mit klassenbasierten Exceptions
        pass

    # TODO: How to test?
    @unittest.skip("not supported yet")
    def test_RFC_PING_AND_WAIT(self):
       # RFC_PING_AND_WAIT Aufruf und Warten
        pass
    """

    """
Example #31
0
def get_cache():
    with Connection(**connection_info) as con:
        table_cached = con.type_desc_get(table_name)
        struct_cached = con.type_desc_get(struct_name)
        return {
            table_name: vars(table_cached),
            struct_name: vars(struct_cached),
        }
Example #32
0
 def test_wsrfc_call_no_client_pse(self):
     try:
         client = Connection(dest="WS_ALX_NOCC")
     except Exception as ex:
         assert isinstance(ex, ExternalRuntimeError) is True
         assert ex.code == 20
         assert ex.key == "RFC_INVALID_PARAMETER"
         assert ex.message == "Unable to use TLS with client PSE missing"
Example #33
0
class main():
    def __init__(self,server='testing'):
        config = ConfigParser()
        config.read('sapnwrfc.cfg')
        params_connection = config._sections[server]
        self.conn = Connection(**params_connection)

    def qry(self, Fields, SQLTable, Where = '', MaxRows=50, FromRow=0):
        """A function to query SAP with RFC_READ_TABLE"""

        # By default, if you send a blank value for fields, you get all of them
        # Therefore, we add a select all option, to better mimic SQL.
        if Fields[0] == '*':
            Fields = ''
        else:
            Fields = [{'FIELDNAME':x} for x in Fields] # Notice the format

        # the WHERE part of the query is called "options"
        options = [{'TEXT': x} for x in Where] # again, notice the format

        # we set a maximum number of rows to return, because it's easy to do and
        # greatly speeds up testing queries.
        rowcount = MaxRows

        # Here is the call to SAP's RFC_READ_TABLE
        tables = self.conn.call("RFC_READ_TABLE", QUERY_TABLE=SQLTable, DELIMITER='|', FIELDS = Fields, OPTIONS=options, ROWCOUNT = MaxRows, ROWSKIPS=FromRow)

        # We split out fields and fields_name to hold the data and the column names
        fields = []
        fields_name = []

        data_fields = tables["DATA"] # pull the data part of the result set
        data_names = tables["FIELDS"] # pull the field name part of the result set

        headers = [x['FIELDNAME'] for x in data_names] # headers extraction
        long_fields = len(data_fields) # data extraction
        long_names = len(data_names) # full headers extraction if you want it

        # now parse the data fields into a list
        for line in range(0, long_fields):
            fields.append(data_fields[line]["WA"].strip())

        # for each line, split the list by the '|' separator
        fields = [x.strip().split('|') for x in fields ]

        # return the 2D list and the headers
        return fields, headers

    def sql_query(self, Query, MaxRows=50, FromRow=0):
        pass
    def create_routing(self, Material='1680001S11PP111', Plant='8000', Sequence=u'管道预制', WorkCenter='JMH1PP02'):
        from datetime import datetime
        op= [{'VALID_FROM': datetime(2015,1,1),
               'VALID_TO_DATE': datetime(9999,12,31),
               'ACTIVITY': '0010',
               'CONTROL_KEY': 'PP01',
               'WORK_CNTR': 'JMH1PP02',
               'PLANT': '8000',
               'STANDARD_TEXT_KEY': '',
               'DESCRIPTION': 'abcdefg',
               'OPERATION_MEASURE_UNIT': 'EA',
               'STD_VALUE_01': '0.000',
               'STD_VALUE_02': '0.000',
               'STD_VALUE_03': '0.000',
               'BASE_QUANTITY': '1.000',
               'MIN_SEND_AHEAD_QTY': '0',
               'MAX_NO_OF_SPLITS': '1',
               'DENOMINATOR': '1',
               'NOMINATOR': '1'}]
        op[0]['WORK_CNTR']=WorkCenter
        op[0]['PLANT']=Plant
        op[0]['DESCRIPTION']=Sequence

        task= [{'GROUP_COUNTER': '01',
                 'VALID_FROM': datetime(2015,1,1),
                 'VALID_TO_DATE': datetime(9999,12,31),
                 'TASK_LIST_USAGE': '1',
                 'PLANT': '8000',
                 'TASK_LIST_STATUS': '4',
                 'TASK_MEASURE_UNIT': 'EA',
                 'LOT_SIZE_TO': '999'}]
        task[0]['PLANT']=Plant

        mta=[{'MATERIAL': '1680001S11PP111',
               'PLANT': '8000',
               'VALID_FROM':  datetime(2015,1,1),
               'VALID_TO_DATE': datetime(9999,12,31)}]
        mta[0]['MATERIAL']=Material
        mta[0]['PLANT']=Plant

        result = self.conn.call("ZPP_ROUTING_CREATE", TASK=task, MATERIALTASKALLOCATION=mta, OPERATION=op)
        print Material,result['O_FLAG']
        return result

    def write_bom(self, pcode='1680001S11PP111',option=0):
        sqlconn=MssqlConnection()
        if option==0:
            res=sqlconn.queryAll(
            """
            SELECT parent_material_code,plant,subsidiary_material_code,sap_code,quantity,unit,material_type,material_desc,type
            FROM production_bom
            WHERE parent_material_code = '%s'
            """%pcode)
        elif option==1:
            res=sqlconn.queryAll(
            """
            WITH RPL (parent_material_code,plant,subsidiary_material_code,sap_code,quantity,unit,material_type,material_desc,type) AS
            (SELECT ROOT.parent_material_code,ROOT.plant,ROOT.subsidiary_material_code,ROOT.sap_code,ROOT.quantity,ROOT.unit,ROOT.material_type,ROOT.material_desc,ROOT.type
            FROM production_bom ROOT
            WHERE ROOT.parent_material_code = '%s'
            Union ALL
            SELECT CHILD.parent_material_code,CHILD.plant,CHILD.subsidiary_material_code,CHILD.sap_code,CHILD.quantity,CHILD.unit,CHILD.material_type,CHILD.material_desc,CHILD    .type
            FROM RPL PARENT, production_bom CHILD
            WHERE Parent.subsidiary_material_code = Child.parent_material_code
            )
            SELECT parent_material_code,plant,subsidiary_material_code,sap_code,quantity,unit,material_type,material_desc
            FROM RPL
            where len(parent_material_code) = 15
            ORDER BY parent_material_code,subsidiary_material_code
            """%pcode)
        else:
             print "请在编码后增加写入方式参数(0为单层写入(缺省),1为多层写入)"
             return

        item=[]
        elem={}
        #i=0
        #print res
        for row in res:
            #print row
            elem= {'MATNR': row[0],
            'WERKS':  row[1],
            'IDNRK':  row[3],
            'MENGE':  row[4],
            'MEINS':  row[5],
            'STLAN': '1',
            'STLAL': '01',
            'DATUV': datetime(2015,1,2),
            'BMENG': '1',
            'STLST': '01',
            'POSTP': 'L',
            'SANKA': 'X',
            'PREIS': '0.01',
            'SAKTO': '4101010000'}
            item.append(elem)
            #i=i+1
        result = self.conn.call("ZBOM_CREATE_SMP2", T_ITEM=item)
        print result['T_RETURN'][0]['MSG']
        return result

    def isBomExist(self,material_code='1580150C5APP111'):
        fields = ['MATNR']
        table = 'MAST'
        where = ["MATNR = '%s'"%(material_code,)]
        maxrows = 10
        fromrow = 0
        results, headers = self.qry(fields, table, where, maxrows, fromrow)
        #print headers
        #print results
        if results:
            return True
        else:
            return False
Example #34
0
File: issue89.py Project: SAP/PyRFC
# -*- coding: utf-8 -*-

from abap_systems import DSP
from pyrfc import Connection

function_name = u'ZDT'
# umlauts = u'Hällo SAP!'
umlauts = u'Россия'
# umlauts = u'\u0420\u043e\u0441\u0441\u0438\u044f'

if __name__ == '__main__':
    conn = Connection(**DSP)
    res = conn.call(function_name, IN1=1, MTEXT=umlauts)
    # res = conn.call(function_name, REQUSTR=umlauts, REQUTEXT=umlauts)
    print umlauts
    print res
Example #35
0
File: issue38.py Project: SAP/PyRFC
from pyrfc import Connection

connection_info = {
    'user': '******',
    'passwd': 'Welcome',
    'ashost': '10.117.19.101',
    'saprouter': '/H/203.13.155.17/W/xjkb3d/H/172.19.138.120/H/',
    'sysnr': '00',
    'lang': 'EN',
    'client': '100',
    'sysid': 'S16'
}

conn = Connection(**connection_info)

float_value1 = 1.23456789
float_value2 = 9.87

i = 1

fv = float_value2
if i != 2:
    imp = dict(RFCFLOAT=fv,
               RFCINT2=0x7ffe, RFCINT1=0x7f,
               RFCCHAR4=u'bcde', RFCINT4=0x7ffffffe,
               RFCHEX3=str.encode('fgh'),
               RFCCHAR1=u'a', RFCCHAR2=u'ij',
               RFCTIME='123456',  # datetime.time(12,34,56),
               RFCDATE='20161231',  # datetime.date(2011,10,17),
               RFCDATA1=u'k'*50, RFCDATA2=u'l'*50
               )
import signal
import sys



config = ConfigParser()
config.read('sapnwrfc.cfg')

# Callback function
def my_stfc_connection(request_context, REQUTEXT=""):
    return {
        'ECHOTEXT': REQUTEXT,
        'RESPTEXT': u"Python server here. Connection attributes are: "
                    u"User '{user}' from system '{sysId}', client '{client}', "
                    u"host '{partnerHost}'".format(**request_context['connection_attributes'])
    }

# Open a connection for retrieving the metadata of 'STFC_CONNECTION'
params_connection = config._sections['connection']
conn = Connection(**params_connection)
func_desc_stfc_connection = conn.get_function_description("STFC_CONNECTION")

# Instantiate server with gateway information for registering, and
# install a function.
params_gateway = config._sections['gateway']
server = Server(**params_gateway)
server.install_function(func_desc_stfc_connection, my_stfc_connection)
print "--- Server registration and serving ---"
server.serve(20)
Example #37
0
File: test.py Project: SAP/PyRFC
from platform import system, release
from sys import version_info
from configparser import ConfigParser
from pyrfc import Connection, get_nwrfclib_version

config = ConfigParser()
config.read('pyrfc.cfg')
params = config._sections['test']

conn = Connection(**params)

print('Platform:', system(), release())
print('Python version:', version_info)
print('SAP NW RFC:', get_nwrfclib_version())


result = conn.call('/COE/RBP_PAM_SERVICE_ORD_CHANG', IV_ORDERID='4711', IT_NOTICE_NOTIFICATION=[{'': 'ABCD'}, {'': 'XYZ'}])

for line in result['ET_STRING']:
    print line

for line in result['ET_TABLE']:
    print line

result = conn.call('/COE/RBP_PAM_SERVICE_ORD_CHANG', IV_ORDERID='4711', IT_NOTICE_NOTIFICATION=['ABCD', 'XYZ'])

for line in result['ET_STRING']:
    print line

for line in result['ET_TABLE']:
    print line
Example #38
0
 def __init__(self,server='testing'):
     config = ConfigParser()
     config.read('sapnwrfc.cfg')
     params_connection = config._sections[server]
     self.conn = Connection(**params_connection)
Example #39
0
def run(COUNT):
    conn = Connection(**MME)
    result = conn.call('STFC_PERFORMANCE', **{
        'CHECKTAB': 'X', 'LGET0332': str(COUNT), 'LGET1000': str(COUNT)})
    return result
Example #40
0
from platform import system, release
from sys import version_info
from configparser import ConfigParser
from pyrfc import Connection, get_nwrfclib_version

config = ConfigParser()
config.read('tests/pyrfc.cfg')
params = config._sections['coe_he_66'] # or coevi51

conn = Connection(**params)

print('Platform:', system(), release())
print('Python version:', version_info)
print('SAP NW RFC:', get_nwrfclib_version())

PLNTY='A'
PLNNR='00100000'
NOT_REQUESTED = [
  'ET_COMPONENTS',
  'ET_HDR_HIERARCHY',
  'ET_MPACKAGES',
  'ET_OPERATIONS',
  'ET_OPR_HIERARCHY',
  'ET_PRTS',
  'ET_RELATIONS',
]

result = conn.call('EAM_TASKLIST_GET_DETAIL', {'not_requested': NOT_REQUESTED}, IV_PLNTY=PLNTY, IV_PLNNR=PLNNR)
assert len(result['ET_RETURN']) == 0

result = conn.call('EAM_TASKLIST_GET_DETAIL', IV_PLNTY=PLNTY, IV_PLNNR=PLNNR)