Setting a Service State

Setting the state of a service is as simple as calling either enableservice or disableservice with a service name as a parameter to the method call. Citrix Netscaler load balancer service and virtual server names are not case-sensitive, so when calling either method you do not need to care about setting a correct case for the name parameter.

We are going to define another function in our NSConfigApi class that will implement switching between the states and wrap two SOAP functions into one convenient, easy-to-use class method. We will call this method set_service_state, and it will accept two required arguments: a new state and a

Python array that contains the names of all the services whose state we want to change. Listing 2-26 shows the code.

Listing 2-26. The wrapper for the SOAP enableservice and disableservice functions def set_service_state(self, state, service_list, verbose=False): [...]

for service in service_list: if verbose:

print 'Changing state of %s to %sd... ' % (service, state) req = getattr(self.module, '%sservice' % state)() req._name = service res = getattr(self.soap, '%sservice' % state)(req)._return

As you can see, it is a very simple function; however, it contains one thing that's worth a bit more attention: we do not explicitly specify the name of the method we are calling—it is automatically constructed during runtime from the argument value that we receive in the state variable.

To achieve this, we use the Python getattr function, which allows us to get a reference to an object's property at runtime without knowing the property name in advance. When we call getattr, we provide two arguments: a reference to an object and the name of the property we are addressing. Therefore, our explicit call to a method looks like this:

result = some_object.some_function()

would be equivalent to:

result = getattr(some_object, "some_function")()

It is important to note the () after the getattr call. The getattr return value is a reference to an object, and as such does not execute a function. If we are accessing an object variable, it will return the value of the variable, but if we are accessing a function we would only get a reference to it:

Was this article helpful?

0 0

Post a comment