Python Developer Reference for Azure Functions

This section provides detailed reference information for developing Azure Functions using Python.

Core Libraries and Features

Function App Structure

A Python function app is typically organized as follows:

my_function_app/
├── .venv/                (Virtual environment)
├── __init__.py           (Entry point for the app)
├── requirements.txt      (Python dependencies)
├── local.settings.json   (Local development settings)
├── host.json             (Function host configuration)
└── MyHttpTrigger/        (A single function folder)
    ├── __init__.py       (The function's Python code)
    └── function.json     (Function bindings and configuration)
└── MyTimerTrigger/       (Another function folder)
    ├── __init__.py
    └── function.json
            

Python Version Support

Azure Functions supports the following Python versions:

It's recommended to use the latest supported version for new projects.

Dependencies (requirements.txt)

All Python packages your function app needs must be listed in the requirements.txt file.

azure-functions
requests==2.28.1
pandas>=1.5.0
            

Virtual Environments

It's highly recommended to use a virtual environment for each function app to manage dependencies. You can create one using:

python -m venv .venv
source .venv/bin/activate  # On Linux/macOS
.venv\Scripts\activate      # On Windows
            

Triggers and Bindings

Python functions leverage triggers and bindings to connect to Azure services and other resources. These are defined in the function.json file for each function.

HTTP Trigger Example (function.json)

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
            

HTTP Trigger Example (Python - __init__.py)


import logging
import azure.functions as func

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

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

    if name:
        return func.HttpResponse(
             f"Hello, {name}. This HTTP triggered function executed successfully.",
             status_code=200
        )
    else:
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body",
             status_code=400
        )
            

Blob Input Binding Example

This example shows how to bind to a blob storage container to read a file.

// function.json
{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "myblob",
      "type": "blob",
      "direction": "in",
      "path": "samples-workitems/{name}.txt",
      "connection": "AzureWebJobsStorage"
    },
    {
      "name": "outputBlob",
      "type": "blob",
      "direction": "out",
      "path": "samples-output/{name}.txt",
      "connection": "AzureWebJobsStorage"
    }
  ]
}
            

// __init__.py
import logging
import azure.functions as func

def main(myblob: bytes, outputBlob: func.Out[str]):
    logging.info(f"Python blob trigger function processed blob\n"
                 f"Name: {myblob}")
    content = myblob.decode('utf-8')
    outputBlob.set(f"Processed content: {content}")
            

Context and Logging

The Context Object

The context object provides information about the execution environment.

Logging

Use Python's standard logging module for outputting logs. These logs will appear in Application Insights.


import logging
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Processing request...')
    # ... your code ...
    logging.warning('A non-critical issue occurred.')
    logging.error('An unrecoverable error occurred.')
    return func.HttpResponse("Response sent.")
            

Asynchronous Programming

Azure Functions in Python supports asynchronous programming using async and await.


import logging
import azure.functions as func
import asyncio

async def process_data(data):
    await asyncio.sleep(1) # Simulate async work
    return f"Processed: {data}"

async def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python async HTTP trigger function processed a request.')
    data_to_process = "some_data"
    result = await process_data(data_to_process)

    return func.HttpResponse(
        f"Async function executed. Result: {result}",
        status_code=200
    )
            
Tip: For CPU-bound operations in Python functions, consider using multiprocessing instead of threading to leverage multiple cores.

Common Scenarios

Note: For the most up-to-date information and advanced topics, please refer to the official Microsoft Azure Functions Python Developer Guide.