The following will run through the Python exercise from the Azure Functions University repo and YouTube channel. Azure Functions University is a great resource for learning all about Azure Functions, including all the various triggers, languages, deployment, and Durable Functions.

Also it’s worth reviewing the Azure Functions Python developer guide on Microsoft Docs.

Create the Azure Function

The following applications are a prerequisite to get started:

Once you have installed Python, install the following packages with pip.

pip install azure-functions
pip install nltk
pip install numpy

Create a new directory and cd into it. Then create a new tst directory.

mkdir azure-functions-university-python && cd azure-functions-university-python
mkdir tst

Create a new Python virtual environment used for local development. If you are using bash use the following:

sudo apt-get install python3-venv
python -m venv .venv
source .venv/bin/activate

Or PowerShell as follows:

py -m venv .venv
.venv\scripts\activate

Note: if you using git you should add /.venv to the .gitignore file

Now download the data_sample.txt which will be used to POST an HTTP request to the API.

# Change to the tst directory
cd tst

# Download the data_sample.txt file
curl https://raw.githubusercontent.com/marcduiker/azure-functions-university/main/src/python/AzureFunctions.Http/homework/homework_resources/data/data_sample.txt -o data_sample.txt

# Change back to the previous directory
cd ..

Create the src directory where the Azure Function project will be created, and cd into it.

mkdir src && cd src

Now, using the Azure Functions Core Tools CLI, create a new project as follows:

func init PythonFuncStopWords --python

Change directory into the new directory.

cd PythonFuncStopWords

And now create a new function app and name it whatever you want. I named mine NLPApplication. Name yours something unique.

func new --name NLPApplication --template "HTTP trigger" --authlevel "function"

Within the PythonFuncStopWords directory I created a new folder called shared_code. This will be used to host a couple of other Python functions which will be imported into the main function.

mkdir shared_code && cd shared_code

Create a new file called nlp_text_processing.py and copy the code from here. Or you can download it using the following command:

curl https://raw.githubusercontent.com/marcduiker/azure-functions-university/main/src/python/AzureFunctions.Http/homework/homework_resources/shared_code/nlp_text_processing.py -o nlp_text_processing.py

# Change back
cd ..

The PythonFuncStopWords project folder should look like this:

PythonFuncStopWords
│   .funcignore
│   .gitignore
│   getting_started.md
│   host.json
│   local.settings.json
│   requirements.txt
│
├───.vscode
│       extensions.json
│
├───NLPApplication
│       function.json
│       __init__.py
│
└───shared_code
        nlp_text_processing.py

Populate the requirements.txt with the following:

# Do not include azure-functions-worker as it may conflict with the Azure Functions platform
azure-functions
nltk
numpy

Change directory into the function:

cd NLPApplication

The “entry point” to the application is the __init__.py file on GitHub, which should look as follows:

import logging
import json

import azure.functions as func

from ..shared_code import nlp_text_processing as tp

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info("Python HTTP trigger function processed a request.")

    file_sent = None
    text = ""

    try:
        file_sent = req.get_body()
    except ValueError as e:
        logging.error("Value Error: ", e)
        raise ValueError
    else:
        text = str(file_sent)

    processed_text = tp.remove_stop_words(text)
    tokens = tp.tokenize_text(processed_text)
    entities = tp.get_entities(tokens)

    if file_sent:
        return func.HttpResponse(
            json.dumps(
                [
                    {
                        "processedText": processed_text,
                        "tokens": tokens,
                        "entities": entities,
                    }
                ]
            ),
            status_code=200,
        )
    else:
        return func.HttpResponse(
            "Please pass a file in the request body", status_code=400
        )

Now it is time to test the function. Ensure you are in the PythonFuncStopWords directory and then type:

func start

You should receive the following which states the functions URL (http://localhost:7071/api/NLPApplication)

Azure Functions Core Tools
Core Tools Version:       4.0.4590 Commit hash: N/A  (64-bit)
Function Runtime Version: 4.5.2.18383


Functions:

        NLPApplication: [GET,POST] http://localhost:7071/api/NLPApplication

We can test it using Postman. Enter the functions URL (above), set the method the POST, select BODY as binary and then attach the data_sample.txt file from the tst directory. Then click Send

postman1

The following JSON will be returned as the response and a Status: 200 OK will be received.

postman2

This time if you change the method to GET and remove the data_sample.txt, clicking Send will return a Status: 400 Bad Request and the response as “Please pass a file in the request body”. This is all specified in the function’s code.

postman3

Deploy to Azure

Start by creating the resources. Sign into Azure using the CLI

az login

Create a resource group for the resources

az group create --name python-func-rg --location uksouth

Create a Storage Account

az storage account create --name "mkpythonfuncstg" --location uksouth --resource-group python-func-rg --sku Standard_LRS

AZ CLI should return similar to this:

{
  "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/python-func-rg",
  "location": "uksouth",
  "managedBy": null,
  "name": "python-func-rg",
  "properties": {
    "provisioningState": "Succeeded"
  },
  "tags": null,
  "type": "Microsoft.Resources/resourceGroups"
}

Create the function app in Azure. NLPApplication name was available so ensure yours is unique.

az functionapp create --resource-group python-func-rg --os-type Linux --consumption-plan-location uksouth --runtime python --name "NLPApplication" --storage-account "mkpythonfuncstg" --functions-version 3

Here’s how the resource group looks in Azure.

resources

And now deploy the local app to the new Function in Azure.

func azure functionapp publish "NLPApplication" --build remote

deploy

And we can see the app and code now in Azure.

func

Click Get function URL which will include the function key. You can test a GET request with curl

curl https://nlpapplication.azurewebsites.net/api/NLPApplication?code=<FUNCTION-KEY>

Which if successful will return

Please pass a file in the request body

And one more time performing a POST from Postman using the function URL and Key.

postman4

Delete Resources

And finally to delete all of the resources when you are finished.

az group delete --name python-func-rg