คำสั่ง AzCopy

AzCopy is a command-line utility that you can use to copy blobs or files to or from a storage account.

Download AzCopy

First, download the AzCopy V10 executable file to any directory on your computer. AzCopy V10 is just an executable file, so there’s nothing to install.

These files are compressed as a zip file (Windows and Mac) or a tar file (Linux). To download and decompress the tar file on Linux, see the documentation for your Linux distribution.

ตรวจสอบเวอร์ชันบน Command prompts

> azcopy --version
azcopy version 10.17.0

ตรวจสอบเวอร์ชันบน PowerShell

> .\azcopy --version
azcopy version 10.17.0

ดู help

> azcopy --help
AzCopy 10.17.0
Project URL: github.com/Azure/azure-storage-azcopy

AzCopy is a command line tool that moves data into and out of Azure Storage.
To report issues or to learn more about the tool, go to github.com/Azure/azure-storage-azcopy

The general format of the commands is: 'azcopy [command] [arguments] --[flag-name]=[flag-value]'.

Usage:
  azcopy [command]

Available Commands:
  bench          Performs a performance benchmark
  completion     Generate the autocompletion script for the specified shell
  copy           Copies source data to a destination location
  doc            Generates documentation for the tool in Markdown format
  env            Shows the environment variables that you can use to configure the behavior of AzCopy.
  help           Help about any command
  jobs           Sub-commands related to managing jobs
  list           List the entities in a given resource
  login          Log in to Azure Active Directory (AD) to access Azure Storage resources.
  logout         Log out to terminate access to Azure Storage resources.
  make           Create a container or file share.
  remove         Delete blobs or files from an Azure storage account
  set-properties (Preview) Given a location, change all the valid system properties of that storage (blob or file)
  sync           Replicate source to the destination location

Flags:
      --cap-mbps float                      Caps the transfer rate, in megabits per second. Moment-by-moment throughput might vary slightly from the cap. If this option is set to zero, or it is omitted, the throughput isn't capped.
  -h, --help                                help for azcopy
      --log-level string                    Define the log verbosity for the log file, available levels: INFO(all requests/responses), WARNING(slow responses), ERROR(only failed requests), and NONE(no output logs). (default 'INFO'). (default "INFO")
      --output-level string                 Define the output verbosity. Available levels: essential, quiet. (default "default")
      --output-type string                  Format of the command's output. The choices include: text, json. The default value is 'text'. (default "text")
      --skip-version-check                  Do not perform the version check at startup. Intended for automation scenarios & airgapped use.      --trusted-microsoft-suffixes string   Specifies additional domain suffixes where Azure Active Directory login tokens may be sent.  The default is '*.core.windows.net;*.core.chinacloudapi.cn;*.core.cloudapi.de;*.core.usgovcloudapi.net;*.storage.azure.net'. Any listed here 
are added to the default. For security, you should only put Microsoft Azure domains here. Separate multiple entries with semi-colons.      
  -v, --version                             version for azcopy

Use "azcopy [command] --help" for more information about a command.

Authorize AzCopy

You can provide authorization credentials by using Azure Active Directory (AD), or by using a Shared Access Signature (SAS) token.

Use this table as a guide:

Storage typeCurrently supported method of authorization
Blob storageAzure AD & SAS
Blob storage (hierarchical namespace)Azure AD & SAS
File storageSAS only

Option 1: Use Azure Active Directory

ใช้คำสั่ง azcopy login

> azcopy login
To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXXXXX to authenticate.

แล้วเปิด browser ไปที่ https://microsoft.com/devicelogin แล้วใส่ code

เลือก account เสร็จแล้ว จะมีหน้าถามว่า Are you trying to sign in to Azure Storage AzCopy? ให้กด Continue

กลับมาที่ terminal จะขึ้นว่า INFO: Login succeeded.

Option 2: Use a SAS token

You can append a SAS token to each source or destination URL that use in your AzCopy commands.

This example command recursively copies data from a local directory to a blob container. A fictitious SAS token is appended to the end of the container URL.

azcopy copy %LOCAL_PATH% %BLOB_PATH%?%SAS_KEY% --recursive=true
azcopy copy "C:\local\path" "https://account.blob.core.windows.net/mycontainer1/?sv=2018-xx-xx&ss...e=2019-05-01T05:01:17Z&st=2019-xx-xx....4%3D" --recursive=true

