Create and run Azure Functions locally by using the Core Tools (javascript)

Create a new functions project with func init

สร้าง functions project ชื่อ FunctionJS2207

> mkdir FunctionJS2207
> cd .\FunctionJS2207\

To create a new functions project, run func init on the command line.

> func init
Use the up/down arrow keys to select a worker runtime:
dotnet
dotnet (isolated process)
node
python
powershell
custom

> func init
Use the up/down arrow keys to select a worker runtime:node
Use the up/down arrow keys to select a language:
javascript
typescript

> func init
Use the up/down arrow keys to select a worker runtime:node
Use the up/down arrow keys to select a language:javascript
Writing package.json
Writing .gitignore
Writing host.json
Writing local.settings.json
Writing C:\Project\FunctionJS2207\.vscode\extensions.json

ดูไฟล์ที่คำสั่ง func init สร้างมาให้ เมื่อเลือกเป็น node , javascript

$ tree
.
├── host.json
├── local.settings.json
└── package.json

0 directories, 3 files

host.json

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[2.*, 3.0.0)"
  }
}

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true"
  }
}

package.json

{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "start": "func start",
    "test": "echo \"No tests yet...\""
  },
  "dependencies": {},
  "devDependencies": {}
}

Create a new function with func new

สร้าง function ชื่อ HttpExample โดยใช้ template แบบ HttpTrigger

> func new
Use the up/down arrow keys to select a template:
Azure Blob Storage trigger
Azure Cosmos DB trigger
Durable Functions activity
Durable Functions entity
Durable Functions Entity HTTP starter
Durable Functions HTTP starter
Durable Functions orchestrator
Azure Event Grid trigger
Azure Event Hub trigger
HTTP trigger
IoT Hub (Event Hub)
Kafka output
Kafka trigger
Azure Queue Storage trigger
RabbitMQ trigger
SendGrid
Azure Service Bus Queue trigger
Azure Service Bus Topic trigger
SignalR negotiate HTTP trigger
Timer trigger

> func new
Use the up/down arrow keys to select a template:HTTP trigger
Function name: [HttpTrigger] HttpExample

จะได้ไฟล์ HttpExample/index.js และไฟล์ HttpExample/function.json

HttpExample/index.js

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}

HttpExample/function.json

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

Run functions locally

> func start

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


Functions:

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

For detailed output, run func with --verbose flag.

Create and run Azure Functions locally by using the Core Tools (Python)

Note: สร้าง functions project ด้วย vscode extension ง่ายกว่าสร้างด้วยคำสั่ง func init (Create an Azure Function by using Visual Studio Code) เพราะจะสร้างไฟล์ config ต่างๆของ vscode และ .venv มาให้ด้วย , สร้างด้วยคำสั่งมีประโยชน์ตอนสร้าง function ด้วย func new

Create a new functions project with func init

สร้าง functions project ชื่อ FunctionPy2207

> mkdir FunctionPy2207
> cd .\FunctionPy2207\

To create a new functions project, run func init on the command line.

> func init
Use the up/down arrow keys to select a worker runtime:
dotnet
dotnet (isolated process)
node
python
powershell
custom

> func init
Use the up/down arrow keys to select a worker runtime:python
Found Python version 3.9.10 (py).
Writing requirements.txt
Writing getting_started.md
Writing .gitignore
Writing host.json
Writing local.settings.json
Writing C:\Project\FunctionPy2207\.vscode\extensions.json

ดูไฟล์ที่คำสั่ง func init สร้างมาให้ เมื่อเลือกเป็น python

$ tree
.
├── getting_started.md
├── host.json
├── local.settings.json
└── requirements.txt

0 directories, 4 files

host.json

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[2.*, 3.0.0)"
  }
}

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true"
  }
}

requirements.txt

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

azure-functions

getting_started.md

## Getting Started with Azure Function
### Last updated: March 8th 2021

#### Project Structure
The main project folder (<project_root>) can contain the following files:

