Source: MicrosoftDocs/azure-docs
title: Create a Python function from the command line - Azure Functions description: Learn how to create a Python function from the command line, then publish the local project to serverless hosting in Azure Functions. ms.date: 12/14/2023 ms.topic: quickstart ms.devlang: python ms.custom: devx-track-python, devx-track-azurecli, devx-track-azurepowershell, mode-api, devdivchpfy22 zone_pivot_groups: python-mode-functions
In this article, you use command-line tools to create a Python function that responds to HTTP requests. After testing the code locally, you deploy it to the serverless environment of Azure Functions.
This article covers both Python programming models supported by Azure Functions. Use the selector at the top to choose your programming model.
Note
The Python v2 programming model for Azure Functions provides a decorator-based approach for creating functions. To learn more about the Python v2 programming model, see the Developer Reference Guide.
Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.
There's also a Visual Studio Code-based version of this article.
Before you begin, you must have the following requirements in place:
-
An Azure account with an active subscription. Create an account for free.
-
One of the following tools for creating Azure resources:
-
Azure CLI version 2.4 or later.
-
The Azure Az PowerShell module version 5.9.0 or later.
-
-
Python versions that are supported by Azure Functions. ::: zone pivot="python-mode-decorators"
-
The Azurite storage emulator. While you can also use an actual Azure Storage account, the article assumes you're using this emulator. ::: zone-end
[!INCLUDE functions-install-core-tools]
In a suitable folder, run the following commands to create and activate a virtual environment named .venv. Make sure that you're using a version of Python that is supported by Azure Functions.
python -m venv .venvsource .venv/bin/activateIf Python didn't install the venv package on your Linux distribution, run the following command:
sudo apt-get install python3-venvpy -m venv .venv.venv\scripts\activatepy -m venv .venv.venv\scripts\activateYou run all subsequent commands in this activated virtual environment.
In Azure Functions, a function project is a container for one or more individual functions that each responds to a specific trigger. All functions in a project share the same local and hosting configurations.
::: zone pivot="python-mode-configuration"
In this section, you create a function project that contains a single function.
-
Run the
func initcommand as follows to create a Python functions project in the virtual environment.func init --python --model V1The environment now contains various files for the project, including configuration files named local.settings.json and host.json. Because local.settings.json can contain secrets downloaded from Azure, the file is excluded from source control by default in the .gitignore file.
-
Add a function to your project by using the following command, where the
--nameargument is the unique name of your function (HttpExample) and the--templateargument specifies the function's trigger (HTTP).func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous"func newcreates a subfolder matching the function name that contains a code file appropriate to the project's chosen language and a configuration file named function.json. -
Run this command to make sure that the Azure Functions library is installed in the environment.
.venv/bin/python -m pip install -r requirements.txt
.venv\Scripts\python -m pip install -r requirements.txt
.venv\Scripts\python -m pip install -r requirements.txt
::: zone-end
::: zone pivot="python-mode-decorators"
In this section, you create a function project and add an HTTP triggered function.
-
Run the
func initcommand as follows to create a Python v2 functions project in the virtual environment.func init --pythonThe environment now contains various files for the project, including configuration files named local.settings.json and host.json. Because local.settings.json can contain secrets downloaded from Azure, the file is excluded from source control by default in the .gitignore file.
-
Add a function to your project by using the following command, where the
--nameargument is the unique name of your function (HttpExample) and the--templateargument specifies the function's trigger (HTTP).func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous"If prompted, choose the ANONYMOUS option.
func newadds an HTTP trigger endpoint namedHttpExampleto thefunction_app.pyfile, which is accessible without authentication. -
Open the local.settings.json project file and verify that the
AzureWebJobsFeatureFlagssetting has a value ofEnableWorkerIndexing. This is required for Functions to interpret your project correctly as the Python v2 model. You'll add this same setting to your application settings after you publish your project to Azure. -
In the local.settings.json file, update the
AzureWebJobsStoragesetting as in the following example:"AzureWebJobsStorage": "UseDevelopmentStorage=true",
This tells the local Functions host to use the storage emulator for the storage connection currently required by the Python v2 model. When you publish your project to Azure, you'll need to instead use the default storage account. If you're instead using an Azure Storage account, set your storage account connection string here.
-
Run this command to make sure that the Azure Functions library is installed in the environment.
.venv/bin/python -m pip install -r requirements.txt
.venv\Scripts\python -m pip install -r requirements.txt
.venv\Scripts\python -m pip install -r requirements.txt
By default, local development uses the Azurite storage emulator. This emulator is used when the AzureWebJobsStorage setting in the local.settings.json project file is set to UseDevelopmentStorage=true. When using the emulator, you must start the local Azurite storage emulator before running the function.
You can skip this step if the AzureWebJobsStorage setting in local.settings.json is set to the connection string for an Azure Storage account instead of UseDevelopmentStorage=true.
Use the following command to start the Azurite storage emulator in a separate process:
start azuriteFor more information, see Run Azurite ::: zone-end
[!INCLUDE functions-run-function-test-local-cli]
Before you can deploy your function code to Azure, you need to create three resources:
- A resource group, which is a logical container for related resources.
- A storage account, which maintains the state and other information about your projects.
- A function app, which provides the environment for executing your function code. A function app maps to your local function project and lets you group functions as a logical unit for easier management, deployment, and sharing of resources.
Use the following commands to create these items. Both Azure CLI and PowerShell are supported.
-
If you haven't done so already, sign in to Azure.
az loginThe
az logincommand signs you into your Azure account.Connect-AzAccountThe Connect-AzAccount cmdlet signs you into your Azure account.
-
Create a resource group named
AzureFunctionsQuickstart-rgin your chosen region.az group create --name AzureFunctionsQuickstart-rg --location <REGION>The az group create command creates a resource group. In the above command, replace
<REGION>with a region near you, using an available region code returned from the az account list-locations command.New-AzResourceGroup -Name AzureFunctionsQuickstart-rg -Location '<REGION>'The New-AzResourceGroup command creates a resource group. You generally create your resource group and resources in a region near you, using an available region returned from the Get-AzLocation cmdlet.
::: zone pivot="python-mode-decorators" ::: zone-end
[!NOTE] You can't host Linux and Windows apps in the same resource group. If you have an existing resource group named
AzureFunctionsQuickstart-rgwith a Windows function app or web app, you must use a different resource group. -
Create a general-purpose storage account in your resource group and region.
az storage account create --name <STORAGE_NAME> --location <REGION> --resource-group AzureFunctionsQuickstart-rg --sku Standard_LRSThe az storage account create command creates the storage account.
New-AzStorageAccount -ResourceGroupName AzureFunctionsQuickstart-rg -Name <STORAGE_NAME> -SkuName Standard_LRS -Location <REGION>The New-AzStorageAccount cmdlet creates the storage account.
In the previous example, replace
<STORAGE_NAME>with a name that's appropriate to you and unique in Azure Storage. Names must contain 3 to 24 characters numbers and lowercase letters only.Standard_LRSspecifies a general-purpose account supported by Functions.The storage account incurs only a few cents (USD) for this quickstart.
-
Create the function app in Azure.
az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location westeurope --runtime python --runtime-version 3.9 --functions-version 4 --name <APP_NAME> --os-type linux --storage-account <STORAGE_NAME>The az functionapp create command creates the function app in Azure. If you're using Python 3.9, 3.8, or 3.7, change
--runtime-versionto3.9,3.8, or3.7, respectively. You must supply--os-type linuxbecause Python functions can't run on Windows, which is the default.New-AzFunctionApp -Name <APP_NAME> -ResourceGroupName AzureFunctionsQuickstart-rg -StorageAccountName <STORAGE_NAME> -FunctionsVersion 4 -RuntimeVersion 3.9 -Runtime python -Location '<REGION>'The New-AzFunctionApp cmdlet creates the function app in Azure. If you're using Python 3.9, 3.8, or 3.7, change
-RuntimeVersionto3.9,3.8, or3.7, respectively.
In the previous example, replace
<APP_NAME>with a globally unique name appropriate to you. The<APP_NAME>is also the default DNS domain for the function app.This command creates a function app running in your specified language runtime under the Azure Functions Consumption Plan, which is free for the amount of usage you incur here. The command also creates an associated Azure Application Insights instance in the same resource group, with which you can monitor your function app and view logs. For more information, see Monitor Azure Functions. The instance incurs no costs until you activate it.
[!INCLUDE functions-publish-project-cli]
::: zone pivot="python-mode-decorators"
To use the Python v2 model in your function app, you need to add a new application setting in Azure named AzureWebJobsFeatureFlags with a value of EnableWorkerIndexing. This setting is already in your local.settings.json file.
Run the following command to add this setting to your new function app in Azure.
az functionapp config appsettings set --name <FUNCTION_APP_NAME> --resource-group <RESOURCE_GROUP_NAME> --settings AzureWebJobsFeatureFlags=EnableWorkerIndexing
Update-AzFunctionAppSetting -Name <FUNCTION_APP_NAME> -ResourceGroupName <RESOURCE_GROUP_NAME> -AppSetting @{"AzureWebJobsFeatureFlags" = "EnableWorkerIndexing"}
In the previous example, replace <FUNCTION_APP_NAME> and <RESOURCE_GROUP_NAME> with the name of your function app and resource group, respectively. This setting is already in your local.settings.json file.
::: zone-end
Run the following command to view near real-time streaming logs in Application Insights in the Azure portal.
func azure functionapp logstream <APP_NAME> --browserIn a separate terminal window or in the browser, call the remote function again. A verbose log of the function execution in Azure is shown in the terminal.
[!INCLUDE functions-cleanup-resources-cli]
[!div class="nextstepaction"] Connect to an Azure Storage queue
Having issues with this article?