เมื่อทำงานเสร็จก็ logout

> azcopy logout
INFO: Logout succeeded.

Azure App Services ฟ้อง 404 (Not Found)

นำโปรเจ็กส์ที่สร้างด้วย Bookdown ขึ้น Azure App Services (Stack=.Net, .Net version=.Net 6) แล้วกล่อง Search ใช้งานไม่ได้ ทั้งที่ตอนพัฒนาก็รันด้วย RStudio แล้วใช้งานกล่อง Search เพื่อทำการค้นหาได้ปกติดี

เลยลอง F12 ดูที่ Console ก็เจอว่า search_index.json 404 (Not Found) ทั้งที่ไฟล์ก็มีอยู่

ลองค้น google ดูจนไปเจอกระทู้นี้ javascript – Getting “404 not found” on doing a GET on local file in Azure web app – Stack Overflow อาการเหมือนกันคือมีปัญหาว่าเรียกไฟล์ javascript จากที่อื่นได้ แต่เรียกไฟล์ javascript ที่อยู่ใน local ไม่ได้

ทางแก้คือสร้างไฟล์ web.config ตามนี้

<?xml version="1.0"?>
<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".json" mimeType="application/json" />
     </staticContent>
    </system.webServer>
</configuration>

แล้วเอาไปวางไว้ที่ /site/wwwroot

ลองเรียกเว็บอีกที ก็ใช้ได้ละ

Azure App Service

Azure App Service is an HTTP-based service for hosting web applications, REST APIs, and mobile back ends. You can develop in your favorite programming language, be it .NET, .NET Core, Java, Ruby, Node.js, PHP, or Python. Applications run and scale with ease on both Windows and Linux-based environments.

Built-in auto scale support

Baked into Azure App Service is the ability to scale up/down or scale out/in. Depending on the usage of the web app, you can scale the resources of the underlying machine that is hosting your web app up/down . Resources include the number of cores or the amount of RAM available. Scaling out/in is the ability to increase, or decrease, the number of machine instances that are running your web app.

Continuous integration/deployment support

The Azure portal provides out-of-the-box continuous integration and deployment with Azure DevOps, GitHub, Bitbucket, FTP, or a local Git repository on your development machine. Connect your web app with any of the above sources and App Service will do the rest for you by auto-syncing code and any future changes on the code into the web app.

Deployment slots

When you deploy your web app, web app on Linux, mobile back end, or API app to Azure App Service, you can use a separate deployment slot instead of the default production slot when you’re running in the Standard, Premium, or Isolated App Service plan tier. Deployment slots are live apps with their own host names. App content and configurations elements can be swapped between two deployment slots, including the production slot.

App Service on Linux

App Service can also host web apps natively on Linux for supported application stacks. It can also run custom Linux containers (also known as Web App for Containers). App Service on Linux supports a number of language specific built-in images. Just deploy your code. Supported languages include: Node.js, Java (JRE 8 & JRE 11), PHP, Python, .NET Core, and Ruby. If the runtime your application requires is not supported in the built-in images, you can deploy it with a custom container.

The languages, and their supported versions, are updated on a regular basis. You can retrieve the current list by using the following command in the Cloud Shell.

> az webapp list-runtimes --os-type linux
[
  "DOTNETCORE:7.0",
  "DOTNETCORE:6.0",
  "DOTNETCORE:3.1",
  "NODE:16-lts",
  "NODE:14-lts",
  "PYTHON:3.9",
  "PYTHON:3.8",
  "PYTHON:3.7",
  "PHP:8.0",
  "PHP:7.4",
  "RUBY:2.7",
  "JAVA:11-java11",
  "JAVA:8-jre8",
  "JBOSSEAP:7-java11",
  "JBOSSEAP:7-java8",
  "TOMCAT:10.0-java11",
  "TOMCAT:10.0-jre8",
  "TOMCAT:9.0-java11",
  "TOMCAT:9.0-jre8",
  "TOMCAT:8.5-java11",
  "TOMCAT:8.5-jre8"
]

App Service on Windows

