Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

Example: Use the Azure libraries to create and deploy a web app

  • 2025-04-21
Feedback

In this article

This example shows how to use the Azure SDK management libraries in a Python script to create and deploy a web app to Azure App Service, with the app code pulled from a GitHub repository.

The Azure SDK for Python includes management libraries (namespaces beginning withazure-mgmt) that let you automate resource configuration and deployment — similar to what you can do with the Azure portal, Azure CLI, or ARM templates. For examples, seeQuickstart: Deploy a Python (Django or Flask) web app to Azure App Service.

1: Set up your local development environment

If you haven't already, set up an environment where you can run this code. Here are some options:

  • Configure a Python virtual environment usingvenv or your tool of choice. To start using the virtual environment, be sure to activate it. To install python, seeInstall Python.

    #!/bin/bash# Create a virtual environmentpython -m venv .venv# Activate the virtual environmentsource .venv/Scripts/activate # only required for Windows (Git Bash)
  • Use aconda environment. To install Conda, seeInstall Miniconda.

  • Use aDev Container inVisual Studio Code orGitHub Codespaces.

2: Install the required Azure library packages

Create a file namedrequirements.txt with the following contents:

azure-mgmt-resourceazure-mgmt-webazure-identity

In your local development environment, install the requirements using the following code:

pip install -r requirements.txt

3: Fork the sample repository

  1. Visithttps://github.com/Azure-Samples/python-docs-hello-world and fork the repository into your own GitHub account. Using a fork ensures that you have the necessary permissions to deploy the app to Azure.

    Forking the sample repository on GitHub

  2. Next, create an environment variable namedREPO_URL and set it to the URL of your forked repository. This variable is required by the example code in the next section.

export REPO_URL=<url_of_your_fork>export AZURE_SUBSCRIPTION_ID=<subscription_id>

4: Write code to create and deploy a web app

Create a Python file namedprovision_deploy_web_app.py and add the following code. The in-line comments explain what each part of the script does. TheREPO_URL andAZURE_SUBSCRIPTION_ID environment variables should already be set in the previous step.

import random, osfrom azure.identity import AzureCliCredentialfrom azure.mgmt.resource import ResourceManagementClientfrom azure.mgmt.web import WebSiteManagementClient# Acquire a credential object using CLI-based authentication.credential = AzureCliCredential()# Retrieve subscription ID from environment variablesubscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]# Constants we need in multiple places: the resource group name and the region# in which we provision resources. You can change these values however you want.RESOURCE_GROUP_NAME = 'PythonAzureExample-WebApp-rg'LOCATION = "centralus"# Step 1: Provision the resource group.resource_client = ResourceManagementClient(credential, subscription_id)rg_result = resource_client.resource_groups.create_or_update(RESOURCE_GROUP_NAME,    { "location": LOCATION })print(f"Provisioned resource group {rg_result.name}")# For details on the previous code, see Example: Provision a resource group# at https://docs.microsoft.com/azure/developer/python/azure-sdk-example-resource-group#Step 2: Provision the App Service plan, which defines the underlying VM for the web app.# Names for the App Service plan and App Service. We use a random number with the# latter to create a reasonably unique name. If you've already provisioned a# web app and need to re-run the script, set the WEB_APP_NAME environment # variable to that name instead.SERVICE_PLAN_NAME = 'PythonAzureExample-WebApp-plan'WEB_APP_NAME = os.environ.get("WEB_APP_NAME", f"PythonAzureExample-WebApp-{random.randint(1,100000):05}")# Obtain the client objectapp_service_client = WebSiteManagementClient(credential, subscription_id)# Provision the plan; Linux is the defaultpoller = app_service_client.app_service_plans.begin_create_or_update(RESOURCE_GROUP_NAME,    SERVICE_PLAN_NAME,    {        "location": LOCATION,        "reserved": True,        "sku" : {"name" : "B1"}    })plan_result = poller.result()print(f"Provisioned App Service plan {plan_result.name}")# Step 3: With the plan in place, provision the web app itself, which is the process that can host# whatever code we want to deploy to it.poller = app_service_client.web_apps.begin_create_or_update(RESOURCE_GROUP_NAME,    WEB_APP_NAME,    {        "location": LOCATION,        "server_farm_id": plan_result.id,        "site_config": {            "linux_fx_version": "python|3.8"        }    })web_app_result = poller.result()print(f"Provisioned web app {web_app_result.name} at {web_app_result.default_host_name}")# Step 4: deploy code from a GitHub repository. For Python code, App Service on Linux runs# the code inside a container that makes certain assumptions about the structure of the code.# For more information, see How to configure Python apps,# https://docs.microsoft.com/azure/app-service/containers/how-to-configure-python.## The create_or_update_source_control method doesn't provision a web app. It only sets the# source control configuration for the app. In this case we're simply pointing to# a GitHub repository.## You can call this method again to change the repo.REPO_URL = os.environ["REPO_URL"]poller = app_service_client.web_apps.begin_create_or_update_source_control(RESOURCE_GROUP_NAME,    WEB_APP_NAME,     {         "location": "GitHub",        "repo_url": REPO_URL,        "branch": "master",        "is_manual_integration": True    })sc_result = poller.result()print(f"Set source control on web app to {sc_result.branch} branch of {sc_result.repo_url}")# Step 5: Deploy the code using the repository and branch configured in the previous step.## If you push subsequent code changes to the repo and branch, you must call this method again# or use another Azure tool like the Azure CLI or Azure portal to redeploy. # Note: By default, the method returns None.app_service_client.web_apps.sync_repository(RESOURCE_GROUP_NAME, WEB_APP_NAME)print(f"Deploy code")

