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
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 #3
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 #4
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",
        }
Example #5
0
def test_utclong_accepts_min_max_initial():
    UTCLONG = RFC_MATH["UTCLONG"]
    conn = Connection(**connection_info("QM7"))

    res = conn.call("ZDATATYPES", IV_UTCLONG=UTCLONG["MIN"])
    assert res["EV_UTCLONG"] == UTCLONG["MIN"]

    res = conn.call("ZDATATYPES", IV_UTCLONG=UTCLONG["MAX"])
    assert res["EV_UTCLONG"] == UTCLONG["MAX"]

    res = conn.call("ZDATATYPES", IV_UTCLONG=UTCLONG["INITIAL"])
    assert res["EV_UTCLONG"] == UTCLONG["INITIAL"]

    conn.close()
Example #6
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 #7
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
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 _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
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
    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 #13
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"
Example #14
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 #15
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 #16
0
def run(COUNT):
    conn = Connection(**MME)
    result = conn.call(
        'STFC_PERFORMANCE', **{
            'CHECKTAB': 'X',
            'LGET0332': str(COUNT),
            'LGET1000': str(COUNT)
        })
    return result
Example #17
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)
    def _rfcGetSmonAnalysisByRunId(self, connection: Connection, guid: str,
                                   startDateTime: datetime,
                                   endDateTime: datetime):
        rfcName = '/SDF/SMON_ANALYSIS_READ'
        result = None

        if not guid:
            raise ValueError(
                ("argument error for rfc %s for hostname: %s, guid: %s, "
                 "expected start (%s) and end time (%s) to be same day") %
                (rfcName, self.sapHostName, guid, startDateTime, endDateTime))

        # validate that start and end time are the same day, since thaty is what RFC expects
        if (startDateTime.date() != endDateTime.date()):
            raise ValueError(
                ("argument error for rfc %s for hostname: %s, guid: %s, "
                 "expected start (%s) and end time (%s) to be same day") %
                (rfcName, self.sapHostName, guid, startDateTime, endDateTime))

        self.tracer.info(
            "[%s] invoking rfc %s for hostname=%s with guid=%s, datum=%s, start_time=%s, end_time=%s",
            self.logTag, rfcName, self.sapHostName, guid, startDateTime.date(),
            startDateTime.time(), endDateTime.time())

        try:
            result = connection.call(rfcName,
                                     GUID=guid,
                                     DATUM=startDateTime.date(),
                                     START_TIME=startDateTime.time(),
                                     END_TIME=endDateTime.time())
            return 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
Example #19
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 #20
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 #21
0
 def getSWNCRecordsForSID(tracer: logging.Logger, logTag: str, sapSid: str,
                          rfcName: str, connection: Connection,
                          startDateTime: datetime, endDateTime: datetime,
                          useSWNCCache: bool):
     if (useSWNCCache and sapSid in SwncRfcSharedCache._swncRecordsCache):
         cacheEntry = SwncRfcSharedCache._swncRecordsCache[sapSid]
         if (cacheEntry['expirationDateTime'] > datetime.utcnow()):
             if (cacheEntry['swnc_records']):
                 return cacheEntry['swnc_records']
     swnc_result = None
     try:
         tracer.info(
             "%s executing RFC SWNC_GET_WORKLOAD_SNAPSHOT check for SID: %s",
             logTag, sapSid)
         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:
         tracer.error(
             "[%s] communication error for rfc %s with SID: %s (%s)",
             logTag,
             rfcName,
             sapSid,
             e,
             exc_info=True)
         raise
     except Exception as e:
         tracer.error("[%s] Error occured for rfc %s with SID: %s (%s)",
                      logTag,
                      rfcName,
                      sapSid,
                      e,
                      exc_info=True)
         raise
     finally:
         if swnc_result:
             SwncRfcSharedCache._swncRecordsCache[sapSid] = {
                 'swnc_records':
                 swnc_result,
                 'expirationDateTime':
                 datetime.utcnow() + CACHE_EXPIRATION_PERIOD
             }
    def _rfcGetDumpLog(self, connection: Connection, startDateTime: datetime,
                       endDateTime: datetime):
        rfcName = '/SDF/GET_DUMP_LOG'
        self.tracer.info(
            "[%s] invoking rfc %s for hostname=%s with date_from=%s, time_from=%s, date_to=%s, time_to=%s",
            self.logTag, rfcName, self.sapHostName, startDateTime.date(),
            startDateTime.time(), endDateTime.date(), endDateTime.time())
        try:
            short_dump_result = connection.call(rfcName,
                                                DATE_FROM=startDateTime.date(),
                                                TIME_FROM=startDateTime.time(),
                                                DATE_TO=endDateTime.date(),
                                                TIME_TO=endDateTime.time())

            return short_dump_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 ABAPApplicationError as e:
            self.tracer.error(
                "[%s] Error occured 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
Example #23
0
def user_login(username, pwd):
    try:
        user_in = {'USERID': username, 'PASSWORD': pwd}

        conn = Connection(ashost='192.168.95.20',
                          sysnr='00',
                          client='310',
                          user='******',
                          passwd='lsm2009lsm')

        result = conn.call("YREP_USER", USER_IN=user_in)
        # print(result)
        return result

    except CommunicationError:
        return "Could not connect to server"
    except LogonError:
        return "Could not log in Wrong credentials"
    except (ABAPApplicationError, ABAPRuntimeError):
        return "An error occurred"
Example #24
0
File: issue38.py Project: SAP/PyRFC
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
               )
    print 'rfc'
    result = conn.call('STFC_STRUCTURE', IMPORTSTRUCT=imp, RFCTABLE=[imp])
    print (fv, result['ECHOSTRUCT']['RFCFLOAT'])


