azureazure-functionsazure-functions-core-tools

Deploy to azure functions app sending all files to app files but not recognising my functions


I have tried to deploy a functions app to azure. The app deploys but then does not recognise I have functions.

import logging
import os
import azure.functions as func
from azure.core.credentials import AzureKeyCredential
from azure.ai.documentintelligence import DocumentIntelligenceClient
from .feature_extraction import extract_section_headers


# Set up logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

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


@app.route(route="HttpTrigger", auth_level=func.AuthLevel.ANONYMOUS)
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    document_url = req.params.get('documentUrl')
    if not document_url:
        try:
            req_body = req.get_json()
            document_url = req_body.get('documentUrl')
        except ValueError:
            pass

    if not document_url:
        return func.HttpResponse(
             "Please pass a document URL in the query string or in the "
             "request body",
             status_code=400
        )

    # Azure credentials from environment variables
    endpoint = os.environ["DOCUMENT_INTELLIGENCE_ENDPOINT"]
    key = os.environ["DOCUMENT_INTELLIGENCE_KEY"]

    credential = AzureKeyCredential(key)
    document_intelligence_client = DocumentIntelligenceClient(
        endpoint=endpoint,
        credential=credential
    )

    try:
        poller = document_intelligence_client.begin_analyze_document_from_url(
            "prebuilt-layout", document_url)
        result = poller.result()

        # Extract section headers
        section_headers = extract_section_headers(result)
        logger.info(section_headers)

        return func.HttpResponse(
            body=str(section_headers),
            mimetype="application/json",
            status_code=200
        )
    except Exception as e:
        logger.error(f"Failed to analyze document. Exception: {str(e)}")
        return func.HttpResponse(
            f"Failed to analyze document. Exception: {str(e)}",
            status_code=500
        )


app.register_functions(extract_section_headers)

I am also using another file called extract section headers where I have started the function like this: from typing import List import azure.functions as func

feature_extraction = func.Blueprint()

@feature_extraction.function_name("extract_section_headers") def extract_section_headers(analyze_result) -> List[dict]: """ Extracts section headers from the analyzed document.

Also please find attached my project layout: Project layout

local.settings.json:

{
    "IsEncrypted": false,
    "Values": {
      "FUNCTIONS_WORKER_RUNTIME": "python",
      "DOCUMENT_INTELLIGENCE_ENDPOINT": "https://smartformprocessor.cognitiveservices.azure.com/",
      "DOCUMENT_INTELLIGENCE_KEY": "861e665469694f99acc152609d367628",
      "AzureWebJobsFeatureFlags": "EnableWorkerIndexing"
    }
  }

I am also experiencing this error, although I believe this is just related to local development.

**[2024-02-12T08:51:10.900Z] Reading functions metadata (Host)
[2024-02-12T08:51:10.900Z] 0 functions found (Host)
[2024-02-12T08:51:10.901Z] Reading functions metadata (Custom)
[2024-02-12T08:51:10.901Z] 1 functions found (Custom)
[2024-02-12T08:51:10.901Z] 0 functions loaded
[2024-02-12T08:51:10.901Z] Generating 0 job function(s)
[2024-02-12T08:51:10.904Z] No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).
[2024-02-12T08:51:10.904Z] HttpOptions
[2024-02-12T08:51:10.904Z] Initializing function HTTP routes
[2024-02-12T08:51:10.904Z] No HTTP routes mapped**

I am expecting the functions to be shown in the functions section of my azure portal. I have tried debugging locally and also deploying via github actions with a successful deployment but still not functions.


Solution

  • I have created a V2 python function with below code in it and added the necessary packages in requirements.txt file.

    function_app.py-

    import azure.functions as func
    import logging
    import os
    from azure.core.credentials import AzureKeyCredential 
    from azure.ai.formrecognizer import DocumentAnalysisClient
    from feature_extraction import extract_section_headers
    
    app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
    
    @app.route(route="http_trigger")
    def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
        logging.info('Python HTTP trigger function processed a request.')
    
        document_url = req.params.get('documentUrl')
        if not document_url:
            try:
                req_body = req.get_json()
            except ValueError:
                pass
            else:
                document_url = req_body.get('documentUrl')
    
        if not document_url:
            return func.HttpResponse(
                 "Please pass a document URL in the query string or in the request body",
                 status_code=200
            )
        # Azure credentials from environment variables
        endpoint = os.environ["DOCUMENT_INTELLIGENCE_ENDPOINT"]
        key = os.environ["DOCUMENT_INTELLIGENCE_KEY"]
    
        credential = AzureKeyCredential(key)
        document_intelligence_client = DocumentAnalysisClient(
            endpoint=endpoint,
            credential=credential
        )
        
        try:
            poller = document_intelligence_client.begin_analyze_document_from_url(
                "prebuilt-read", document_url)
            result = poller.result()
            
            # Extract section headers
            section_headers = extract_section_headers(result)
            logging.info(section_headers)
            
            return func.HttpResponse(
                body=str(section_headers),
                mimetype="application/json",
                status_code=200
            )
        except Exception as e:
            logging.error(f"Failed to analyze document. Exception: {str(e)}")
            return func.HttpResponse(
                f"Failed to analyze document. Exception: {str(e)}",
                status_code=500
            )
            
    
    

    requirements.txt file looks like below-

    azure-functions
    azure-ai-formrecognizer
    azure-core
    

    Then executed the function locally and got the expected output.

    enter image description here

    enter image description here

    Portal-

    enter image description here