azure-functions-host
azure-functions-host copied to clipboard
Azure Function run correctly in local machine but when deployed to Azure function App it is not showing up in overview section
I wanted to deploy CRON Timer Trigger using Azure Function in Python. I tried to deploy it using VS Code and through command as well
func azure functionapp publish <functionapp_name>
But in both cases trigger is not showing azure portal.
Here are the steps I followed:
Step 1: Installed all the following prerequisites:
Installed Azure Core Tools v4 Have Azurite V3 Extension Installed. Working in Python 3.11.8. Latest version of VS Code in Windows Azure Function Extension installed
Step 2: Created Azure Python Function with Consumption Plan
Step 3: Created a Function App with Python v2 Model
Used VS Code Azure Extension to create Function locally
Step 4: After doing required changes in default function code, I tried to deploy that using VS Code Azure Extension by selecting the required function app: Deployed using following Azure Extension
Step 5: Checked for deployment status. In VS Code it is shown as successful. In Portal all files which are not ignored, are uploaded to the Azure Function Resource but it's not showing as a function.
Function is not showing up in overview
However I can see files successfully deployed in App File Section
Step 6: Also I have checked deployed Azure Function in VS Code but I can't see function.json under Function.
My function_app.py looks like the following:
import logging
import azure.functions as func
import traceback
import uuid
from tqdm import tqdm
import requests
from dotenv import load_dotenv
import os
from datetime import datetime,timedelta
import time
from dateutil.relativedelta import relativedelta
import inflect
import logging
######################################## VARIABLES ########################################
# Load environment variables from .env file
load_dotenv()
# Define authentication parameters for power platform datavese
tenant_id = os.environ.get('TenantId')
client_id = os.environ.get('ClientId')
client_secret = os.environ.get('ClientSecret')
resource = os.environ.get('Resource')
# Constants
MAX_RETRIES = 5 # Maximum number of retries
BASE_DELAY = 1.0 # Base delay in seconds for the exponential backoff
MAX_DELAY = 60.0 # Maximum delay in seconds for the exponential backoff
BATCH_SIZE = 1000 # Batch size for logging purposes
RATE_LIMIT = 6000 # Maximum number of requests per time window
TIME_WINDOW = 300 # Time window in seconds for rate limiting
CONCURRENT_REQUESTS = 100 # Maximum number of concurrent requests
# Audit Management Table
AuditManagement = os.environ.get('AuditManagement')
# Endpoint
odata_endpoint = f"{resource}/api/data/v9.2/"
# Date variables
date_today = datetime.utcnow()
# Prefixes
prefixes = os.environ.get("Prefixes").split(",")
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Handle Error
def handle_error(exception):
print(f"An error occurred: {exception}")
######################################## Fetch Token ########################################
def fetchToken():
token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/token'
#print("app_registration_token_url :",token_url)
token_data = {
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'resource': resource
}
token_response = requests.post(token_url, data=token_data)
#print("token_response",token_response)
access_token = token_response.json()['access_token']
print("access_token : ",access_token)
return access_token
######################################## Fetch Audit Management Table ########################################
headers = {
"Authorization": f"Bearer {fetchToken()}",
"Accept": "application/json",
"Content-Type": "application/json"
}
post_headers = {
'Authorization': f'Bearer {fetchToken()}',
'OData-MaxVersion': '4.0',
'OData-Version': '4.0',
'Accept': 'application/json',
'If-None-Match': 'null'
}
def fetch_audit_management():
logging.info(f'------------Table Records--------------------')
try:
full_url = f"{odata_endpoint + AuditManagement}"
print("full_url : ",full_url)
response = requests.get(full_url, headers=headers)
if response.status_code == 200:
data = response.json()
records = data.get("value", [])
if not records:
print("No records fetched for While Active")
logging.info("No records fetched for While Active")
return("No records fetched")
else:
logging.info("Records fetched for While Active")
return records
else:
logging.info(f"Failed to retrieve records. Status code: {response.status_code}")
print(f"Failed to retrieve records. Status code: {response.status_code}")
except Exception as e:
handle_error(e)
return None # Return None when an error occurs
app = func.FunctionApp()
@app.schedule(schedule="0 0 4 * * *", arg_name="myTimer", run_on_startup=False,
use_monitor=False)
def amr_timer_trigger(myTimer: func.TimerRequest) -> None:
start_time = time.time()
# Log the start of Azure Function execution in hh:mm:ss format
logging.info(f'timer trigger function executed at: {time.strftime("%H:%M:%S")}')
if myTimer.past_due:
logging.info('The timer is past due!')
else:
try:
###### Comment : Fetching while active entity from Table
logging.info(f'\n\nFetching while active entity from Table')
records = fetch_audit_management()
# Iterating over entites fetched
logging.info(f'Iterating over entites fetched from Table')
for record in records:
logging.info(f'\n\nFetched Records: {record}')
except Exception as e:
handle_error(e)
logging.info('AMR timer trigger function executed in %s seconds', time.time() - start_time)
requirements.txt
azure-functions
python-dotenv
requests
python-dateutil
inflect
tqdm
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsFeatureFlags": "EnableWorkerIndexing"
}
}
Code is working fine when tested locally but when it is published it is not showing in azure portal.
Any help or suggestions will be appreciated as I want to test the deployment reliably.
I tried all the above-mentioned steps. The expected results is successful deployment of Azure Function.
I'm having some of the same issues. I'm running on node and found that the latest tag isn't working for me (4.33.2). I did this and it worked.
FROM mcr.microsoft.com/azure-functions/node:4.33.1
Can you try something similar? Drop back one version?