Search code examples
python-3.xazure-functionsazure-storage-queues

Azure Storage queue integration for Azure Functions in Python behaves abnormally


i have an Azure Function in Python (v1) running in environment with version 3.6.4. I am trying to put simple strings to an output storage queue as separate messages through the standard syntax:

for SomeStrVar in ListOfStrVars:
    outputQueue = open(os.environ['outputQueueItem'],'w')
    outputQueue.write(SomeStrVar)
    outputQueue.close()

where the outputQueueItem is the configured output queue for the function. What happens is that instead of ending up with X number of messages in the target queue I get only the last one that is in the list. Even though the file handle is opened and closed for each element in the list it seems that the same message is overwritten over and over again in the queue.

To me this is not normal behavior, but i must say that I am new to Python and might be that i am overseeing something here.

Any suggestions about how should this be written to work as expected are highly appreciated. Until then I am switching to directly using the QueueService class.

Thanks in advance, Svet


Solution

  • The output binding is processed at the end of the function execution, which is why you're only seeing that last entry; it's the only one the functions host knows about.

    Instead, in your loop, try generating a JSON array and then setting that to the output value at the end. So you end up writing something like ['SomeValue1','SomeValue2','SomeValue3'] out as part of the binding. Then the host will see the array and create a message with each of the values.

    I'm not a python expert, but something like this:

    arr = { "a", "b", "c", "d" }
    output = "["
    for i in arr:
      output += "'%s'," % i  
    output = output[:-1]
    output += "]"
    
    # write to the output binding
    f = open(os.environ['output'], 'w')
    f.write(output)