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 :-)

2
  • please post relevant code of what you have done/tried so far Commented Oct 30, 2019 at 10:35
  • Thank you, I have remade my question with sample source code. Commented Oct 31, 2019 at 5:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.