I wanted to log every access to my web services (using soaplib): Get the client IP, what method is it calling, what parameters, and what class. Rather than write the code to log the access in every method I’ve written a decorator (logWebServiceCall) so you only need to add it on the top of your web method, like this:
class MyService(SimpleWSGISoapApp )
@logWebServiceCall
@soapmethod(String, String, _returns=Array(String))
def myMethod(self, param1, param2):
...code here...
Decorator code:
from soaplib.wsgi_soap import request
def logWebServiceCall(func):
def wrapped(*args, **kwargs):
if hasattr(request, "environ"):
if not kwargs.has_key('_soap_descriptor'):
message = request.environ['SCRIPT_NAME']
message += " - " + request.environ['HTTP_SOAPACTION']
message += " - " + request.environ['REMOTE_ADDR']
message += " - " + str(list(args)[1:])
print message
result = func(*args, **kwargs)
return result
wrapped.__doc__ = func.__doc__
wrapped.func_name = func.func_name
wrapped._is_soap_method = True
return wrapped
Update:
Just finished a decorator for validation. Same usage than the previous one.
def validateUserFirst(func):
def wrapped(*args, **kwargs):
if hasattr(request, "environ"):
if not kwargs.has_key('_soap_descriptor'):
argumentsList = list(args)[1:]
if len(argumentsList) < 2:
raise Exception('This method requires username and password at least')
username = argumentsList[0]
password = argumentsList[1]
if not validate(username, password): # define the validation method as you want
raise Exception('Invalid username or password')
result = func(*args, **kwargs)
return result
wrapped.__doc__ = func.__doc__
wrapped.func_name = func.func_name
wrapped._is_soap_method = True
return wrapped