* **local.settings.json** - Used to store app settings and connection strings when running locally. This file doesn't get published to Azure. To learn more, see [local.settings.file](https://aka.ms/azure-functions/python/local-settings).
* **requirements.txt** - Contains the list of Python packages the system installs when publishing to Azure.
* **host.json** - Contains global configuration options that affect all functions in a function app. This file does get published to Azure. Not all options are supported when running locally. To learn more, see [host.json](https://aka.ms/azure-functions/python/host.json).
* **.vscode/** - (Optional) Contains store VSCode configuration. To learn more, see [VSCode setting](https://aka.ms/azure-functions/python/vscode-getting-started).
* **.venv/** - (Optional) Contains a Python virtual environment used by local development.
* **Dockerfile** - (Optional) Used when publishing your project in a [custom container](https://aka.ms/azure-functions/python/custom-container).
* **tests/** - (Optional) Contains the test cases of your function app. For more information, see [Unit Testing](https://aka.ms/azure-functions/python/unit-testing).
* **.funcignore** - (Optional) Declares files that shouldn't get published to Azure. Usually, this file contains .vscode/ to ignore your editor setting, .venv/ to ignore local Python virtual environment, tests/ to ignore test cases, and local.settings.json to prevent local app settings being published.

Each function has its own code file and binding configuration file ([**function.json**](https://aka.ms/azure-functions/python/function.json)).

#### Developing your first Python function using VS Code

If you have not already, please checkout our [quickstart](https://aka.ms/azure-functions/python/quickstart) to get you started with Azure Functions developments in Python. 

#### Publishing your function app to Azure 

For more information on deployment options for Azure Functions, please visit this [guide](https://docs.microsoft.com/en-us/azure/azure-functions/create-first-function-vs-code-python#publish-the-project-to-azure).

#### Next Steps

* To learn more about developing Azure Functions, please visit [Azure Functions Developer Guide](https://aka.ms/azure-functions/python/developer-guide).

* To learn more specific guidance on developing Azure Functions with Python, please visit [Azure Functions Developer Python Guide](https://aka.ms/azure-functions/python/python-developer-guide).

Create a new function with func new

สร้าง function ชื่อ HttpExample โดยใช้ template แบบ HttpTrigger

> func new
Use the up/down arrow keys to select a template:
Azure Blob Storage trigger
Azure Cosmos DB trigger
Durable Functions activity
Durable Functions entity
Durable Functions HTTP starter
Durable Functions orchestrator
Azure Event Grid trigger
Azure Event Hub trigger
HTTP trigger
Kafka output
Kafka trigger
Azure Queue Storage trigger
RabbitMQ trigger
Azure Service Bus Queue trigger
Azure Service Bus Topic trigger
Timer trigger

> func new
Use the up/down arrow keys to select a template:HTTP trigger
Function name: [HttpTrigger] HttpExample
Writing C:\Project\FunctionPy2207\HttpExample\__init__.py
Writing C:\Project\FunctionPy2207\HttpExample\function.json
The function "HttpExample" was created successfully from the "HTTP trigger" template.

จะได้ไฟล์ HttpExample/__init__.py และไฟล์ HttpExample/function.json

HttpExample/__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.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

HttpExample/function.json

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

Run functions locally

> func start
Found Python version 3.9.10 (py).

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


Functions:

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

For detailed output, run func with --verbose flag.

ติดตั้ง package เพิ่ม

สร้าง Virtual Environments ชื่อ .venv

> python -m venv .venv

activate

> .\.venv\Scripts\activate

ติดตั้ง numpy

> python -m pip install numpy

ไฟล์ requirements.txt

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

azure-functions
numpy

เพิ่ม import ที่ไฟล์ __init__.py

import numpy

ลองรัน func start ถ้าไม่ error ก็ติดตั้ง package สำเร็จ

Create and run Azure Functions locally by using the Core Tools (dotnet)

Azure Functions Core Tools

The Azure Functions Core Tools provide a local development experience for creating, developing, testing, running, and debugging Azure Functions.

The Azure Functions Core Tools are a set of command-line tools that you can use to develop and test Azure Functions on your local computer.

Versions

  • v1 (v1.x branch): Requires .NET 4.7.1 Windows Only
  • v2 (dev branch): Self-contained cross-platform package
  • v3: (v3.x branch): Self-contained cross-platform package
  • v4: (v4.x branch): Self-contained cross-platform package (recommended)

Installing on Windows

winget install Microsoft.AzureFunctionsCoreTools

The Core Tools are packaged as a single command-line utility named func. If you run func from the command line without any other commands, it will display version information and a usage guide.

> func

                  %%%%%%
                 %%%%%%
            @   %%%%%%    @
          @@   %%%%%%      @@
       @@@    %%%%%%%%%%%    @@@
     @@      %%%%%%%%%%        @@
       @@         %%%%       @@
         @@      %%%       @@
           @@    %%      @@
                %%
                %


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

Usage: func [context] [context] <action> [-/--options]

Contexts:
azure       Commands to log in to Azure and manage resources
durable     Commands for working with Durable Functions
extensions  Commands for installing extensions
function    Commands for creating and running functions locally
host        Commands for running the Functions host locally
kubernetes  Commands for working with Kubernetes and Azure Functions
settings    Commands for managing environment settings for the local Functions host
templates   Commands for listing available function templates

Actions:
start   Launches the functions runtime host
    --port [-p]             Local port to listen on. Default: 7071
    --cors                  A comma separated list of CORS origins with no spaces. Example: https://functions.azure.com
                            ,https://functions-staging.azure.com
    --cors-credentials      Allow cross-origin authenticated requests (i.e. cookies and the Authentication header)
    --timeout [-t]          Timeout for the functions host to start in seconds. Default: 20 seconds.
    --useHttps              Bind to https://localhost:{port} rather than http://localhost:{port}. By default it creates
                             and trusts a certificate.
    --cert                  for use with --useHttps. The path to a pfx file that contains a private key
    --password              to use with --cert. Either the password, or a file that contains the password for the pfx f
                            ile
    --language-worker       Arguments to configure the language worker.
    --no-build              Do no build current project before running. For dotnet projects only. Default is set to fal
                            se.
    --enableAuth            Enable full authentication handling pipeline.
    --functions             A space seperated list of functions to load.
    --verbose               When false, hides system logs other than warnings and errors.
    --dotnet-isolated-debug When specified, set to true, pauses the .NET Worker process until a debugger is attached.
    --enable-json-output    Signals to Core Tools and other components that JSON line output console logs, when applica
                            ble, should be emitted.
    --json-output-file      If provided, a path to the file that will be used to write the output when using --enable-j
                            son-output.

new     Create a new function from a template. Aliases: new, create
    --language [-l]  Template programming language, such as C#, F#, JavaScript, etc.
    --template [-t]  Template name
    --name [-n]      Function name
    --authlevel [-a] Authorization level is applicable to templates that use Http trigger, Allowed values: [function, a
                     nonymous, admin]. Authorization level is not enforced when running functions from core tools
    --csx            use old style csx dotnet functions

init    Create a new Function App in the current folder. Initializes git repo.
    --source-control       Run git init. Default is false.
    --worker-runtime       Runtime framework for the functions. Options are: dotnet, dotnetIsolated, node, python, powe
                           rshell, custom
    --force                Force initializing
    --docker               Create a Dockerfile based on the selected worker runtime
    --docker-only          Adds a Dockerfile to an existing function app project. Will prompt for worker-runtime if not
                            specified or set in local.settings.json
    --csx                  use csx dotnet functions
    --language             Initialize a language specific project. Currently supported when --worker-runtime set to nod
                           e. Options are - "typescript" and "javascript"
    --managed-dependencies Installs managed dependencies. Currently, only the PowerShell worker runtime supports this f
                           unctionality.
    --no-docs              Do not create getting started documentation file. Currently supported when --worker-runtime
                           set to python.

logs    Gets logs of Functions running on custom backends
    --platform Hosting platform for the function app. Valid options: kubernetes
    --name     Function name

Local development vs. Azure portal development

The Azure portal has a powerful functions editor experience. In most cases, it doesn’t support modifying functions that you develop locally. Once you start using a local development workflow based on Core Tools, you can’t use the Azure portal to make changes to your functions.

Function apps and functions projects

Every function published to Azure belongs to a function app, which is a collection of one or more functions that Azure publishes together into the same environment. All of the functions in a function app share a common set of configuration values. Build them all for the same language runtime. A function app is an Azure resource that can be configured and managed independently.

When you develop functions locally, you work within a functions project. The project is a folder that contains the code and configuration files that define your functions. A functions project on your computer is equivalent to a function app in Azure, and can contain multiple functions that use the same language runtime.

Create a new functions project with func init

สร้าง functions project ชื่อ FunctionCS2207

> mkdir FunctionCS2207
> cd .\FunctionCS2207\

To create a new functions project, run func init on the command line.

> func init
Use the up/down arrow keys to select a worker runtime:
dotnet
dotnet (isolated process)
node
python
powershell
custom

> func init
Use the up/down arrow keys to select a worker runtime:dotnet
Use the up/down arrow keys to select a language:
c#
f#

> func init
Use the up/down arrow keys to select a worker runtime:dotnet
Use the up/down arrow keys to select a language:c#

Writing C:\Project\FunctionCS2207\.vscode\extensions.json

func init will ask you which language runtime you’d like to use for the app and tailor the project folder’s contents appropriately.

ดูไฟล์ที่คำสั่ง func init สร้างมาให้ เมื่อเลือกเป็น dotnet และ c#

$ tree -a
.
├── .gitignore
├── .vscode
│   └── extensions.json
├── FunctionCS2207.csproj
├── host.json
└── local.settings.json

1 directory, 5 files

When you create a new functions project, the files included in the project folder depend on the language runtime you select. Regardless of the runtime you choose, the two most critical project files are always present:

  • host.json stores runtime configuration values, such as logging options, for the function app. The settings stored in this file are used both when running functions locally and in Azure.
  • local.settings.json stores configuration values that only apply to the function app when it’s run locally with the Core Tools. This file contains two kinds of settings:
    • Local runtime settings: Used to configure the local functions runtime itself.
    • Custom application settings: You add and configure them based on your app’s needs. All the functions in the app can access and use them.

host.json

{
    "version": "2.0",
    "logging": {
        "applicationInsights": {
            "samplingSettings": {
                "isEnabled": true,
                "excludedTypes": "Request"
            }
        }
    }
}

local.settings.json

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet"
    }
}

FunctionCS2207.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.0.1" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

Functions projects that func init generates don’t have any functions in them. Let’s find out how to add one.

Create a new function with func new

Each individual function in a project requires code and a configuration to define its behavior. Running func new in a functions project folder will create a new function and all the files you need to get started developing.

สร้าง function ชื่อ HttpExample โดยใช้ template แบบ HttpTrigger

> func new
Use the up/down arrow keys to select a template:
QueueTrigger
HttpTrigger
BlobTrigger
TimerTrigger
KafkaTrigger
KafkaOutput
DurableFunctionsOrchestration
SendGrid
EventHubTrigger
ServiceBusQueueTrigger
ServiceBusTopicTrigger
EventGridTrigger
CosmosDBTrigger
IotHubTrigger

> func new
Use the up/down arrow keys to select a template:Function name: HttpExample
HttpExample

The function "HttpExample" was created successfully from the "HttpTrigger" template.

จะได้ไฟล์ HttpExample.cs

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace FunctionCS2207
{
    public static class HttpExample
    {
        [FunctionName("HttpExample")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }
}

Run functions locally

Functions aren’t programs that can be run on their own: they must be hosted. The function host is what powers everything outside of your function code: it loads the configuration, listens for triggers and HTTP requests, starts the worker process for the language your functions are written in, writes log output, and more. In Azure, function apps run the function host automatically when they start.

You can use the Core Tools to run your own instance of the functions host and try out your functions locally before you publish them. By running your functions before publishing them, you can make sure your configuration and code loads correctly and test out your functions by making real HTTP calls to them without the need for Azure resources.

To start the functions host locally, run func start from a functions project folder. At the end of the output, the Core Tools will display local URLs you can use to call each of your functions. While the host is running, you can use any tools or libraries that make HTTP calls, like curl, to interact with your functions. The Core Tools will write any log output produced by the host to the terminal in real time.

> func start
Microsoft (R) Build Engine version 17.2.0+41abc5629 for .NET
Copyright (C) Microsoft Corporation. All rights reserved.

  Determining projects to restore...
  All projects are up-to-date for restore.
  FunctionCS2207 -> C:\Project\FunctionCS2207\bin\output\FunctionCS2207.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:05.59



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

[2022-07-25T09:35:23.827Z] Found C:\Project\FunctionCS2207\FunctionCS2207.csproj. Using for user secrets file configuration.

Functions:

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

For detailed output, run func with --verbose flag.

ลองเรียกไปที่ http://localhost:7071/api/HttpExample จะได้

This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.

ให้ค่า name http://localhost:7071/api/HttpExample?name=jack

Hello, jack. This HTTP triggered function executed successfully.

ติดตั้ง package เพิ่ม

ทดลองติดตีั้ง NuGet Gallery | NodaTime 3.1.0

> dotnet add package NodaTime

ไฟล์ FunctionCS2207.csproj

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.0.1" />
    <PackageReference Include="NodaTime" Version="3.1.0" />
  </ItemGroup>

เพิ่ม using ที่ไฟล์ HttpExample.cs

using NodaTime;

ลองรัน func start ถ้าไม่ error ก็ติดตั้ง package สำเร็จ

Create an Azure Function by using Visual Studio Code

Prerequisites

Before you begin make sure you have the following requirements in place:

Create your local project

In this section, you use Visual Studio Code to create a local Azure Functions project in C#. Later in this exercise, you’ll publish your function code to Azure.

  1. Choose the Azure icon in the Activity bar, then in the Workspace area, select Add…. Finally, select Create Function….Choosing to create a new project. NoteA pop-up message will likely appear prompting you to create a new project, if it does select Create new project.
  2. Choose a directory location for your project workspace and choose Select. NoteBe sure to select a project folder that is outside of an existing workspace.
  3. Provide the following information at the prompts:
    • Select a language: Choose C#.
    • Select a .NET runtime: Choose .NET 6
    • Select a template for your project’s first function: Choose HTTP trigger.
    • Provide a function name: Type HttpExample.
    • Provide a namespace: Type My.Function.
    • Authorization level: Choose Anonymous, which enables anyone to call your function endpoint.
    • Select how you would like to open your project: Choose Add to workspace.

Using this information, Visual Studio Code generates an Azure Functions project with an HTTP trigger.

Run the function locally

Visual Studio Code integrates with Azure Functions Core tools to let you run this project on your local development computer before you publish to Azure.

  1. Make sure the terminal is open in Visual Studio Code. You can open the terminal by selecting Terminal and then New Terminal in the menu bar.
  2. Press F5 to start the function app project in the debugger. Output from Core Tools is displayed in the Terminal panel. Your app starts in the Terminal panel. You can see the URL endpoint of your HTTP-triggered function running locally.The endpoint of your HTTP-triggered function is displayed in the **Terminal** panel.
  3. With Core Tools running, go to the Azure: Functions area. Under Functions, expand Local Project > Functions. Right-click the HttpExample function and choose Execute Function Now….Steps for running the function locally as described in the text.
  4. In Enter request body type the request message body value of { "name": "Azure" }. Press Enter to send this request message to your function. When the function executes locally and returns a response, a notification is raised in Visual Studio Code. Information about the function execution is shown in Terminal panel.
  5. Press Shift + F5 to stop Core Tools and disconnect the debugger.

After you’ve verified that the function runs correctly on your local computer, it’s time to use Visual Studio Code to publish the project directly to Azure.

Sign in to Azure

Before you can publish your app, you must sign in to Azure. If you’re already signed in, go to the next section.

  1. If you aren’t already signed in, choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose Sign in to Azure….Sign in to Azure within VS Code
  2. When prompted in the browser, choose your Azure account and sign in using your Azure account credentials.
  3. After you’ve successfully signed in, you can close the new browser window. The subscriptions that belong to your Azure account are displayed in the Side bar.

Create resources in Azure

In this section, you create the Azure resources you need to deploy your local function app.

  1. Choose the Azure icon in the Activity bar, then in the Resources area select the Create resource… button.Location of the Deploy to Function app button.
  2. Provide the following information at the prompts:
    • Select Create Function App in Azure…
    • Enter a globally unique name for the function app: Type a name that is valid in a URL path. The name you type is validated to make sure that it’s unique in Azure Functions.
    • Select a runtime stack: Use the same choice you made in the Create your local project section above.
    • Select a location for new resources: For better performance, choose a region near you.
    • Select subscription: Choose the subscription to use. You won’t see this if you only have one subscription.
    The extension shows the status of individual resources as they are being created in Azure in the AZURE: ACTIVITY LOG area of the terminal window.
  3. When completed, the following Azure resources are created in your subscription, using names based on your function app name:
    • A resource group, which is a logical container for related resources.
    • A standard Azure Storage account, which maintains state and other information about your projects.
    • A consumption plan, which defines the underlying host for your serverless function app.
    • A function app, which provides the environment for executing your function code. A function app lets you group functions as a logical unit for easier management, deployment, and sharing of resources within the same hosting plan.
    • An Application Insights instance connected to the function app, which tracks usage of your serverless function.

Deploy the code

  1. In the WORKSPACE section of the Azure bar select the Deploy… button, and then select Deploy to Function App….Image showing location of the **Deploy...** button.
  2. When prompted to Select a resource, choose the function app you created in the previous section.
  3. Confirm that you want to deploy your function by selecting Deploy on the confirmation prompt. ImportantPublishing to an existing function overwrites any previous deployments.

Run the function in Azure

  1. Back in the Resources area in the side bar, expand your subscription, your new function app, and FunctionsRight-click the HttpExample function and choose Execute Function Now….Execute function now in Azure from Visual Studio Code
  2. In Enter request body you see the request message body value of { "name": "Azure" }. Press Enter to send this request message to your function.
  3. When the function executes in Azure and returns a response, a notification is raised in Visual Studio Code.
    Executed function notification

สร้าง Azure Functions แบบ HTTP trigger ด้วย Python

  1. Create a function app
  2. Triggers
  3. Bindings
  4. Create a function in the Azure portal
  5. Navigate to your function and its files
  6. Test in the Azure portal
  7. Run function manually
  8. Other .Net

Azure Functions allow developers to host business logic that can be executed without managing or provisioning infrastructure.

1. Create a function app

Let’s create a function app in the Azure portal.

  1. Sign in to the Azure portal
  2. Under Azure services, select Create a resource.
  3. In the menu, select Compute, and then select Function App in the Popular products list.
  4. On the Basics tab, enter the following values for each setting.
SettingValue
PublishCode
Runtime stackPython
Version*3.8
Play typeConsumption (Serverless)

*Python มีเวอร์ชันให้เลือกเป็น 3.7 , 3.8 , 3.9

When deployment completes, select Go to resource

2. Triggers

Functions are event driven, which means they run in response to an event. The type of event that starts a function is called a trigger. Each function must be configured with exactly one trigger.

Azure supports triggers for the following services.

ServiceTrigger description
Blob StorageStarts a function when a new or updated blob is detected.
Azure Cosmos DBStart a function when inserts and updates are detected.
Event GridStarts a function when an event is received from Event Grid.
HTTPStarts a function with an HTTP request.
Microsoft Graph EventsStarts a function in response to an incoming webhook from the Microsoft Graph. Each instance of this trigger can react to one Microsoft Graph resource type.
Queue StorageStarts a function when a new item is received on a queue. The queue message is provided as input to the function.
Service BusStarts a function in response to messages from a Service Bus queue.
TimerStarts a function on a schedule.

3. Bindings

A binding is a declarative way to connect data and services to your function. Bindings interact with various data sources, which means you don’t have to write the code in your function to connect to data sources and manage connections. The platform takes care of that complexity for you as part of the binding code.

Each binding has a direction–your code reads data from input bindings, and writes data to output bindings. Each function can have zero or more bindings to manage the input and output data processed by the function.

A trigger is a type of input binding that has the ability to initiate execution of some code.

Azure provides a large number of bindings to connect to different storage and messaging services.

4. Create a function in the Azure portal

When you create your first function in the Azure Create function pane, you can select a predefined trigger for your function. Based on your selections, Azure generates default code and configuration information, such as creating an event log entry when input data is received.

When you create a function from a template, several files are created, including a configuration file, function.json, and a source code file, __init__.py.

When you select a function that you created in your function app, the Function pane opens. By selecting Code + Test from the Function menu, you have access to actions in the command bar to test and run the code, to save or discard changes you make, or to obtain the published URL.

By selecting Test/Run from the command bar, you can run use cases for requests that include query strings and values. The function’s path above the code box displays the name of the file that is open. You can select a specific file from the dropdown to test or edit, for example, function.json.

__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.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

function.json

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]
}

The bindings property is where you configure both triggers and bindings. Each binding shares a few common settings and some settings which are specific to a particular type of binding. Every binding requires the following settings:

PropertyTypesComments
typestringName of binding. For example, queueTrigger.
directionstringIndicates whether the binding is for receiving data into the function or sending data from the function. For example, in or out.
namestringThe name that is used for the bound data in the function. For example, myQueue.

6. Test in the Azure portal

The portal also provides a convenient way to test your functions. As previously described, in the screenshot above. When you select Run in this pane, the results automatically appear in the Output tab, and the Logs pane opens to display the status.

7. Run function manually

You can start a function by manually triggering the configured trigger. For instance, if you’re using an HTTP trigger, you can use a tool, such as Postman or cURL, to initiate an HTTP request to your function endpoint URL, which is available from the function definition (Get function URL).

เช่นตัวอย่างนี้ก็ ต่อท้าย url ด้วย &name=jack

8. Other .Net

.Net 6

run.csx

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    string responseMessage = string.IsNullOrEmpty(name)
        ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
}

function.json

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ]
}