> az webapp list-runtimes --os-type windows
[
  "dotnet:7",
  "dotnet:6",
  "DOTNETCORE:3.1",
  "ASPNET:V4.8",
  "ASPNET:V3.5",
  "NODE:16LTS",
  "NODE:14LTS",
  "PHP:7.4",
  "java:1.8:Java SE:8",
  "java:11:Java SE:11",
  "java:1.8:TOMCAT:10.0",
  "java:11:TOMCAT:10.0",
  "java:1.8:TOMCAT:9.0",
  "java:11:TOMCAT:9.0",
  "java:1.8:TOMCAT:8.5",
  "java:11:TOMCAT:8.5"
]

Limitations

  • App Service on Linux is not supported on Shared pricing tier.
  • You can’t mix Windows and Linux apps in the same App Service plan.
  • The Azure portal shows only features that currently work for Linux apps. As features are enabled, they’re activated on the portal.

Azure App Service plans

In App Service, an app (Web Apps, API Apps, or Mobile Apps) always runs in an App Service plan. An App Service plan defines a set of compute resources for a web app to run. One or more apps can be configured to run on the same computing resources (or in the same App Service plan). In addition, Azure Functions also has the option of running in an App Service plan.

When you create an App Service plan in a certain region (for example, West Europe), a set of compute resources is created for that plan in that region. Whatever apps you put into this App Service plan run on these compute resources as defined by your App Service plan. Each App Service plan defines:

  • Region (West US, East US, etc.)
  • Number of VM instances
  • Size of VM instances (Small, Medium, Large)
  • Pricing tier (Free, Shared, Basic, Standard, Premium, PremiumV2, PremiumV3, Isolated)

The pricing tier of an App Service plan determines what App Service features you get and how much you pay for the plan. There are a few categories of pricing tiers:

  • Shared compute: Both Free and Shared share the resource pools of your apps with the apps of other customers. These tiers allocate CPU quotas to each app that runs on the shared resources, and the resources can’t scale out.
  • Dedicated compute: The BasicStandardPremiumPremiumV2, and PremiumV3 tiers run apps on dedicated Azure VMs. Only apps in the same App Service plan share the same compute resources. The higher the tier, the more VM instances are available to you for scale-out.
  • Isolated: This tier runs dedicated Azure VMs on dedicated Azure Virtual Networks. It provides network isolation on top of compute isolation to your apps. It provides the maximum scale-out capabilities.
  • Consumption: This tier is only available to function apps. It scales the functions dynamically depending on workload.

Deploy to App Service

Every development team has unique requirements that can make implementing an efficient deployment pipeline difficult on any cloud service. App Service supports both automated and manual deployment.

Automated deployment

Automated deployment, or continuous integration, is a process used to push out new features and bug fixes in a fast and repetitive pattern with minimal impact on end users.

Azure supports automated deployment directly from several sources. The following options are available:

  • Azure DevOps: You can push your code to Azure DevOps, build your code in the cloud, run the tests, generate a release from the code, and finally, push your code to an Azure Web App.
  • GitHub: Azure supports automated deployment directly from GitHub. When you connect your GitHub repository to Azure for automated deployment, any changes you push to your production branch on GitHub will be automatically deployed for you.
  • Bitbucket: With its similarities to GitHub, you can configure an automated deployment with Bitbucket.

Manual deployment

There are a few options that you can use to manually push your code to Azure:

  • Git: App Service web apps feature a Git URL that you can add as a remote repository. Pushing to the remote repository will deploy your app.
  • CLIwebapp up is a feature of the az command-line interface that packages your app and deploys it. Unlike other deployment methods, az webapp up can create a new App Service web app for you if you haven’t already created one.
  • Zip deploy: Use curl or a similar HTTP utility to send a ZIP of your application files to App Service.
  • FTP/S: FTP or FTPS is a traditional way of pushing your code to many hosting environments, including App Service.

Use deployment slots

Whenever possible, use deployment slots when deploying a new production build. When using a Standard App Service Plan tier or better, you can deploy your app to a staging environment and then swap your staging and production slots. The swap operation warms up the necessary worker instances to match your production scale, thus eliminating downtime.

Authentication and Authorization in App Service

Azure App Service provides built-in authentication and authorization support, so you can sign in users and access data by writing minimal or no code in your web app, API, and mobile back end, and also Azure Functions.

Why use the built-in authentication?

