Skip to content

Instantly share code, notes, and snippets.

@wrigby
Last active July 18, 2016 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrigby/22abba76f92c4de1fe52 to your computer and use it in GitHub Desktop.
Save wrigby/22abba76f92c4de1fe52 to your computer and use it in GitHub Desktop.
Python suds plugin for Apache Axis sessions

Why?

  • Because the MultiRef support in Suds doesn't handle references in the header of the reply, but it does remove all the multirefs from the body, so it eats the session ID before you can do anything about it.
  • Because with this plugin, you don't even have to think about handling sessions
  • Because I was trying to figure out how to use Diamond IP's IPControl SOAP API, and had to write this to make it work

How to use it?

session_plugin = AxisSessionPlugin()
c = Client(..., plugins=[session_plugin])

# Proceed as usual

That's all folks!

from suds.plugin import MessagePlugin
from suds.sax.element import Element
class AxisSessionPlugin(MessagePlugin):
def __init__(self):
self.session_id = None
def marshalled(self, context):
""" Insert the sessionID element in the header """
if self.session_id is not None:
sid_el = Element('sessionID', ns=('ssn', 'http://xml.apache.org/axis/session')).setText(self.session_id)
context.envelope.getChild("Header").append(sid_el)
def parsed(self, context):
""" Finds the session ID in the parsed reply """
session_id = None
envelope = context.reply.getChild("Envelope")
header = envelope.getChild("Header")
session_element = header.getChild("sessionID")
if session_element is not None:
# Found a sessionID element in the header
# Check to see if we're using multiRefs
href = session_element.get("href")
if href is not None:
# Using multirefs - find the multiRef in the body and use its value
target_id = href[1:] # Removes leading '#'
for multiref in envelope.getChild("Body").getChildren("multiRef"):
if multiref.get("id") == target_id:
session_id = multiref.getText()
break
else:
# Not using multiRefs - just use the value of the sessionID element
session_id = session_element.getText()
self.session_id = session_id
@rgraham717
Copy link

Thank you so much for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment