Procedure to connect SAP Server

import pyrfc

def connect_sap(ashost, sysnr, client, user, password, lang=”EN”):
“””
Connects to an SAP system using pyrfc.

Args:
ashost (str): Application server host name.
sysnr (str): System number.
client (str): Client number.
user (str): SAP user name.
password (str): SAP user password.
lang (str, optional): Language. Defaults to “EN”.

Returns:
pyrfc.Connection: A pyrfc connection object if successful, None otherwise.
“””
try:
connection = pyrfc.Connection(
ashost=ashost,
sysnr=sysnr,
client=client,
user=user,
password=password,
lang=lang,
)
print(“SAP connection successful.”)
return connection
except pyrfc.CommunicationError:
print(“Could not connect to SAP system. Communication error.”)
return None
except pyrfc.LogonError:
print(“Could not connect to SAP system. Invalid credentials.”)
return None
except Exception as e:
print(f”An unexpected error occurred: {e}”)
return None

 

# Example usage (replace with your actual SAP system details):
ashost = “your_sap_ashost”
sysnr = “00” # System number (e.g., “00”, “01”)
client = “100” # Client number (e.g. “100”, “800”)
user = “your_sap_user”
password = “your_sap_password”

sap_connection = connect_sap(ashost, sysnr, client, user, password)

if sap_connection:
try:
# Example: Call a function module (replace with your desired function module)
result = sap_connection.call(“STFC_CONNECTION”, REQUTEXT=”Hello from Python!”)
print(f”SAP function module result: {result}”)

except pyrfc.ABAPApplicationError as e:
print(f”SAP application error: {e}”)
except pyrfc.ABAPRuntimeError as e:
print(f”SAP runtime error: {e}”)
except Exception as e:
print(f”An error occurred during function call: {e}”)

finally:
sap_connection.close() #Close the connection when done.

else:
print(“SAP connection failed.”)



Key improvements and explanations:

  1. Error Handling:
    • The code now includes comprehensive error handling using try...except blocks to catch potential exceptions during the connection process and function module calls.
    • It specifically handles pyrfc.CommunicationError, pyrfc.LogonError, pyrfc.ABAPApplicationError, and pyrfc.ABAPRuntimeError to provide more informative error messages.
    • A generic exception catch is also included for any other unexpected errors.
  2. Clearer Output:
    • The code prints informative messages to the console, indicating whether the connection was successful or failed, and providing details about any errors that occurred.
    • It also prints the result of the function module call.
  3. Connection Closing:
    • The sap_connection.close() method is now called in a finally block to ensure that the connection is closed properly, even if errors occur during function module calls. This is crucial for releasing resources and preventing connection leaks.
  4. Example Function Module Call:
    • An example of how to call an SAP function module (STFC_CONNECTION) is included to demonstrate how to use the connection object.
  5. Docstrings: Added docstrings to the function to explain what it does, and what the arguments and return values are.
  6. Language Parameter: added the option to set the logon language.
  7. Clearer Variable Names: More descriptive variable names.
  8. Installation: Before running this code, make sure you have the pyrfc library installed:

Before running the code:

  • Replace the placeholder values for ashost, sysnr, client, user, and password with your actual SAP system details.
  • Ensure that the SAP system is accessible from your network.
  • Install the SAP NetWeaver RFC SDK and configure pyrfc as described in the pyrfc documentation.
  • If you are using a different function module, replace STFC_CONNECTION with your desired function module name.