You’re not required to use App Service for authentication and authorization. Many web frameworks are bundled with security features, and you can use them if you like. If you need more flexibility than App Service provides, you can also write your own utilities.

The built-in authentication feature for App Service and Azure Functions can save you time and effort by providing out-of-the-box authentication with federated identity providers, allowing you to focus on the rest of your application.

  • Azure App Service allows you to integrate a variety of auth capabilities into your web app or API without implementing them yourself.
  • It’s built directly into the platform and doesn’t require any particular language, SDK, security expertise, or even any code to utilize.
  • You can integrate with multiple login providers. For example, Azure AD, Facebook, Google, Twitter.

Identity providers

App Service uses federated identity, in which a third-party identity provider manages the user identities and authentication flow for you. The following identity providers are available by default:

ProviderSign-in endpointHow-To guidance
Microsoft Identity Platform/.auth/login/aadApp Service Microsoft Identity Platform login
Facebook/.auth/login/facebookApp Service Facebook login
Google/.auth/login/googleApp Service Google login
Twitter/.auth/login/twitterApp Service Twitter login
Any OpenID Connect provider/.auth/login/<providerName>App Service OpenID Connect login

When you enable authentication and authorization with one of these providers, its sign-in endpoint is available for user authentication and for validation of authentication tokens from the provider. You can provide your users with any number of these sign-in options.

How it works

The authentication and authorization module runs in the same sandbox as your application code. When it’s enabled, every incoming HTTP request passes through it before being handled by your application code. This module handles several things for your app:

  • Authenticates users with the specified provider
  • Validates, stores, and refreshes tokens
  • Manages the authenticated session
  • Injects identity information into request headers

The module runs separately from your application code and is configured using app settings. No SDKs, specific languages, or changes to your application code are required.

 Note

In Linux and containers the authentication and authorization module runs in a separate container, isolated from your application code. Because it does not run in-process, no direct integration with specific language frameworks is possible.

Authentication flow

The authentication flow is the same for all providers, but differs depending on whether you want to sign in with the provider’s SDK.

  • Without provider SDK: The application delegates federated sign-in to App Service. This is typically the case with browser apps, which can present the provider’s login page to the user. The server code manages the sign-in process, so it is also called server-directed flow or server flow.
  • With provider SDK: The application signs users in to the provider manually and then submits the authentication token to App Service for validation. This is typically the case with browser-less apps, which can’t present the provider’s sign-in page to the user. The application code manages the sign-in process, so it is also called client-directed flow or client flow. This applies to REST APIs, Azure Functions, JavaScript browser clients, and native mobile apps that sign users in using the provider’s SDK.

The table below shows the steps of the authentication flow.

StepWithout provider SDKWith provider SDK
Sign user inRedirects client to /.auth/login/<provider>.Client code signs user in directly with provider’s SDK and receives an authentication token. For information, see the provider’s documentation.
Post-authenticationProvider redirects client to /.auth/login/<provider>/callback.Client code posts token from provider to /.auth/login/<provider> for validation.
Establish authenticated sessionApp Service adds authenticated cookie to response.App Service returns its own authentication token to client code.
Serve authenticated contentClient includes authentication cookie in subsequent requests (automatically handled by browser).Client code presents authentication token in X-ZUMO-AUTH header (automatically handled by Mobile Apps client SDKs).

For client browsers, App Service can automatically direct all unauthenticated users to /.auth/login/<provider>. You can also present users with one or more /.auth/login/<provider> links to sign in to your app using their provider of choice.

Authorization behavior

In the Azure portal, you can configure App Service with a number of behaviors when an incoming request is not authenticated.

  • Allow unauthenticated requests: This option defers authorization of unauthenticated traffic to your application code. For authenticated requests, App Service also passes along authentication information in the HTTP headers.This option provides more flexibility in handling anonymous requests. It lets you present multiple sign-in providers to your users.
  • Require authentication: This option will reject any unauthenticated traffic to your application. This rejection can be a redirect action to one of the configured identity providers. In these cases, a browser client is redirected to /.auth/login/<provider> for the provider you choose. If the anonymous request comes from a native mobile app, the returned response is an HTTP 401 Unauthorized. You can also configure the rejection to be an HTTP 401 Unauthorized or HTTP 403 Forbidden for all requests.

Azure CLI

