Python Code for Wrike APIs Working In Emulator but not working when deployed to Azure Functions

141 views Asked by At

I wrote an azure function to change the prefixes of tasks in Wrike using APIs for the events TaskParentsAdded, TaskParentsRemoved, TaskCustomFieldChanged. The code works as expected when I run the code locally, but when I deploy it to Azure it gives me this error "Error: error "syntaxError: Unexpected token "',"'/home/Log"...is not valid JSON" occurred while parsing the response body - '/home/LogFiles/' not found.." under the connect to Log Stream folder. I have attached the function I think is the problem.

@app.route(route=MAIN_ROUTE, auth_level=func.AuthLevel.ANONYMOUS)
def main(req, context):
#Retrieve the payload from the request 
    try:
        #this should apply in production
        payload = req.get_json()
    except:
        try:
            #this should apply during testing
            payload = req.params
        except:
            payload = {}
            
        logging.info(f'Got request: {payload}')

I tried changing my logging configuration, my endpoint URL, which made it unable to run in the emulator.

1

There are 1 answers

0
Suresh Chikkam On
  • Configure your log path clearly in your host.json file before the deployment.

host.Json

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    },
    "fileLoggingMode": "always",
    "logLevel": {
      "default": "Information"
    },
    "fileLoggingFolder": "/home/LogFiles/"
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}
  • If the error still occurs same at the deployment stage, then try to remove the fileLoggingMode configuration.

  • The Azure Function will not attempt to write logs to the file system. Instead, it will rely on the Application Insights integration for logging.

Function app - __init__.py

import azure.functions as func


def process_wrike_event(req):
    try:
        event_payload = req.get_json()
    except ValueError:
        logging.warning('Invalid event payload. Unable to process the event.')
        return

    # Extract relevant information from the event payload
    event_type = event_payload['eventType']
    task_id = event_payload['taskId']

    # Check the event type and perform the necessary action
    if event_type == 'TaskParentsAdded':
        # Change the task prefix using Wrike API
        change_task_prefix(task_id, 'new-prefix')

    elif event_type == 'TaskParentsRemoved':
        # Change the task prefix using Wrike API
        change_task_prefix(task_id, 'new-prefix')

    elif event_type == 'TaskCustomFieldChanged':
        # Check if the custom field corresponds to the prefix
        if event_payload['customFieldId'] == 'prefix-field-id':
            # Change the task prefix using Wrike API
            change_task_prefix(task_id, event_payload['newPrefix'])

    else:
        logging.warning(f"Unsupported event type: {event_type}")

def change_task_prefix(task_id, new_prefix):
    wrike_api_token = os.environ['WRIKE_API_TOKEN']

    # Make an API request to Wrike to update the task prefix
    api_url = f"https://api.wrike.com/v4/tasks/{task_id}"
    headers = {'Authorization': f'Bearer {wrike_api_token}'}
    payload = {'title': f'{new_prefix} - Updated Title'}

    response = requests.put(api_url, headers=headers, json=payload)

    if response.status_code == 200:
        logging.info(f"Task prefix updated for task ID: {task_id}")
    else:
        logging.error(f"Failed to update task prefix. Status code: {response.status_code}, Error: {response.text}")

# Azure Function HTTP trigger
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Received Wrike event')
    try:
        process_wrike_event(req)
        return func.HttpResponse('OK', status_code=200)
    except Exception as e:
        logging.error(f"Error processing Wrike event: {e}")
        return func.HttpResponse('Error', status_code=500)

Output: enter image description here