system.net.httpClient asynchronous use - callback function with user payload?

@PGriffith, I really appreciate the “new” system.net.httpClient

I use it in the asynchronous flavor.

promise = httpClient.getAsync("http://127.0.0.1:8081/test")
promise.then(callbackPollData)|

...

def callbackPollData(result, error):

I juste have a “feature request” or I’ve missed something…
I would like to be able to use the same callback function for multiple request.

IMO it would be very usefull if we were able to pass a user dictionnary payload to the callback when we register it.

myPayload = {...}
promise = httpClient.getAsync("http://127.0.0.1:8081/test")
promise.then(callbackPollData,myPayload)

...

def callbackPollData(result, error, payload):

callback function is a callable PyObject ? perhaps user payload can be stored in the PyObject, I will try…

Your callback will have access to myPayload due to its presence in the local variable namespace when the def executes. This is called closure. Worth learning to use. Another option is applying python’s partial function to yield a function that carries your payload.

partial function doesn’t work for me as args for promise.then(partial(…))

I don’t want to use closure because it need to nest functions

I finally end with a callback like:

promise.then(CallBackWithPayload({"data":123}))

...

class CallBackWithPayload():
	def __init__(self, payload):
		self.payload = payload
	
	def __call__(self,result,error):
		strMsg = "payload=%s - result=%s - error=%s" % (self.payload,result,error)
...

but is there any risk of memory leak with this class if the function promise.then(…) is called every x seconds ? I don’t know when CallBackWithPayload instances will be garbage collected…?

1 Like

With adding:

class CallBackWithPayload():

  def __del__(self):
    log...

it seems to confirm CallBackWithPayload are destroyed after waiting less than 2 minutes.

I hope you’re putting the CallBackWithPayload class in its own project script…

Yes sure !

Is it throwing an error? In a few tag related scripting functions we're doing too strict of a check for callable functions, so httpClient might be doing something similar. partial would be the recommended way forward...

No, there is no error when I call promise.then(partial(myFunction,payload)) but myFunction seem to be never called