This code uses CLI-based authentication (usingAzureCliCredential) because it demonstrates actions that you might otherwise do with the Azure CLI directly. In both cases, you're using the same identity for authentication. Depending on your environment, you might need to runaz login first to authenticate.

To use such code in a production script (for example, to automate VM management), useDefaultAzureCredential (recommended) with a service principal based method as described inHow to authenticate Python apps with Azure services.

Reference links for classes used in the code

5: Run the script

python provision_deploy_web_app.py

6: Verify the web app deployment

To view the deployed website, run the following command:

az webapp browse --name <PythonAzureExample-WebApp-12345> --resource-group PythonAzureExample-WebApp-rg

Replace the web app name (--name) with the value generated by the script.You don’t need to change the resource group name (--resource-group) unless you changed it in the script. When you open the site, you should see “Hello, World!” in your browser.

Tip

If you don't see the expected output, wait a few minutes and try again.

If you're still not seeing the expected output:

  1. Go to theAzure portal.
  2. Navigate toResource groups, and locate the resource group you created.
  3. Select the resource group to view its resources. Make sure it includes both an App Service Plan and an App Service.
  4. Select theApp Service, and then go toDeployment Center.
  5. Open thelogs tab to check the deployment logs for any errors or status updates.

7: Redeploy the web app code (optional)

The script provisions all the necessary resources to host your web app and configures the deployment source to use your forked repository using manual integration. With manual integration, you need to manually trigger the web app to pull updates from the specified repository and branch.

The script uses theWebSiteManagementClient.web_apps.sync_repository method to trigger the web app to pull code from your repository. If you make further changes to your code, you can redeploy by calling this API again, or by using other Azure tools such as the Azure CLI or the Azure portal.

You can redeploy your code using the Azure CLI by running theaz webapp deployment source sync command:

az webapp deployment source sync --name <PythonAzureExample-WebApp-12345> --resource-group PythonAzureExample-WebApp-rg

You don’t need to change the resource group name (--resource-group) unless you changed it in the script.

To deploy your code from Azure portal:

  1. Go to theAzure portal.
  2. Navigate toResource groups, and locate the resource group you created.
  3. Select the resource group name to view its resources. Make sure it includes both an App Service Plan and an App Service.
  4. Select theApp Service, and then go toDeployment Center.
  5. On the top menu, selectSync to trigger the deployment of your code.

8: Clean up resources

az group delete --name PythonAzureExample-WebApp-rg --no-wait

You do not need to change resource group name (--resource-group option) unless you changed it in the script.

If you no longer need the resource group created in this example, you can delete it by running theaz group delete command. While resource groups don’t incur ongoing charges, it’s a good practice to clean up any unused resources. Use the--no-wait argument to immediately return control to the command line without waiting for the deletion to complete.

You can also delete a resource group programmatically using theResourceManagementClient.resource_groups.begin_delete method.

See also


Feedback

Was this page helpful?

YesNo

In this article