title | description | ms.date | ms.topic | ms.devlang | ms.custom | ROBOTS |
---|---|---|---|---|---|---|
Create a Python function from the command line for Azure Functions |
Learn how to create a Python function from the command line and publish the local project to serverless hosting in Azure Functions. |
11/03/2020 |
quickstart |
python |
devx-track-powershell, devx-track-azurecli, devx-track-azurepowershell, mode-api |
NOINDEX,NOFOLLOW |
[!div class="op_single_selector" title1="Select your function language: "]
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.
Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.
There is also a Visual Studio Code-based version of this article.
Before you begin, you must have the following:
-
An Azure account with an active subscription. Create an account for free.
-
The Azure Functions Core Tools version 3.x.
-
Either the Azure CLI or Azure PowerShell for creating Azure resources:
-
Azure CLI version 2.4 or later.
-
The Azure Az PowerShell module version 5.9.0 or later.
-
-
Python 3.8 (64-bit), Python 3.7 (64-bit), Python 3.6 (64-bit), which are all supported by version 3.x of Azure Functions.
Verify your prerequisites, which depend on whether you are using the Azure CLI or Azure PowerShell for creating Azure resources:
-
In a terminal or command window, run
func --version
to check that the Azure Functions Core Tools are version 3.x. -
Run
az --version
to check that the Azure CLI version is 2.4 or later. -
Run
az login
to sign in to Azure and verify an active subscription. -
Run
python --version
(Linux/macOS) orpy --version
(Windows) to check your Python version reports 3.8.x, 3.7.x or 3.6.x.
-
In a terminal or command window, run
func --version
to check that the Azure Functions Core Tools are version 3.x. -
Run
(Get-Module -ListAvailable Az).Version
and verify version 5.0 or later. -
Run
Connect-AzAccount
to sign in to Azure and verify an active subscription. -
Run
python --version
(Linux/macOS) orpy --version
(Windows) to check your Python version reports 3.8.x, 3.7.x or 3.6.x.
In a suitable folder, run the following commands to create and activate a virtual environment named .venv
. Be sure to use Python 3.8, 3.7 or 3.6, which are supported by Azure Functions.
python -m venv .venv
source .venv/bin/activate
If Python didn't install the venv package on your Linux distribution, run the following command:
sudo apt-get install python3-venv
py -m venv .venv
.venv\scripts\activate
py -m venv .venv
.venv\scripts\activate
You run all subsequent commands in this activated virtual environment.
In this section, you create a local Azure Functions project in Python. Each function in the project responds to a specific trigger.
-
Run the
func init
command to create a functions project in a folder named LocalFunctionProj with the specified runtime:func init LocalFunctionProj --python
-
Navigate into the project folder:
cd LocalFunctionProj
What's created in the LocalFunctionProj folder?
This folder contains various files for the project, including configurations 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:
func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous"
The
--name
argument is the unique name of your function (HttpExample).The
--template
argument specifies the function's trigger (HTTP).func new
creates a subfolder matching the function name that contains an __init__.py file with the function's code and a configuration file named function.json.
Code for __init__.py
__init__.py contains a
main()
Python function that's triggered according to the configuration in function.json.:::code language="python" source="~/functions-quickstart-templates/Functions.Templates/Templates/HttpTrigger-Python/init.py":::
For an HTTP trigger, the function receives request data in the variable
req
as defined in function.json.req
is an instance of the azure.functions.HttpRequest class. The return object, defined as$return
in function.json, is an instance of azure.functions.HttpResponse class. To learn more, see Azure Functions HTTP triggers and bindings.
Code for function.json
function.json is a configuration file that defines the input and output bindings for the function, including the trigger type.
You can change
scriptFile
to invoke a different Python file if desired.:::code language="json" source="~/functions-quickstart-templates/Functions.Templates/Templates/HttpTrigger-Python/function.json":::
Each binding requires a direction, a type, and a unique name. The HTTP trigger has an input binding of type
httpTrigger
and output binding of typehttp
.
-
Run your function by starting the local Azure Functions runtime host from the LocalFunctionProj folder:
func start
Toward the end of the output, the following lines should appear:
... Now listening on: http://0.0.0.0:7071 Application started. Press Ctrl+C to shut down. Http Functions: HttpExample: [GET,POST] http://localhost:7071/api/HttpExample ...
I don't see HttpExample in the output
If HttpExample doesn't appear, you likely started the host from outside the root folder of the project. In that case, use Ctrl+C to stop the host, navigate to the project's root folder, and run the previous command again.
-
Copy the URL of your HttpExample function from this output to a browser and append the query string ?name=<YOUR_NAME>, making the full URL like http://localhost:7071/api/HttpExample?name=Functions. The browser should display a message like Hello Functions:
-
The terminal in which you started your project also shows log output as you make requests.
-
When you're done, use Ctrl+C and choose y to stop the functions host.
Before you can deploy your function code to Azure, you need to create a resource group, a storage account, and a function app by using the following commands:
-
If you haven't done so already, sign in to Azure:
az login
The az login command signs you into your Azure account.
Connect-AzAccount
The Connect-AzAccount cmdlet signs you into your Azure account.
-
Create a resource group named
AzureFunctionsQuickstart-rg
in thewesteurope
region.az group create --name AzureFunctionsQuickstart-rg --location westeurope
The az group create 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
az account list-locations
command.New-AzResourceGroup -Name AzureFunctionsQuickstart-rg -Location westeurope
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.
You can't host Linux and Windows apps in the same resource group. If you have an existing resource group named
AzureFunctionsQuickstart-rg
with a Windows function app or web app, you must use a different resource group. -
Create a general-purpose Azure Storage account in your resource group and region:
az storage account create --name <STORAGE_NAME> --location westeurope --resource-group AzureFunctionsQuickstart-rg --sku Standard_LRS
The az storage account create command creates the storage account.
New-AzStorageAccount -ResourceGroupName AzureFunctionsQuickstart-rg -Name <STORAGE_NAME> -SkuName Standard_LRS -Location westeurope
The New-AzStorageAccount cmdlet creates the storage account.
Replace
<STORAGE_NAME>
with a name that is appropriate to you and unique in Azure Storage. Names must contain three to 24 characters numbers and lowercase letters only.Standard_LRS
specifies a general-purpose account, which is 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.8 --functions-version 3 --name <APP_NAME> --storage-account <STORAGE_NAME> --os-type linux
The az functionapp create command creates the function app in Azure. If you are using Python 3.7 or 3.6, change
--runtime-version
to3.7
or3.6
, respectively.New-AzFunctionApp -Name <APP_NAME> -ResourceGroupName AzureFunctionsQuickstart-rg -StorageAccount <STORAGE_NAME> -FunctionsVersion 3 -RuntimeVersion 3.8 -Runtime python -Location 'West Europe'
The New-AzFunctionApp cmdlet creates the function app in Azure. If you're using Python 3.7 or 3.6, change
-RuntimeVersion
to3.7
or3.6
, respectively.
Replace
<STORAGE_NAME>
with the name of the account you used in the previous step.Replace
<APP_NAME>
with a globally unique name appropriate to you. The<APP_NAME>
is also the default DNS domain for the function app.
What is the cost of the resources provisioned on Azure?
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 provisions 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.
After you've successfully created your function app in Azure, you're now ready to deploy your local functions project by using the func azure functionapp publish command.
In the following example, replace <APP_NAME>
with the name of your app.
func azure functionapp publish <APP_NAME>
The publish
command shows results similar to the following output (truncated for simplicity):
... Getting site publishing info... Creating archive for current directory... Performing remote build for functions project. ... Deployment successful. Remote build succeeded! Syncing triggers... Functions in msdocs-azurefunctions-qs: HttpExample - [httpTrigger] Invoke url: https://msdocs-azurefunctions-qs.azurewebsites.net/api/httpexample
Because your function uses an HTTP trigger, you invoke it by making an HTTP request to its URL in the browser or with a tool like curl.
Copy the complete Invoke URL shown in the output of the publish
command into a browser address bar, appending the query parameter &name=Functions. The browser should display similar output as when you ran the function locally.
Run curl
with the Invoke URL, appending the parameter &name=Functions. The output of the command should be the text, "Hello Functions."
Run the following command to view near real-time streaming logs in Application Insights in the Azure portal:
func azure functionapp logstream <APP_NAME> --browser
Replace <APP_NAME>
with the name of your function app.
In 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.
If you continue to the next step and add an Azure Storage queue output binding, keep all your resources in place as you'll build on what you've already done.
Otherwise, use the following command to delete the resource group and all its contained resources to avoid incurring further costs.
az group delete --name AzureFunctionsQuickstart-rg
Remove-AzResourceGroup -Name AzureFunctionsQuickstart-rg
[!div class="nextstepaction"] Connect to an Azure Storage queue