if i == 2:
    print 'coe'

    # imp = dict(ZACCP='196602', ZCHAR='ABC', ZCLNT='000', ZCURR=0, ZDATS='', ZDEC=0, ZFLTP=fv, ZSHLP_MAT1='ELIAS')
    imp = dict(ZACCP='196602', ZCHAR='ABC', ZCLNT='620',
               ZCURR=0, ZDEC=0, ZDATS='19570321', ZFLTP=fv)

    result = conn.call('/COE/RBP_FE_DATATYPES', IV_COUNT=0,
                       IS_INPUT=imp)  # ['ES_OUTPUT']
    print (fv, result['ES_OUTPUT']['ZFLTP'])
Example #25
0
# -*- 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 #26
0
USERNAME = '******'
PASSWORD = '******'

from pyrfc import Connection
conn = Connection(
    ashost='172.16.100.146',
    sysnr='00',
    #saprouter='190.60.219.67',
    client='402',
    user=USERNAME,
    passwd=PASSWORD)
#conn.call('zmm_ws_get_material_movements', REQUTEXT=u'Hello SAP!')

#result = conn.call('ZMM_WS_GET_MATERIAL_MOVEMENTS', I_FECHA_INICIAL = '20200401',  I_FECHA_FINAL = '20200401')

options = [{'TEXT': "FCURR = 'USD'"}]
#pp = PrettyPrinter(indent=4)
ROWS_AT_A_TIME = 0
rowskips = 0

result = conn.call('RFC_READ_TABLE', \

QUERY_TABLE = 'TCURR', \
ROWSKIPS = rowskips, ROWCOUNT = ROWS_AT_A_TIME)

