Azure function works fine when tested locally, but not loaded when deployed.

Hafsa Javed 0 Reputation points Student Ambassador
2024-05-25T18:15:57.4966667+00:00

logslogs

init.py file


import os
import logging
import azure.functions as func

from azure.core.exceptions import ClientAuthenticationError, ResourceNotFoundError
from azure.data.tables import TableServiceClient, TableClient
from azure.core.credentials import AzureNamedKeyCredential


app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

# Load connection string from environment variable (assuming a .env file)
conn_str = os.environ['the_connection_string']
table_name = os.environ['table_name']


# Create a TableClient object using the connection string
table_service_client = TableServiceClient.from_connection_string(conn_str=conn_str)
table_client = table_service_client.get_table_client(table_name=table_name)

visitor_entry = {
    'PartitionKey' : "VisitorsCount",
    'RowKey' : "resume_visitors",
    'value' : 0
}

@app.function_name(name="visitorCount")
@app.route(route="count", auth_level=func.AuthLevel.ANONYMOUS)
def main(req : func.HttpRequest) -> func.HttpResponse:
    if not conn_str:
        return func.HttpResponse(
        body='Error: Missing COSMOSDB_CONNECTION_STRING environment variable.',
        status_code=500
        )

    logging.info("HTTP trigger function processed a request. ")
    try:
        count = table_client.get_entity(partition_key="VisitorsCount",row_key="resume_visitors")
        if count:
            """Updates the 'visitors_count' value in the 'visitors' entry."""
            count['value'] += 1
            try:
                table_client.update_entity(entity=count)
                logging.info(f"Visitor count updated to: {count['value']}")
            except LookupError as e:
                logging.error(f"Entity not found: {e}")
                return func.HttpResponse (
                    status_code= 500,
                    body=f"{e}"
                )
            except ClientAuthenticationError as e:
                logging.error(f"Connection error: {e}")
                return func.HttpResponse (
                    status_code= 500,
                    body=f"{e}"
                )
            except Exception as e:
                logging.error(f"Unexpected error: {e}")
                return func.HttpResponse (
                    status_code= 500,
                    body=f"{e}"
                )
    
    except ResourceNotFoundError:
        """Creates an entry with key 'visitors' and value 0 in the Cosmos DB table."""
        logging.info("Resource not found. Creating resource")
        try:
            table_client.create_entity(entity=visitor_entry)
            logging.info("Visitor entry created successfully!")
            return func.HttpResponse (
            status_code= 200,
            body="Visitor count created."
            )
        except Exception as e:
            logging.info(f"Error creating entry: {e}")
            return func.HttpResponse (
                status_code= 500,
                body=f"Error creating visitor count entry {e}."
            )


    return func.HttpResponse (
        status_code= 200,
        body=f"Visitor count incremented to {count['value']}."
    )
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,515 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Dan Rios 1,655 Reputation points MVP
    2024-05-25T19:30:50.1+00:00

    Hi,

    This is a fairly well known bug with the portal where it gives you no information or logs, but the function will be failing to load.

    You can review this GitHub issue on this problem here where it has many fixes depending on your code and libraries: https://github.com/Azure/azure-functions-python-worker/issues/1262

    The comments on this issue will have lots of different fixes you can try. Essentially it will be failing to load silently due to the requirements text file or the libraries you’re importing.

    The reason it works locally is likely due to the Azure Function running a different OS version to your desktop.

    A common fix is not to have anything before the import azure.functions as func .

    You can also try and go to the diagnose and solve area in the Function, within the portal, and locate the category “functions not triggering” to see if it can help give you an error log on what is failing.

    If this was useful, please mark as accepted so others can see this and the GitHub issue thread.

    0 comments No comments