The Azure Command-Line Interface (CLI) is a cross-platform command-line tool to connect to Azure and execute administrative commands on Azure resources. It allows the execution of commands through a terminal using interactive command-line prompts or a script.

For interactive use, you first launch a shell such as cmd.exe on Windows, or Bash on Linux or macOS, and then issue a command at the shell prompt. To automate repetitive tasks, you assemble the CLI commands into a shell script using the script syntax of your chosen shell, and then you execute the script.

You can install the Azure CLI locally on Linux, Mac, or Windows computers. It can also be used from a browser through the Azure Cloud Shell or run from inside a Docker container.

Install Azure CLI

Start PowerShell as administrator and run the following command:

$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\AzureCLI.msi; Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'; rm .\AzureCLI.msi

Update Azure CLI

> az upgrade
This command is in preview and under development. Reference and support levels: https://aka.ms/CLI_refstatus
You already have the latest azure-cli version: 2.38.0
Upgrade finished.You can enable auto-upgrade with 'az config set auto-upgrade.enable=yes'. More details in https://docs.microsoft.com/cli/azure/update-azure-cli#automatic-update

Run the Azure CLI

You can now run the Azure CLI with the az command from either Windows Command Prompt or PowerShell.

> az

     /\
    /  \    _____   _ _  ___ _
   / /\ \  |_  / | | | \'__/ _\
  / ____ \  / /| |_| | | |  __/
 /_/    \_\/___|\__,_|_|  \___|


Welcome to the cool new Azure CLI!