print(result['DATA'])
Example #27
0
class TestErrorsABAP:
    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_no_connection_params(self):
        try:
            Connection()
        except RFCError as ex:
            assert ex.args[0] == "Connection parameters missing"

    def test_RFC_RAISE_ERROR(self):
        try:
            result = self.conn.call("RFC_RAISE_ERROR", MESSAGETYPE="A")
        except ABAPRuntimeError as ex:
            assert self.conn.alive == True
            assert ex.code == 4
            assert ex.key == "Function not supported"
            assert ex.message == "Function not supported"
            assert ex.msg_class == "SR"
            assert ex.msg_type == "A"
            assert ex.msg_number == "006"

    def test_STFC_SAPGUI(self):
        # STFC_SAPGUI RFC-TEST:   RFC with SAPGUI
        try:
            self.conn.call("STFC_SAPGUI")
        except (ABAPRuntimeError) as ex:
            assert self.conn.alive == True
            error = get_error(ex)
            assert error["code"] == 3
            assert error["key"] == "DYNPRO_SEND_IN_BACKGROUND"

    def test_RFC_RAISE_ERROR_AbapRuntimeError_E0(self):
        # RFC_RAISE_ERROR ARFC: Raise Different Type of Error Message
        # Comment: cf. result_print of the error_test.py
        # cf. ExceptionTest.c (l. 92ff)
        try:
            self.conn.call("RFC_RAISE_ERROR", METHOD="0", MESSAGETYPE="E")
        except (ABAPRuntimeError) as ex:
            assert self.conn.alive == True
            error = get_error(ex)
            assert error["code"] == 4
            assert error["message"][0] == u"Function not supported"

    def test_RFC_RAISE_ERROR_AbapApplicationError_E1(self):
        # Comment: cf. result_print of the error_test.py
        # '1_E': 'ABAPApplicationError-5-RAISE_EXCEPTION-ID:SR Type:E Number:006 STRING-True',
        # cf. ExceptionTest.c (l. 75ff)
        try:
            self.conn.call("RFC_RAISE_ERROR", METHOD="1", MESSAGETYPE="E")
        except ABAPApplicationError as ex:
            assert self.conn.alive == True
            error = get_error(ex)
            assert error["code"] == 5
            assert error["key"] == "RAISE_EXCEPTION"
            assert error["msg_class"] == u"SR"
            assert error["msg_type"] == "E"
            assert error["msg_number"] == "006"

    def test_RFC_RAISE_ERROR_AbapApplicationError_E2(self):
        # '2_E': 'ABAPApplicationError-5-RAISE_EXCEPTION- Number:000-True',
        # cf. ExceptionTest.c (l. 65ff)
        try:
            self.conn.call("RFC_RAISE_ERROR", METHOD="2", MESSAGETYPE="E")
        except ABAPApplicationError as ex:
            assert self.conn.alive == True
            error = get_error(ex)
            assert error["code"] == 5
            assert error["key"] == "RAISE_EXCEPTION"
            assert error["msg_number"] == "000"

    def test_RFC_RAISE_ERROR_AbapRuntimeError_E3(self):
        # '3_E': 'ABAPRuntimeError-3-COMPUTE_INT_ZERODIVIDE-Division by 0 (type I)-True''] ==
        # cf. ExceptionTest.c (l. 164ff)
        try:
            self.conn.call("RFC_RAISE_ERROR", METHOD="3", MESSAGETYPE="E")
        except (ABAPRuntimeError) as ex:
            assert self.conn.alive == True
            error = get_error(ex)
            assert error["code"] == 3
            assert error["key"] == "COMPUTE_INT_ZERODIVIDE"

    def test_RFC_RAISE_ERROR_AbapRuntimeError_A(self):
        # cf. ExceptionTest.c (l. 112ff)
        try:
            self.conn.call("RFC_RAISE_ERROR", MESSAGETYPE="A")
        except (ABAPRuntimeError) as ex:
            assert self.conn.alive == True
            error = get_error(ex)
            assert error["code"] == 4
            assert error["msg_class"] == "SR"
            assert error["msg_type"] == "A"
            assert error["msg_number"] == "006"
            assert error["msg_v1"] == "Method = 0"

    def test_RFC_RAISE_ERROR_AbapRuntimeError_X(self):
        # cf. ExceptionTest.c (l. 137ff)
        try:
            self.conn.call("RFC_RAISE_ERROR", MESSAGETYPE="X")
        except (ABAPRuntimeError) as ex:
            assert self.conn.alive == True
            error = get_error(ex)
            assert error["code"] == 4
            assert error["key"] == "MESSAGE_TYPE_X"
            assert error["msg_class"] == "00"
            assert error["msg_type"] == "X"
            assert error["msg_number"] == "341"
            assert error["msg_v1"] == "MESSAGE_TYPE_X"

    def test_RFC_RAISE_ERROR_AbapRuntimeError_E36(self):
        # '36_E': 'ABAPRuntimeError-4-Division by 0 (type I)-Division by 0 (type I)-True''] ==
        try:
            self.conn.call("RFC_RAISE_ERROR", METHOD="36", MESSAGETYPE="E")
        except (ABAPRuntimeError) as ex:
            assert self.conn.alive == True
            error = get_error(ex)
            assert error["code"] == 4
            assert u"Division by 0" in error["message"][0]

    def test_RFC_RAISE_ERROR_AbapRuntimeError_E51(self):
        # '51_E': 'ABAPRuntimeError-3-BLOCKED_COMMIT-A database commit was blocked by the application.-True''] ==
        try:
            self.conn.call("RFC_RAISE_ERROR", METHOD="51", MESSAGETYPE="E")
        except (ABAPRuntimeError) as ex:
            assert self.conn.alive == True
            error = get_error(ex)
            assert error["code"] == 3
            assert error["key"] == "BLOCKED_COMMIT"

    """ todo Windows test crashes!
Example #28
0
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)
assert len(result['ET_RETURN']) == 1
Example #29
0
File: test.py Project: SAP/PyRFC
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 #30
0
class TestErrors:
    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_no_connection_params(self):
        try:
            Connection()
        except RFCError as ex:
            assert ex.args[0] == "Connection parameters missing"

    # todo: test correct status after error -> or to the error tests?
    def test_incomplete_params(self):
        incomplete_params = params.copy()
        for p in ["ashost", "gwhost", "mshost"]:
            if p in incomplete_params:
                del incomplete_params[p]
        try:
            Connection(**incomplete_params)
        except RFCError as ex:
            error = get_error(ex)
        assert error["code"] == 20
        assert error["key"] == "RFC_INVALID_PARAMETER"
        assert error["message"][0] in [
            "Parameter ASHOST, GWHOST, MSHOST or SERVER_PORT is missing.",
            "Parameter ASHOST, GWHOST, MSHOST or PORT is missing.",
            "Parameter ASHOST, GWHOST or MSHOST is missing.",
        ]

    def test_denied_users(self):
        denied_params = params.copy()
        denied_params["user"] = "******"
        try:
            Connection(**denied_params)
        except LogonError as ex:
            error = get_error(ex)

        assert error["code"] == 2
        assert error["key"] == "RFC_LOGON_FAILURE"
        assert error["message"][
            0] == "Name or password is incorrect (repeat logon)"

    def test_call_without_RFM_name(self):
        try:
            self.conn.call()
        except Exception as ex:
            assert isinstance(ex, TypeError) is True
            assert ex.args[
                0] == "call() takes at least 1 positional argument (0 given)"

    def test_call_non_existing_RFM(self):
        try:
            self.conn.call("undefined")
        except ABAPApplicationError as ex:
            error = get_error(ex)
        assert error["code"] == 5
        assert error["key"] == "FU_NOT_FOUND"
        assert error["message"][0] == "ID:FL Type:E Number:046 undefined"

    def test_call_non_string_RFM_name(self):
        try:
            self.conn.call(1)
        except RFCError as ex:
            assert ex.args == (
                "Remote function module name must be unicode string, received:",
                1,
                int,
            )

    def test_call_non_existing_RFM_parameter(self):
        try:
            self.conn.call("STFC_CONNECTION", undefined=0)
        except ExternalRuntimeError as ex:
            error = get_error(ex)
        assert error["code"] == 20
        assert error["key"] == "RFC_INVALID_PARAMETER"
        assert error["message"][0] == "field 'undefined' not found"

    def test_non_existing_field_structure(self):
        IMPORTSTRUCT = {"XRFCCHAR1": "A", "RFCCHAR2": "BC", "RFCCHAR4": "DEFG"}
        try:
            result = self.conn.call("STFC_STRUCTURE",
                                    IMPORTSTRUCT=IMPORTSTRUCT)
        except ExternalRuntimeError as ex:
            assert ex.code == 20
            assert ex.key == "RFC_INVALID_PARAMETER"
            assert ex.message == "field 'XRFCCHAR1' not found"

    def test_non_existing_field_table(self):
        IMPORTSTRUCT = {"XRFCCHAR1": "A", "RFCCHAR2": "BC", "RFCCHAR4": "DEFG"}
        try:
            result = self.conn.call("STFC_STRUCTURE", RFCTABLE=[IMPORTSTRUCT])
        except ExternalRuntimeError as ex:
            assert ex.code == 20
            assert ex.key == "RFC_INVALID_PARAMETER"
            assert ex.message == "field 'XRFCCHAR1' not found"
Example #31
0
from pyrfc import Connection, get_nwrfclib_version

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

conn = Connection(**params)

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

input = '0123456789ABCDEF'
L = len(input)
print 'input string:', type(input), len(input), input
r = conn.call('ZPYRFC_TEST_RAW255', IRAW255=input, IXSTR=input)
oraw = r['ORAW255']
oxstr = r['OXSTR']
print 'raw:', type(oraw), len(oraw), oraw
print 'xstr:', type(oxstr), len(oxstr), oxstr

for i in range(0, L):
    print i, type(input[i]), input[i], type(
        oraw[i]), oraw[i], input[i] == oraw[i], type(
            oxstr[i]), oxstr[i], input[i] == oxstr[i]

input = bytearray([
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
    'F'
])
L = len(input)
Example #32
0
class PreSystemRefresh:

    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'])

    def prRed(self, text):
        return "\033[91m {}\033[00m".format(text)

    def prGreen(self, text):
        return "\033[92m {}\033[00m".format(text)

    def prYellow(self, text):
        print("\033[93m {}\033[00m".format(text))

    def users_list(self):
        try:
            tables = self.conn.call("RFC_READ_TABLE", QUERY_TABLE='USR02', FIELDS=[{'FIELDNAME': 'BNAME'}])
        except Exception as e:
            return self.prRed("\nError while fetching user's list from USR02 table: {}".format(e))

        users = []

        for data in tables['DATA']:
            for names in data.values():
                users.append(names)

        return users

    def locked_users(self):
        params = dict(
                    PARAMETER='ISLOCKED',
                    FIELD='LOCAL_LOCK',
                    SIGN='I',
                    OPTION='EQ',
                    LOW='L'
                    )
        try:
            user_list = self.conn.call("BAPI_USER_GETLIST", SELECTION_RANGE=[params])
        except Exception as e:
            return self.prRed("\nFailed to get already locked user list: {}".format(e))

        locked_user_list = []

        for user in user_list['USERLIST']:
                locked_user_list.append(user['USERNAME'])

        return locked_user_list

    def user_lock(self, user_list, except_users_list):
        users_locked = []

        for user in user_list:
            if user not in except_users_list:
                try:
                    self.conn.call('BAPI_USER_LOCK', USERNAME=user)
                    self.prGreen("\nUser: {} is locked!".format(user))
                    users_locked.append(user)
                except Exception as e:
                    self.prRed("\nNot able to Lock user: "******"Please check! {}".format(e))
                    pass
            else:
                self.prYellow("\nUser: "******" is excepted from setting to Administer Lock.")

        return users_locked

    def suspend_jobs(self):
        try:
            self.conn.call("INST_EXECUTE_REPORT", PROGRAM='BTCTRNS1')
            return self.prGreen("\nBackground Jobs are suspended!")
        except Exception as e:
            return self.prRed("\nFailed to Suspend Background Jobs: {}".format(e))

    def export_sys_tables(self):
        try:
            self.conn.call("SXPG_COMMAND_EXECUTE", COMMANDNAME='ZTABEXP')
            return self.prGreen("\nSuccessfully Exported Quality System Tables")
        except Exception as e:
            return self.prRed("\nError while exporting system tables: {}".format(e))

    def check_variant(self, report, variant_name):
        try:
            output = self.conn.call("RS_VARIANT_CONTENTS_RFC", REPORT=report, VARIANT=variant_name)
        except Exception as e:
            return self.prRed("\nFailed to check variant {}: {}".format(variant_name, e))

        var_content = []

        for key, value in output.items():
            if key == 'VALUTAB':
                var_content = value

        for cont in var_content:
            if cont['SELNAME'] == 'FILE' and cont['LOW'] == '/tmp/printers':
                return True

        for cont in var_content:
            if cont['SELNAME'] == 'COMFILE' and cont['LOW'] == 'PC3C900006':
                return True

        for cont in var_content:
            if cont['SELNAME'] == 'FORCE' and cont['LOW'] == 'X':
                return True

        for cont in var_content:
            if cont['SELNAME'] == 'DISPLAY' and cont['LOW'] == 'X':
                return True

        for cont in var_content:
            if cont['SELNAME'] == 'SET_EXEC' and cont['LOW'] == 'X':
                return True

        return False

    def create_variant(self, report, variant_name, desc, content, text, screen):
        try:
            self.conn.call("RS_CREATE_VARIANT_RFC", CURR_REPORT=report, CURR_VARIANT=variant_name, VARI_DESC=desc, VARI_CONTENTS=content, VARI_TEXT=text, VSCREENS=screen)
        except Exception as e:
            return self.prRed("\nVariant {} Creation is Unsuccessful!!".format(variant_name, e))

        if self.check_variant(report, variant_name) is True:
            return self.prGreen("\nVariant {} Successfully Created".format(variant_name))
        else:
            return self.prRed("\nCreation of variant {} is failed!!".format(variant_name))

    def delete_variant(self, report, variant_name):
        try:
            self.conn.call("RS_VARIANT_DELETE_RFC", REPORT=report, VARIANT=variant_name)
        except Exception as e:
            return self.prRed("\nDeletion of variant {} is failed!!: {}".format(variant_name, e))

        if self.check_variant(report, variant_name) is False:
            return self.prGreen("\nVariant {} Successfully Deleted".format(variant_name))

    def export_printer_devices(self):
        report = "RSPOXDEV"
        variant_name = "ZPRINT_EXP"

        desc = dict(
            MANDT=self.creds['client'],
            REPORT=report,
            VARIANT=variant_name
        )

        content = [{'SELNAME': 'DO_SRV', 'KIND': 'P', 'LOW': 'X'},
                   {'SELNAME': '_EXP', 'KIND': 'P', 'LOW': 'X'},
                   {'SELNAME': 'DO_EXP', 'KIND': 'P', 'LOW': 'X'},
                   {'SELNAME': 'DO_LOG', 'KIND': 'P', 'LOW': 'X'},
                   {'SELNAME': 'WITH_CNF', 'KIND': 'P', 'LOW': 'X'},
                   {'SELNAME': 'DEVICE', 'KIND': 'S', 'SIGN': 'I', 'OPTION': 'CP', 'LOW': '*'},
                   {'SELNAME': 'FILE', 'KIND': 'P', 'LOW': '/tmp/printers'}]

        text = [{'MANDT': self.creds['client'], 'LANGU': 'EN', 'REPORT': report, 'VARIANT':variant_name, 'VTEXT': 'Printers Export'}]

        screen = [{'DYNNR': '1000', 'KIND': 'P'}]

        if self.check_variant(report, variant_name) is False:
            try:
                self.create_variant(report, variant_name, desc, content, text, screen)
            except Exception as e:
                return e

        if self.check_variant(report, variant_name) is True:
            try:
                self.conn.call("SUBST_START_REPORT_IN_BATCH", IV_JOBNAME=report, IV_REPNAME=report, IV_VARNAME=variant_name)
                return self.prGreen("\nExported printer devices Successfully")
            except Exception as e:
                return self.prRed("\nFailed to export printer devices! {}".format(e))
        else:
            return self.prRed("\nCreation of variant {} failed!".format(variant_name))

    def user_master_export(self):
        report = "ZRSCLXCOP"
        variant_name = "ZUSR_EXP"

        try:
            output = self.conn.call("RFC_READ_TABLE", QUERY_TABLE='E070L') #IF Condition check needs to be implemented
        except Exception as e:
            return self.prRed("\nFailed to get current transport sequence number from E070L Table: {}".format(e))

        pc3_val = None
        for data in output['DATA']:
            for val in data.values():
                pc3_val = ((val.split()[1][:3] + 'C') + str(int(val.split()[1][4:]) + 1))

        try:
            result = self.conn.call("RFC_READ_TABLE", QUERY_TABLE='TMSPCONF', FIELDS=[{'FIELDNAME': 'NAME'}, {'FIELDNAME': 'SYSNAME'}, {'FIELDNAME': 'VALUE'}])
        except Exception as e:
            return self.prRed("\nFailed while fetching TMC CTC Value: {}".format(e))

        ctc = None
        for field in result['DATA']:
            if field['WA'].split()[0] == 'CTC' and field['WA'].split()[1] == self.creds['sid']:
                ctc = field['WA'].split()[2]

        if ctc is '1':
            ctc_val = self.creds['sid'] + '.' + self.creds['client']
        else:
            ctc_val = self.creds['sid']

        desc = dict(
            MANDT=self.creds['client'],
            REPORT=report,
            VARIANT=variant_name
        )

        content = [{'SELNAME': 'COPYCLI', 'KIND': 'P', 'LOW': self.creds['client']},
                   {'SELNAME': 'SUSR', 'KIND': 'P', 'LOW': 'X'},
                   {'SELNAME': 'MODUS', 'KIND': 'P', 'LOW': 'E'},
                   {'SELNAME': 'ALTINP', 'KIND': 'P', 'LOW': 'A'},
                   {'SELNAME': 'COMFILE', 'KIND': 'P', 'LOW': pc3_val},
                   {'SELNAME': 'PROF', 'KIND': 'P', 'LOW': 'X'},
                   {'SELNAME': 'PROFIL', 'KIND': 'P', 'LOW': 'SAP_USER'},
                   {'SELNAME': 'TARGET', 'KIND': 'P', 'LOW': ctc_val}]

        text = [{'MANDT': self.creds['client'], 'LANGU': 'EN', 'REPORT': report, 'VARIANT': variant_name,
                 'VTEXT': 'User Master Export'}]

        screen = [{'DYNNR': '1000', 'KIND': 'P'}]

        if pc3_val is not None and self.check_variant(report, variant_name) is False:
            try:
                self.create_variant(report, variant_name, desc, content, text, screen)
            except Exception as e:
                return self.prRed("\nException occured while creating variant {}".format(e))
        else:
            return self.prRed("\nUser-Master Export : pc3_val and variant {} check failed!!".format(variant_name))

        if self.check_variant(report, variant_name) is True:
            try:
                self.conn.call("SUBST_START_REPORT_IN_BATCH", IV_JOBNAME=report, IV_REPNAME=report, IV_VARNAME=variant_name)
                return self.prGreen("\nUser Master Export is Completed!")
            except Exception as e:
                return self.prRed("\nUser Master Export is Failed!! {}".format(e))
        else:
            return self.prRed("\nVariant {} creation has unknown issues, please check!".format(variant_name))
Example #33
0
    },
}

if __name__ == "__main__":
    try:
        IS_INPUT = {
            # Float
            "ZFLTP_MIN": RFC_MATH["FLOAT_POS"]["MIN"],
            "ZFLTP_MAX": RFC_MATH["FLOAT_POS"]["MAX"],
            # Decimal
            "ZDECF16_MIN": RFC_MATH["DECF16_POS"]["MIN"],
            "ZDECF16_MAX": RFC_MATH["DECF16_POS"]["MAX"],
            "ZDECF34_MIN": RFC_MATH["DECF34_POS"]["MIN"],
            "ZDECF34_MAX": RFC_MATH["DECF34_POS"]["MAX"],
        }
        result = conn.call("/COE/RBP_FE_DATATYPES",
                           IS_INPUT=IS_INPUT)["ES_OUTPUT"]
        for k in IS_INPUT:
            if "FLTP" in k:
                print(k, float(IS_INPUT[k]) == result[k])
            else:
                print(k, Decimal(IS_INPUT[k]) == result[k])
    except Exception as e:
        print(e)

    try:
        IS_INPUT = {
            # Float
            "ZFLTP_MIN": RFC_MATH["FLOAT_NEG"]["MIN"],
            "ZFLTP_MAX": RFC_MATH["FLOAT_NEG"]["MAX"],
            # Decimal
            "ZDECF16_MIN": RFC_MATH["DECF16_NEG"]["MIN"],
Example #34
0
def run(COUNT):
    conn = Connection(**MME)
    result = conn.call('STFC_PERFORMANCE', **{
        'CHECKTAB': 'X', 'LGET0332': str(COUNT), 'LGET1000': str(COUNT)})
    return result
Example #35
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