0

I am using Python Function App that is triggered by service bus queue to store the data in SQL Server. I need to handle connection with SQL Server.

I found this link. Specifically, people often initiate a connection outside of main function, then use it in main function. Following the document, the connection could be re-used. But the issue is: Microsoft tutorial is made with solely C# and JavaScript.

I have tried with the following sample source code, it runs well, but I do not know if the Function App would create a new connection or not.

import azure.functions as func

connection = getConnection()

def main(msg: func.ServiceBusMessage):
    # get content of message
    mess = msg.get_body().decode("utf-8")
    logging.info(mess)
    message = eval(str(mess))  # Sensitive

    # handle scenarios
    data = handle_message_from_device(message)
    insert(connection, data)

I want to ask:

  • With the above source code, could Function App re-use the connection or create a new one? If it re-uses the connection, could Function App remain this connection as long as it runs?
  • How could Python function app reuse this connection? Currently, I think when a new message is pushed to Function App, the main file (init file, by default) will be called. So in this case, a new message should be called instead?

Thanks in advance :-)

Truong Nguyen
  • 75
  • 2
  • 11

1 Answers1

1

Yes, this should work just fine. connection = GetConnection() gets called only once on Function (cold) start. From there on it stays "warm" for about 5 minutes. If another request comes in - to the same instance of the function - it will be reused. After the timeout your function gets recycled. On next invocation it gets started again and another connection object will be created.

You can simply test this by adding some logging to your GetConnection() method. You'll see that this will be only executed on first start. For subsequent requests in the next few seconds/minutes, it will not get called again. Unless, of course, your function gets scaled out to additional instances.

silent
  • 14,494
  • 4
  • 46
  • 86
  • Thank you, silent. How about the case that network connection is disconnected for a while, could the connection try itself to re-connect to my Server? – Truong Nguyen Nov 01 '19 at 07:51