Use `az --version` to display the current version.
Here are the base commands:

    account             : Manage Azure subscription information.
    acr                 : Manage private registries with Azure Container Registries.
    ad                  : Manage Azure Active Directory Graph entities needed for Role Based Access
                         Control.
    advisor             : Manage Azure Advisor.
    afd                 : Manage Azure Front Door Standard/Premium. For classical Azure Front Door,
                         please refer https://docs.microsoft.com/en-us/cli/azure/network/front-
                         door?view=azure-cli-latest.
    aks                 : Manage Azure Kubernetes Services.
    ams                 : Manage Azure Media Services resources.
    apim                : Manage Azure API Management services.
    appconfig           : Manage App Configurations.
    appservice          : Manage App Service plans.
    aro                 : Manage Azure Red Hat OpenShift clusters.
    backup              : Manage Azure Backups.
    batch               : Manage Azure Batch.
    bicep               : Bicep CLI command group.
    billing             : Manage Azure Billing.
    bot                 : Manage Microsoft Azure Bot Service.
    cache               : Commands to manage CLI objects cached using the `--defer` argument.
    capacity            : Manage capacity.
    cdn                 : Manage Azure Content Delivery Networks (CDNs).
    cloud               : Manage registered Azure clouds.
    cognitiveservices   : Manage Azure Cognitive Services accounts.
    config              : Manage Azure CLI configuration.
    configure           : Manage Azure CLI configuration. This command is interactive.
    consumption         : Manage consumption of Azure resources.
    container           : Manage Azure Container Instances.
    cosmosdb            : Manage Azure Cosmos DB database accounts.
    databoxedge         : Support data box edge device and management.
    deployment          : Manage Azure Resource Manager template deployment at subscription scope.
    deployment-scripts  : Manage deployment scripts at subscription or resource group scope.
    deploymentmanager   : Create and manage rollouts for your service.
    disk                : Manage Azure Managed Disks.
    disk-access         : Manage disk access resources.
    disk-encryption-set : Disk Encryption Set resource.
    dla                 : Manage Data Lake Analytics accounts, jobs, and catalogs.
    dls                 : Manage Data Lake Store accounts and filesystems.
    dms                 : Manage Azure Data Migration Service (DMS) instances.
    eventgrid           : Manage Azure Event Grid topics, domains, domain topics, system topics
                         partner topics, event subscriptions, system topic event subscriptions and
                         partner topic event subscriptions.
    eventhubs           : Manage Azure Event Hubs namespaces, eventhubs, consumergroups and geo
                         recovery configurations - Alias.
    extension           : Manage and update CLI extensions.
    feature             : Manage resource provider features.
    feedback            : Send feedback to the Azure CLI Team.
    find                : I'm an AI robot, my advice is based on our Azure documentation as well as
                         the usage patterns of Azure CLI and Azure ARM users. Using me improves
                         Azure products and documentation.
    functionapp         : Manage function apps. To install the Azure Functions Core tools see
                         https://github.com/Azure/azure-functions-core-tools.
    group               : Manage resource groups and template deployments.
    hdinsight           : Manage HDInsight resources.
    identity            : Managed Identities.
    image               : Manage custom virtual machine images.
    interactive         : Start interactive mode. Installs the Interactive extension if not
                         installed already.
    iot                 : Manage Internet of Things (IoT) assets.
    keyvault            : Manage KeyVault keys, secrets, and certificates.
    kusto               : Manage Azure Kusto resources.
    lab                 : Manage Azure DevTest Labs.
    lock                : Manage Azure locks.
    logicapp            : Manage logic apps.
    login               : Log in to Azure.
    logout              : Log out to remove access to Azure subscriptions.
    managed-cassandra   : Azure Managed Cassandra.
    managedapp          : Manage template solutions provided and maintained by Independent Software
                         Vendors (ISVs).
    managedservices     : Manage the registration assignments and definitions in Azure.
    maps                : Manage Azure Maps.
    mariadb             : Manage Azure Database for MariaDB servers.
    monitor             : Manage the Azure Monitor Service.
    mysql               : Manage Azure Database for MySQL servers.
    netappfiles         : Manage Azure NetApp Files (ANF) Resources.
    network             : Manage Azure Network resources.
    policy              : Manage resource policies.
    postgres            : Manage Azure Database for PostgreSQL servers.
    ppg                 : Manage Proximity Placement Groups.
    private-link        : Private-link association CLI command group.
    provider            : Manage resource providers.
    redis               : Manage dedicated Redis caches for your Azure applications.
    relay               : Manage Azure Relay Service namespaces, WCF relays, hybrid connections, and
                         rules.
    reservations        : Manage Azure Reservations.
    resource            : Manage Azure resources.
    resourcemanagement  : Resourcemanagement CLI command group.
    rest                : Invoke a custom request.
    restore-point       : Manage restore point with res.
    role                : Manage user roles for access control with Azure Active Directory and
                         service principals.
    search              : Manage Azure Search services, admin keys and query keys.
    security            : Manage your security posture with Microsoft Defender for Cloud.
    servicebus          : Manage Azure Service Bus namespaces, queues, topics, subscriptions, rules
                         and geo-disaster recovery configuration alias.
    sf                  : Manage and administer Azure Service Fabric clusters.
    sig                 : Manage shared image gallery.
    signalr             : Manage Azure SignalR Service.
    snapshot            : Manage point-in-time copies of managed disks, native blobs, or other
                         snapshots.
    sql                 : Manage Azure SQL Databases and Data Warehouses.
    sshkey              : Manage ssh public key with vm.
    staticwebapp        : Manage static apps.
    storage             : Manage Azure Cloud Storage resources.
    synapse             : Manage and operate Synapse Workspace, Spark Pool, SQL Pool.
    tag                 : Tag Management on a resource.
    term                : Manage marketplace agreement with marketplaceordering.
    ts                  : Manage template specs at subscription or resource group scope.
    upgrade             : Upgrade Azure CLI and extensions.
    version             : Show the versions of Azure CLI modules and extensions in JSON format by
                         default or format configured by --output.
    vm                  : Manage Linux or Windows virtual machines.
    vmss                : Manage groupings of virtual machines in an Azure Virtual Machine Scale Set
                         (VMSS).
    webapp              : Manage web apps.

Login

> az login
A web browser has been opened at https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize. Please continue the login in the web browser. If no web browser is available or if the web browser fails to open, use device code flow with `az login --use-device-code`.
[
  {
    "cloudName": "AzureCloud",
    "homeTenantId": "a8de0333-xxxx-xxxx-xxxx-8f11260de56e",
    "id": "5b147b69-xxxx-xxxx-xxxx-e1da24ec0994",
    "isDefault": true,
    "managedByTenants": [],
    "name": "Pay-As-You-Go",
    "state": "Enabled",
    "tenantId": "a8de0333-xxxx-xxxx-xxxx-8f11260de56e",
    "user": {
      "name": "xxxx@outlook.com",
      "type": "user"
    }
  }
]

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"
    }
  ]
}