Azure python web app

Azure python web app DEFAULT

Tutorial: Deploy Python apps to Azure App Service on Linux from Visual Studio Code

  • 2 minutes to read

This article walks you through using Visual Studio Code to deploy a Python application to Azure App Service on Linux using the Azure App Service extension.

If you encounter issues with any of the steps in this tutorial, we'd love to hear the details. Use the Having issues? Let us know. link at the end of each article to submit feedback.

For a demonstration video, see Build WebApps with VS Code and Azure App Service (youtube.com) from virtual PyCon 2020.

Configure your environment

Sign in to Azure

Once you've installed the Azure extension, sign into your Azure account:

  1. Navigate to the Azure explorer

  2. Select Sign in to Azure and follow the prompts. (If you have multiple Azure extensions installed, select the one for the area in which you're working, such as App Service, Functions, etc.)

    Sign in to Azure through VS Code

  3. After signing in, verify that Azure: Signed In" appears in the Status Bar and your subscription(s) appears in the Azure explorer:

    Visual Studio Code status bar showing Azure account

    Visual Studio Code Azure App Service explorer showing subscriptions

Note

If you see the error "Cannot find subscription with name [subscription ID]", this may be because you are behind a proxy and unable to reach the Azure API. Configure and environment variables with your proxy information in your terminal:

Having issues? Let us know.

Sours: https://docs.microsoft.com/en-us/azure/developer/python/tutorial-deploy-app-service-on-linux-01

2: Prepare your app for deployment to Azure App Service

  • 2 minutes to read

Previous step: configure your environment

In this article, you prepare an app to deploy to the Azure App Service for this tutorial. You can use an existing app or create or download an app.

If you already have an app

If you already have an app that you'd like to work with, make sure you have a requirements.txt file in your project root that lists your dependencies, including frameworks like Flask or Django. You can use any framework of your choosing.

If you don't already have an app

If you don't already have an app, use one of the options below. Be sure to verify that the app runs locally.

The remainder of this tutorial uses the code shown in Option 3.

Option 1: Use the VS Code Flask tutorial sample

Download or clone https://github.com/Microsoft/python-sample-vscode-flask-tutorial, which is the result of following the Flask Tutorial. Note that the app code is in the hello_app folder, specifically. Review the sample's readme.md file for instructions on running the app locally.

Option 2: Use the VS Code Django tutorial sample

Download or clone https://github.com/Microsoft/python-sample-vscode-django-tutorial, which is the result of following the Django Tutorial.

Ideally, Django apps deployed to the cloud also use a cloud-based database, such as PostgreSQL for Azure. For more information, see Tutorial: Deploy a Django web app with PostgreSQL using the Azure portal.

If your Django app uses a local SQLite database like this sample, it's easiest for this tutorial to include a pre-initialized and pre-populated copy of the db.sqlite3 file in your repository. Otherwise, you need to configure a post-build command to run Django's command in the container to which the app is deployed. For more information, see App Service configuration - Customize build automation.

Option 3: Create a minimal Flask app

This section describes the minimal Flask app used in this walkthrough. The code is available on GitHub - python-docs-flask-minimal.

  1. Create a new folder, open it in VS Code, and add a file named hello.py with the contents below. The app object is purposely named to demonstrate how the names are used in the startup command for the App Service, as you learn later.

  2. In the same folder, create a file named requirements.txt with the following contents:

  3. Open a terminal using the menu command Terminal > New Terminal.

  4. In the terminal, navigate to the folder containing hello.py. All the remaining terminal commands are run in this folder.

  5. Create and activate a virtual environment named :

  6. When VS Code prompts you to activate the newly-created environment, answer Yes.

  7. Install the app's dependencies:

  8. Set a FLASK_APP environment variable tells Flask where to find the app object:

  9. Run the app:

  10. Open the app in a browser using the URL . You should see the message "Hello Flask, on Azure App Service for Linux."

  11. Stop the Flask server by pressing Ctrl+C in the terminal.

Having issues? Let us know.

Sours: https://docs.microsoft.com/en-us/azure/developer/python/tutorial-deploy-app-service-on-linux-02
  1. Espn dynasty rankings
  2. Black ops 4
  3. Soul runes osrs

5: Deploy your Python web app to Azure App Service on Linux

  • 2 minutes to read

Previous step: configure a custom startup file

Use this procedure to deploy your Python app to an Azure App Service.

  1. In Visual Studio Code, open the Azure: App Service explorer and select the blue up arrow:

    Deploy your web app to App Service in App Service explorer

    Alternately, you can right-click the App Service name and select the Deploy to Web App command.

  2. In the prompts that follow, provide the following details:

    • For "Select the folder to deploy," select your current app folder.
    • For "Select Web App," choose the App Service you created in the previous step.
    • If prompted to update your build configuration to run build commands, answer Yes.
    • If prompted about overwriting the existing deployment, answer Deploy.
    • If prompted to "always deploy the workspace", answer Yes.
  3. While the deployment process is underway, you can view progress in the VS Code Output window.

    Deployment progress in the VS Code output window

  4. When deployment is complete after a few minutes (depending on how many dependencies need to be installed), the message below appears. Select the Browse Website button to view the running site.

    Deployment complete with Browse Website button

    The app running successfully on App Service

  5. If you still see the default app, wait a minute or two for the container to restart after the deployment and try again. If you're using a custom startup command and have verified its correctness, then continue to step 6 to check the logs.

  6. To verify that your files are deployed, expand the App Service in the Azure: App Service explorer, then expand Files:

    Checking deployment files through the App Service explorer

    In case you're wondering, the files .deployment, antenv.tar.gz, and oryx-manifest.toml are used by the App Service build system. The hostingstart.html is the default app page.

Having issues? Let us know.

Feedback

View all page feedback

Sours: https://docs.microsoft.com/en-us/azure/developer/python/tutorial-deploy-app-service-on-linux-05

Use CI/CD to deploy a Python web app to Azure App Service on Linux

Azure Pipelines

In this article, you use Azure Pipelines continuous integration and continuous delivery (CI/CD) to deploy a Python web app to Azure App Service on Linux. You begin by running app code from a GitHub repository locally. You then provision a target App Service through the Azure portal. Finally, you create an Azure Pipelines CI/CD pipeline that automatically builds the code and deploys it to the App Service whenever there's a commit to the repository.

Create a repository for your app code

If you already have a Python web app to use, make sure it's committed to a GitHub repository.

Note

If your app uses Django and a SQLite database, it won't work for this walkthrough. For more information, see considerations for Django later in this article. If your Django app uses a separate database, you can use it with this walkthrough.

If you need an app to work with, you can fork and clone the repository at https://github.com/Microsoft/python-sample-vscode-flask-tutorial. The code is from the tutorial Flask in Visual Studio Code.

To test the example app locally, from the folder containing the code, run the following appropriate commands for your operating system:

Open a browser and navigate to http://localhost:5000 to view the app. When you're finished, close the browser, and stop the Flask server with Ctrl+C.

Provision the target Azure App Service

The quickest way to create an App Service instance is to use the Azure command-line interface (CLI) through the interactive Azure Cloud Shell. In the following steps, you use az webapp up to both provision the App Service and perform the first deployment of your app.

  1. Sign in to the Azure portal at https://portal.azure.com.

  2. Open the Azure CLI by selecting the Cloud Shell button on the portal's toolbar:

    Azure Cloud Shell button on the Azure portal toolbar

  3. The Cloud Shell appears along the bottom of the browser. Select Bash from the dropdown:

    Azure Cloud Shell appearance

  4. In the Cloud Shell, clone your repository using . For the example app, use:

    Replace with the name of the GitHub account you used to fork the repository.

    Tip

    To paste into the Cloud Shell, use Ctrl+Shift+V, or right-click and select Paste from the context menu.

    Note

    The Cloud Shell is backed by an Azure Storage account in a resource group called cloud-shell-storage-<your-region>. That storage account contains an image of the Cloud Shell's file system, which stores the cloned repository. There is a small cost for this storage. You can delete the storage account at the end of this article, along with other resources you create.

  5. In the Cloud Shell, change directories into the repository folder that has your Python app, so the command will recognize the app as Python.

  6. In the Cloud Shell, use to create an App Service and initially deploy your app.

    Change to a name for your app service that's unique across Azure. Typically, you use a personal or company name along with an app identifier, such as . The app URL becomes <your-appservice>.azurewebsites.net.

    When the command completes, it shows JSON output in the Cloud Shell.

    Tip

    If you encounter a "Permission denied" error with a .zip file, you may have tried to run the command from a folder that doesn't contain a Python app. The command then tries to create a Windows app service plan, and fails.

  7. If your app uses a custom startup command, set the az webapp config property. For example, the python-sample-vscode-flask-tutorial app contains a file named startup.txt that contains its specific startup command, so you set the property to .

    1. From the first line of output from the previous command, copy the name of your resource group, which is similar to <your-name>_rg_Linux_<your-region>.

    2. Enter the following command, using your resource group name, your app service name (), and your startup file or command ().

      Again, when the command completes, it shows JSON output in the Cloud Shell.

  8. To see the running app, open a browser and go to http://<your-appservice>.azurewebsites.net. If you see a generic page, wait a few seconds for the App Service to start, and refresh the page.

Create an Azure DevOps project and connect to Azure

To deploy to Azure App Service from Azure Pipelines, you need to establish a service connection between the two services.

  1. In a browser, go to dev.azure.com. If you don't yet have an account on Azure DevOps, select Start free and get a free account. If you have an account already, select Sign in to Azure DevOps.

    Important

    To simplify the service connection, use the same email address for Azure DevOps as you use for Azure.

  2. Once you sign in, the browser displays your Azure DevOps dashboard, at the URL https://dev.azure.com/<your-organization-name>. An Azure DevOps account can belong to one or more organizations, which are listed on the left side of the Azure DevOps dashboard. If more than one organization is listed, select the one you want to use for this walkthrough. By default, Azure DevOps creates a new organization using the email alias you used to sign in.

    A project is a grouping for boards, repositories, pipelines, and other aspects of Azure DevOps. If your organization doesn't have any projects, enter the project name Flask Pipelines under Create a project to get started, and then select Create project.

    First view of Azure DevOps dashboard

    If your organization already has projects, select New project on the organization page. In the Create new project dialog box, enter the project name Flask Pipelines, and select Create.

  3. From the new project page, select Project settings from the left navigation.

    Project settings command on the project dashboard

  4. On the Project Settings page, select Pipelines > Service connections, then select New service connection, and then select Azure Resource Manager from the dropdown.

    Select Azure Resource Manager service connection

  5. In the Add an Azure Resource Manager service connection dialog box:

    1. Give the connection a name. Make note of the name to use later in the pipeline.
    2. For Scope level, select Subscription.
    3. Select the subscription for your App Service from the Subscription drop-down list.
    4. Under Resource Group, select your resource group from the dropdown.
    5. Make sure the option Allow all pipelines to use this connection is selected, and then select OK.

    New service connection dialog box

    The new connection appears in the Service connections list, and is ready for Azure Pipelines to use from the project.

Create a Python-specific pipeline to deploy to App Service

  1. From your project page left navigation, select Pipelines.

    Selecting Pipelines on the project dashboard

  2. Select Create Pipeline:

    New pipeline button on the pipelines list.

  3. On the Where is your code screen, select GitHub. You may be prompted to sign into GitHub.

    Where is your code prompt

  4. On the Select a repository screen, select the repository that contains your app, such as your fork of the example app.

    Select a repository

  5. You may be prompted to enter your GitHub password again as a confirmation, and then GitHub prompts you to install the Azure Pipelines extension:

    Install Azure Pipelines extension on GitHub

    On this screen, scroll down to the Repository access section, choose whether to install the extension on all repositories or only selected ones, and then select Approve and install:

    Install Azure Pipelines extension on GitHub approval

  6. On the Configure your pipeline screen, select Python to Linux Web App on Azure.

    Your new pipeline appears. When prompted, select the Azure subscription in which you created your Web App.

    • Select the Web App
    • Select Validate and configure

    Azure Pipelines creates an azure-pipelines.yml file that defines your CI/CD pipeline as a series of stages, Jobs, and steps, where each step contains the details for different tasks and scripts. Take a look at the pipeline to see what it does. Make sure all the default inputs are appropriate for your code.

YAML pipeline explained

The YAML file contains the following key elements:

  • The at the top indicates the commits that trigger the pipeline, such as commits to the branch.

  • The that parameterize the YAML template

    Tip

    To avoid hard-coding specific variable values in your YAML file, you can define variables in the pipeline's web interface instead. For more information, see Variables - Secrets.

  • The

    • Build , which builds your project, and a Deploy stage, which deploys it to Azure as a Linux web app.
    • Deploy that also creates an Environment with default name same as the Web App. You can choose to modify the environment name.
  • Each stage has a element that specifies one or more virtual machines (VMs) in which the pipeline runs the . By default, the element contains only a single entry for an Ubuntu VM. You can use a pool to run tests in multiple environments as part of the build, such as using different Python versions for creating a package.

  • The element can contain children like , which runs a specific task as defined in the Azure Pipelines task reference, and , which runs an arbitrary set of commands.

  • The first task under Build stage is UsePythonVersion, which specifies the version of Python to use on the build agent. The suffix indicates the version of the task. The indicates preview version. Then we have script-based task that creates a virtual environment and installs dependencies from file (requirements.txt).

  • Next step creates the .zip file that the steps under deploy stage of the pipeline deploys. To create the .zip file, add an ArchiveFiles task to the end of the YAML file:

    You use in a parameter value to reference variables. The built-in variable contains the location on the build agent where the pipeline cloned the app code. The parameter indicates where to place the .zip file. In this case, the parameter uses the built-in variable .

    Important

    When deploying to Azure App Service, be sure to use . Otherwise, the contents of the .zip file are put in a folder named s, for "sources," which is replicated on the App Service. The App Service on Linux container then can't find the app code.

  • Then we have the task to upload the artifacts.

  • In the Deploy stage, we use the keyword to define a deployment job targeting an environment. By using the template, an environment with same name as the Web app is automatically created if it doesn't already exist. Alternatively you can pre-create the environment and provide the

  • Within the deployment job, first task is UsePythonVersion, which specifies the version of Python to use on the build agent.

  • We then use the AzureWebApp task to deploy the .zip file to the App Service you identified by the and variables at the beginning of the pipeline file. Paste the following code at the end of the file:

    The parameter shown here is specific to the python-vscode-flask-tutorial example code, which defines the app in the startup.py file. By default, Azure App Service looks for the Flask app object in a file named app.py or application.py. If your code doesn't follow this pattern, you need to customize the startup command. Django apps may not need customization at all. For more information, see How to configure Python on Azure App Service - Customize startup command.

    Also, because the python-vscode-flask-tutorial repository contains the same startup command in a file named startup.txt, you could specify that file in the parameter rather than the command, by using .

Run the pipeline

You're now ready to try it out!

  1. Select Save at upper right in the editor, and in the pop-up window, add a commit message and select Save.

  2. Select Run on the pipeline editor, and select Run again in the Run pipeline dialog box. Azure Pipelines queues another pipeline run, acquires an available build agent, and has that build agent run the pipeline.

    The pipeline takes a few minutes to complete, especially the deployment steps. You should see green checkmarks next to each of the steps.

    If there's an error, you can quickly return to the YAML editor by selecting the vertical dots at upper right and selecting Edit pipeline:

    Edit pipeline comment from a build report

  3. From the build page, select the Azure Web App task to display its output. To visit the deployed site, hold down the Ctrl key and select the URL after App Service Application URL.

    If you're using the Flask example, the app should appear as follows:

    View of the Flask example code running on App Service

Important

If your app fails because of a missing dependency, then your requirements.txt file was not processed during deployment. This behavior happens if you created the web app directly on the portal rather than using the command as shown in this article.

The command specifically sets the build action to . If you provisioned the app service through the portal, however, this action is not automatically set.

The following steps set the action:

  1. Open the Azure portal, select your App Service, then select Configuration.
  2. Under the Application Settings tab, select New Application Setting.
  3. In the popup that appears, set Name to , set Value to , and select OK.
  4. Select Save at the top of the Configuration page.
  5. Run the pipeline again. Your dependencies should be installed during deployment.

Run a post-deployment script

A post-deployment script can, for example, define environment variables expected by the app code. Add the script as part of the app code and execute it using startup command.

To avoid hard-coding specific variable values in your YAML file, you can instead define variables in the pipeline's web interface and then refer to the variable name in the script. For more information, see Variables - Secrets.

As noted earlier in this article, you can use Azure Pipelines to deploy Django apps to Azure App Service on Linux, provided that you're using a separate database. You can't use a SQLite database, because App Service locks the db.sqlite3 file, preventing both reads and writes. This behavior doesn't affect an external database.

As described in Configure Python app on App Service - Container startup process, App Service automatically looks for a wsgi.py file within your app code, which typically contains the app object. If you need to customize the startup command in any way, use the parameter in the step of your YAML pipeline file, as described in the previous section.

When using Django, you typically want to migrate the data models using after deploying the app code. You can add with post-deployment script for this purpose:

Run tests on the build agent

As part of your build process, you may want to run tests on your app code. Tests run on the build agent, so you probably need to first install your dependencies into a virtual environment on the build agent computer. After the tests run, delete the virtual environment before you create the .zip file for deployment. The following script elements illustrate this process. Place them before the task in the azure-pipelines.yml file. For more information, see Run cross-platform scripts.

You can also use a task like [email protected] to make test results appear in the pipeline results screen. For more information, see Build Python apps - Run tests.

Provision an App Service with single commands

The az webapp up command used earlier in this article is a convenient method to provision the App Service and initially deploy your app in a single step. If you want more control over the deployment process, you can use single commands to accomplish the same tasks. For example, you might want to use a specific name for the resource group, or create an App Service within an existing App Service Plan.

The following steps perform the equivalent of the command:

  1. Create a resource group.

    A resource group is a collection of related Azure resources. Creating a resource group makes it easy to delete all those resources at once when you no longer need them. In the Cloud Shell, run the following command to create a resource group in your Azure subscription. Set a location for the resource group by specifying the value of . JSON output appears in the Cloud Shell when the command completes successfully.

  2. Create an App Service Plan.

    An App Service runs inside a VM defined by an App Service Plan. Run the following command to create an App Service Plan, substituting your own values for and . The is required for Python deployments. If you want a pricing plan other than the default F1 Free plan, use the argument. The specifies the lower-price compute tier for the VM. You can easily delete the plan later by deleting the resource group.

    Again, you see JSON output in the Cloud Shell when the command completes successfully.

  3. Create an App Service instance in the plan.

    Run the following command to create the App Service instance in the plan, replacing with a name that's unique across Azure. Typically, you use a personal or company name along with an app identifier, such as . The command fails if the name is already in use. By assigning the App Service to the same resource group as the plan, it's easy to clean up all the resources at once.

    Note

    If you want to deploy your code at the same time you create the app service, you can use the and arguments with the command. For more information, see az webapp create.

    Tip

    If you see the error message "The plan (name) doesn't exist", and you're sure that the plan name is correct, check that the resource group specified with the argument is also correct, and the plan you identify is part of that resource group. If you misspell the resource group name, the command doesn't find the plan in that nonexistent resource group, and gives this particular error.

  4. If your app requires a custom startup command, use the command, as described earlier in Provision the target Azure App Service. For example, to customize the App Service with your resource group, app name, and startup command, run:

    The App Service at this point contains only default app code. You can now use Azure Pipelines to deploy your specific app code.

Clean up resources

To avoid incurring ongoing charges for any Azure resources you created in this walkthrough, such as a B1 App Service Plan, delete the resource group that contains the App Service and the App Service Plan. To delete the resource group from the Azure portal, select Resource groups in the left navigation. In the resource group list, select the ... to the right of the resource group you want to delete, select Delete resource group, and follow the prompts.

You can also use az group delete in the Cloud Shell to delete resource groups.

To delete the storage account that maintains the file system for Cloud Shell, which incurs a small monthly charge, delete the resource group that begins with cloud-shell-storage-.

Next steps

Feedback

View all page feedback

Sours: https://docs.microsoft.com/en-us/azure/devops/pipelines/ecosystems/python-webapp

Web azure app python

Configure a Linux Python app for Azure App Service

This article describes how Azure App Service runs Python apps, how you can migrate existing apps to Azure, and how you can customize the behavior of App Service when needed. Python apps must be deployed with all the required pip modules.

The App Service deployment engine automatically activates a virtual environment and runs for you when you deploy a Git repository, or a zip packagewith build automation enabled.

This guide provides key concepts and instructions for Python developers who use a built-in Linux container in App Service. If you've never used Azure App Service, first follow the Python quickstart and Python with PostgreSQL tutorial.

You can use either the Azure portal or the Azure CLI for configuration:

Configure Python version

  • Azure portal: use the General settings tab on the Configuration page as described on Configure general settings for Linux containers.

  • Azure CLI:

    • Show the current Python version with az webapp config show:

      Replace and with the names appropriate for your web app.

    • Set the Python version with az webapp config set

    • Show all Python versions that are supported in Azure App Service with az webapp list-runtimes:

You can run an unsupported version of Python by building your own container image instead. For more information, see use a custom Docker image.

Customize build automation

App Service's build system, called Oryx, performs the following steps when you deploy your app if the app setting is set to :

  1. Run a custom pre-build script if specified by the setting. (The script can itself run other Python and Node.js scripts, pip and npm commands, and Node-based tools like yarn, for example, and .)

  2. Run . The requirements.txt file must be present in the project's root folder. Otherwise, the build process reports the error: "Could not find setup.py or requirements.txt; Not running pip install."

  3. If manage.py is found in the root of the repository (indicating a Django app), run manage.py collectstatic. However, if the setting is , this step is skipped.

  4. Run custom post-build script if specified by the setting. (Again, the script can run other Python and Node.js scripts, pip and npm commands, and Node-based tools.)

By default, the , , and settings are empty.

  • To disable running collectstatic when building Django apps, set the setting to true.

  • To run pre-build commands, set the setting to contain either a command, such as , or a path to a script file relative to your project root, such as . All commands must use relative paths to the project root folder.

  • To run post-build commands, set the setting to contain either a command, such as , or a path to a script file relative to your project root, such as . All commands must use relative paths to the project root folder.

For additional settings that customize build automation, see Oryx configuration.

To access the build and deployment logs, see Access deployment logs.

For more information on how App Service runs and builds Python apps in Linux, see How Oryx detects and builds Python apps.

Note

The and settings are identical to and and are supported for legacy purposes.

A setting named , if it contains or 1, triggers an Oryx build happens during deployment. The setting is true when deploying using git, the Azure CLI command , and Visual Studio Code.

Note

Always use relative paths in all pre- and post-build scripts because the build container in which Oryx runs is different from the runtime container in which the app runs. Never rely on the exact placement of your app project folder within the container (for example, that it's placed under site/wwwroot).

Migrate existing applications to Azure

Existing web applications can be redeployed to Azure as follows:

  1. Source repository: Maintain your source code in a suitable repository like GitHub, which enables you to set up continuous deployment later in this process.

    1. Your requirements.txt file must be at the root of your repository for App Service to automatically install the necessary packages.
  2. Database: If your app depends on a database, provision the necessary resources on Azure as well. See Tutorial: Deploy a Django web app with PostgreSQL - create a database for an example.

  3. App service resources: Create a resource group, App Service Plan, and App Service web app to host your application. You can most easily do this by doing an initial deployment of your code through the Azure CLI command , as shown on Tutorial: Deploy a Django web app with PostgreSQL - deploy the code. Replace the names of the resource group, App Service Plan, and the web app to be more suitable for your application.

  4. Environment variables: If your application requires any environment variables, create equivalent App Service application settings. These App Service settings appear to your code as environment variables, as described on Access environment variables.

  5. App startup: Review the section, Container startup process later in this article to understand how App Service attempts to run your app. App Service uses the Gunicorn web server by default, which must be able to find your app object or wsgi.py folder. If needed, you can Customize the startup command.

  6. Continuous deployment: Set up continuous deployment, as described on Continuous deployment to Azure App Service if using Azure Pipelines or Kudu deployment, or Deploy to App Service using GitHub Actions if using GitHub actions.

  7. Custom actions: To perform actions within the App Service container that hosts your app, such as Django database migrations, you can connect to the container through SSH. For an example of running Django database migrations, see Tutorial: Deploy a Django web app with PostgreSQL - run database migrations.

    • When using continuous deployment, you can perform those actions using post-build commands as described earlier under Customize build automation.

With these steps completed, you should be able to commit changes to your source repository and have those updates automatically deployed to App Service.

Production settings for Django apps

For a production environment like Azure App Service, Django apps should follow Django's Deployment checklist (djangoproject.com).

The following table describes the production settings that are relevant to Azure. These settings are defined in the app's setting.py file.

Django settingInstructions for Azure
Store the value in an App Service setting as described on Access app settings as environment variables. You can alternately store the value as a "secret" in Azure Key Vault.
Create a setting on App Service with the value 0 (false), then load the value as an environment variable. In your development environment, create a environment variable with the value 1 (true).
In production, Django requires that you include app's URL in the array of settings.py. You can retrieve this URL at runtime with the code, . App Service automatically sets the environment variable to the app's URL.
Define settings in App Service for the database connection and load them as environment variables to populate the dictionary. You can alternately store the values (especially the username and password) as Azure Key Vault secrets.

Serve static files for Django apps

If your Django web app includes static front-end files, first follow the instructions on Managing static files in the Django documentation.

For App Service, you then make the following modifications:

  1. Consider using environment variables (for local development) and App Settings (when deploying to the cloud) to dynamically set the Django and variables. For example:

    and can be changed as necessary for your local and cloud environments. For example, if the build process for your static files places them in a folder named , then you can set to to avoid using the default.

  2. If you have a pre-build script that generates static files in a different folder, include that folder in the Django variable so that Django's process finds them. For example, if you run in your front-end folder, and yarn generates a folder containing static files, then include that folder as follows:

    Here, , to build a path to where a build tool like yarn is run. You can again use an environment variable and App Setting as desired.

  3. Add to your requirements.txt file. Whitenoise (whitenoise.evans.io) is a Python package that makes it simple for a production Django app to serve it's own static files. Whitenoise specifically serves those files that are found in the folder specified by the Django variable.

  4. In your settings.py file, add the following line for Whitenoise:

  5. Also modify the and lists to include Whitenoise:

Container characteristics

When deployed to App Service, Python apps run within a Linux Docker container that's defined in the App Service Python GitHub repository. You can find the image configurations inside the version-specific directories.

This container has the following characteristics:

  • Apps are run using the Gunicorn WSGI HTTP Server, using the additional arguments .

    • You can provide configuration settings for Gunicorn through a gunicorn.conf.py file in the project root, as described on Gunicorn configuration overview (docs.gunicorn.org). You can alternately customize the startup command.

    • To protect your web app from accidental or deliberate DDOS attacks, Gunicorn is run behind an Nginx reverse proxy as described on Deploying Gunicorn (docs.gunicorn.org).

  • By default, the base container image includes only the Flask web framework, but the container supports other frameworks that are WSGI-compliant and compatible with Python 3.6+, such as Django.

  • To install additional packages, such as Django, create a requirements.txt file in the root of your project that specifies your direct dependencies. App Service then installs those dependencies automatically when you deploy your project.

    The requirements.txt file must be in the project root for dependencies to be installed. Otherwise, the build process reports the error: "Could not find setup.py or requirements.txt; Not running pip install." If you encounter this error, check the location of your requirements file.

  • App Service automatically defines an environment variable named with the web app's URL, such as . It also defines with the name of your app, such as .

  • npm and Node.js are installed in the container so you can run Node-based build tools, such as yarn.

Container startup process

During startup, the App Service on Linux container runs the following steps:

  1. Use a custom startup command, if provided.
  2. Check for the existence of a Django app, and launch Gunicorn for it if detected.
  3. Check for the existence of a Flask app, and launch Gunicorn for it if detected.
  4. If no other app is found, start a default app that's built into the container.

The following sections provide additional details for each option.

Django app

For Django apps, App Service looks for a file named within your app code, and then runs Gunicorn using the following command:

If you want more specific control over the startup command, use a custom startup command, replace with the name of folder that contains wsgi.py, and add a argument if that module is not in the project root. For example, if your wsgi.py is located under knboard/backend/config from your project root, use the arguments .

To enable production logging, add the and parameters as shown in the examples for custom startup commands.

Flask app

For Flask, App Service looks for a file named application.py or app.py and starts Gunicorn as follows:

If your main app module is contained in a different file, use a different name for the app object, or you want to provide additional arguments to Gunicorn, use a custom startup command.

Default behavior

If the App Service doesn't find a custom command, a Django app, or a Flask app, then it runs a default read-only app, located in the opt/defaultsite folder and shown in the following image.

If you deployed code and still see the default app, see Troubleshooting - App doesn't appear.

Default App Service on Linux web page

Again, if you expect to see a deployed app instead of the default app, see Troubleshooting - App doesn't appear.

Customize startup command

As noted earlier in this article, you can provide configuration settings for Gunicorn through a gunicorn.conf.py file in the project root, as described on Gunicorn configuration overview.

If such configuration is not sufficient, you can control the container's startup behavior by providing either a custom startup command or multiple commands in a startup command file. A startup command file can use whatever name you choose, such as startup.sh, startup.cmd, startup.txt, and so on.

All commands must use relative paths to the project root folder.

To specify a startup command or command file:

  • Azure portal: select the app's Configuration page, then select General settings. In the Startup Command field, place either the full text of your startup command or the name of your startup command file. Then select Save to apply the changes. See Configure general settings for Linux containers.

  • Azure CLI: use the az webapp config set command with the parameter to set the startup command or file:

    Replace with either the full text of your startup command or the name of your startup command file.

App Service ignores any errors that occur when processing a custom startup command or file, then continues its startup process by looking for Django and Flask apps. If you don't see the behavior you expect, check that your startup command or file is error-free and that a startup command file is deployed to App Service along with your app code. You can also check the Diagnostic logs for additional information. Also check the app's Diagnose and solve problems page on the Azure portal.

Example startup commands

  • Added Gunicorn arguments: The following example adds the to a Gunicorn command line for starting a Django app:

    For more information, see Running Gunicorn (docs.gunicorn.org).

  • Enable production logging for Django: Add the and arguments to the command line:

    These logs will appear in the App Service log stream.

    For more information, see Gunicorn logging (docs.gunicorn.org).

  • Custom Flask main module: by default, App Service assumes that a Flask app's main module is application.py or app.py. If your main module uses a different name, then you must customize the startup command. For example, if you have a Flask app whose main module is hello.py and the Flask app object in that file is named , then the command is as follows:

    If your main module is in a subfolder, such as , specify that folder with the argument:

  • Use a non-Gunicorn server: To use a different web server, such as aiohttp, use the appropriate command as the startup command or in the startup command file:

Access app settings as environment variables

App settings are values stored in the cloud specifically for your app as described on Configure app settings. These settings are available to your app code as environment variables and accessed using the standard os.environ pattern.

For example, if you've created app setting called , the following code retrieves that setting's value:

Detect HTTPS session

In App Service, TLS/SSL termination (wikipedia.org) happens at the network load balancers, so all HTTPS requests reach your app as unencrypted HTTP requests. If your app logic needs to check if the user requests are encrypted or not, inspect the header.

Popular web frameworks let you access the information in your standard app pattern. In CodeIgniter, the is_https() checks the value of by default.

Access diagnostic logs

You can access the console logs generated from inside the container.

First, turn on container logging by running the following command:

Replace and with the names appropriate for your web app.

Once container logging is turned on, run the following command to see the log stream:

If you don't see console logs immediately, check again in 30 seconds.

To stop log streaming at any time, type Ctrl+C.

You can also inspect the log files in a browser at .

To access logs through the Azure portal, select Monitoring > Log stream on the left side menu for your app.

Access deployment logs

When you deploy your code, App Service performs the build process described earlier in the section Customize build automation. Because the build runs in its own container, build logs are stored separately from the app's diagnostic logs.

Use the following steps to access the deployment logs:

  1. On the Azure portal for your web app, select Deployment > Deployment Center (Preview) on the left menu.
  2. On the Logs tab, select the Commit ID for the most recent commit.
  3. On the Log details page that appears, select the Show Logs... link that appears next to "Running oryx build...".

Build issues such as incorrect dependencies in requirements.txt and errors in pre- or post-build scripts will appear in these logs. Errors also appear if your requirements file is not exactly named requirements.txt or does not appear in the root folder of your project.

Open SSH session in browser

To make open a direct SSH session with your container, your app should be running.

Paste the following URL into your browser and replace with your app name:

If you're not yet authenticated, you're required to authenticate with your Azure subscription to connect. Once authenticated, you see an in-browser shell, where you can run commands inside your container.

SSH connection

Note

Any changes you make outside the /home directory are stored in the container itself and don't persist beyond an app restart.

To open a remote SSH session from your local machine, see Open SSH session from remote shell.

When you're successfully connected to the SSH session, you should see the message "SSH CONNECTION ESTABLISHED" at the bottom of the window. If you see errors such as "SSH_CONNECTION_CLOSED" or a message that the container is restarting, an error may be preventing the app container from starting. See Troubleshooting for steps to investigate possible issues.

Troubleshooting

In general, the first step in troubleshooting is to use App Service Diagnostics:

  1. On the Azure portal for your web app, select Diagnose and solve problems from the left menu.
  2. Select Availability and performance.
  3. Examine the information in the Application Logs, Container crash, and Container Issues options, where the most common issues will appear.

Next, examine both the deployment logs and the app logs for any error messages. These logs often identify specific issues that can prevent app deployment or app startup. For example, the build can fail if your requirements.txt file has the wrong filename or isn't present in your project root folder.

The following sections provide additional guidance for specific issues.

App doesn't appear

  • You see the default app after deploying your own app code. The default app appears because you either haven't deployed your app code to App Service, or App Service failed to find your app code and ran the default app instead.

    • Restart the App Service, wait 15-20 seconds, and check the app again.

    • Be sure you're using App Service for Linux rather than a Windows-based instance. From the Azure CLI, run the command , replacing and accordingly. You should see as output; otherwise, recreate the App Service and choose Linux.

    • Use SSH to connect directly to the App Service container and verify that your files exist under site/wwwroot. If your files don't exist, use the following steps:

      1. Create an app setting named with the value of 1, redeploy your code, wait a few minutes, then try to access the app again. For more information on creating app settings, see Configure an App Service app in the Azure portal.
      2. Review your deployment process, check the deployment logs, correct any errors, and redeploy the app.
    • If your files exist, then App Service wasn't able to identify your specific startup file. Check that your app is structured as App Service expects for Django or Flask, or use a custom startup command.

  • You see the message "Service Unavailable" in the browser. The browser has timed out waiting for a response from App Service, which indicates that App Service started the Gunicorn server, but the app itself did not start. This condition could indicate that the Gunicorn arguments are incorrect, or that there's an error in the app code.

    • Refresh the browser, especially if you're using the lowest pricing tiers in your App Service Plan. The app may take longer to start up when using free tiers, for example, and becomes responsive after you refresh the browser.

    • Check that your app is structured as App Service expects for Django or Flask, or use a custom startup command.

    • Examine the app log stream for any error messages. The logs will show any errors in the app code.

Could not find setup.py or requirements.txt

  • The log stream shows "Could not find setup.py or requirements.txt; Not running pip install.": The Oryx build process failed to find your requirements.txt file.

    • Connect to the web app's container via SSH and verify that requirements.txt is named correctly and exists directly under site/wwwroot. If it doesn't exist, make site the file exists in your repository and is included in your deployment. If it exists in a separate folder, move it to the root.

ModuleNotFoundError when app starts

If you see an error like , this means that Python could not find one or more of your modules when the application started. This most often occurs if you deploy your virtual environment with your code. Virtual environments are not portable, so a virtual environment should not be deployed with your application code. Instead, let Oryx create a virtual environment and install your packages on the web app by creating an app setting, , and setting it to . This will force Oryx to install your packages whenever you deploy to App Service. For more information, please see this article on virtual environment portability.

Database is locked

When attempting to run database migrations with a Django app, you may see "sqlite3. OperationalError: database is locked." The error indicates that your application is using a SQLite database for which Django is configured by default, rather than using a cloud database such as PostgreSQL for Azure.

Check the variable in the app's settings.py file to ensure that your app is using a cloud database instead of SQLite.

If you're encountering this error with the sample in Tutorial: Deploy a Django web app with PostgreSQL, check that you completed the steps in Configure environment variables to connect the database.

Other issues

  • Passwords don't appear in the SSH session when typed: For security reasons, the SSH session keeps your password hidden as you type. The characters are being recorded, however, so type your password as usual and press Enter when done.

  • Commands in the SSH session appear to be cut off: The editor may not be word-wrapping commands, but they should still run correctly.

  • Static assets don't appear in a Django app: Ensure that you have enabled the whitenoise module

  • You see the message, "Fatal SSL Connection is Required": Check any usernames and passwords used to access resources (such as databases) from within the app.

More resources:

Sours: https://docs.microsoft.com/en-us/azure/app-service/configure-language-python
Deploying Python Flask application to Azure App service

Quickstart: Create a Python app using Azure App Service on Linux

In this quickstart, you deploy a Python web app to App Service on Linux, Azure's highly scalable, self-patching web hosting service. You use the local Azure command-line interface (CLI) on a Mac, Linux, or Windows computer to deploy a sample with either the Flask or Django frameworks. The web app you configure uses a basic App Service tier that incurs a small cost in your Azure subscription.

Set up your initial environment

  1. Have an Azure account with an active subscription. Create an account for free.
  2. Install Python 3.6 or higher.
  3. Install the Azure CLI, with which you run commands in any shell to provision and configure Azure resources.

Open a terminal window and check your Python version is 3.6 or higher:

Check that your Azure CLI version is 2.0.80 or higher:

Then sign in to Azure through the CLI:

This command opens a browser to gather your credentials. When the command finishes, it shows JSON output containing information about your subscriptions.

Once signed in, you can run Azure commands with the Azure CLI to work with resources in your subscription.

Having issues? Let us know.

Clone the sample

Clone the sample repository using the following command and navigate into the sample folder. (Install git if you don't have git already.)

The sample contains framework-specific code that Azure App Service recognizes when starting the app. For more information, see Container startup process.

Having issues? Let us know.

Run the sample

  1. Navigate into in the python-docs-hello-world folder:

  2. Create a virtual environment and install dependencies:

    If you're on a Windows system and see the error "'source' is not recognized as an internal or external command," make sure you're either running in the Git Bash shell, or use the commands shown in the Cmd tab above.

    If you encounter "[Errno 2] No such file or directory: 'requirements.txt'.", make sure you're in the python-docs-hello-world folder.

  3. Run the development server.

    By default, the server assumes that the app's entry module is in app.py, as used in the sample.

    If you use a different module name, set the environment variable to that name.

    If you encounter the error, "Could not locate a Flask application. You did not provide the 'FLASK_APP' environment variable, and a 'wsgi.py' or 'app.py' module was not found in the current directory.", make sure you're in the folder that contains the sample.

  4. Open a web browser and go to the sample app at . The app displays the message Hello, World!.

    Run a sample Python app locally

  5. In your terminal window, press Ctrl+C to exit the development server.

  1. Navigate into the python-docs-hello-django folder:

  2. Create a virtual environment and install dependencies:

    If you're on a Windows system and see the error "'source' is not recognized as an internal or external command," make sure you're either running in the Git Bash shell, or use the commands shown in the Cmd tab above.

    If you encounter "[Errno 2] No such file or directory: 'requirements.txt'.", make sure you're in the python-docs-hello-django folder.

  3. Run the development server.

  4. Open a web browser and go to the sample app at . The app displays the message Hello, World!.

    Run a sample Python app locally

  5. In your terminal window, press Ctrl+C to exit the development server.

Having issues? Let us know.

Deploy the sample

Deploy the code in your local folder (python-docs-hello-world) using the command:

  • If the command isn't recognized, be sure you have the Azure CLI installed as described in Set up your initial environment.
  • If the command isn't recognized, because that your Azure CLI version is 2.0.80 or higher. If not, install the latest version.
  • Replace with a name that's unique across all of Azure (valid characters are , , and ). A good pattern is to use a combination of your company name and an app identifier.
  • The argument creates the web app on the Basic pricing tier, which incurs a small hourly cost. Omit this argument to use a faster premium tier.
  • You can optionally include the argument where is an available Azure region. You can retrieve a list of allowable regions for your Azure account by running the command.
  • If you see the error, "Could not auto-detect the runtime stack of your app," make sure you're running the command in the python-docs-hello-world folder (Flask) or the python-docs-hello-django folder (Django) that contains the requirements.txt file. (See Troubleshooting auto-detect issues with az webapp up (GitHub).)

The command may take a few minutes to complete. While running, it provides messages about creating the resource group, the App Service plan and hosting app, configuring logging, then performing ZIP deployment. It then gives the message, "You can launch the app at http://<app-name>.azurewebsites.net", which is the app's URL on Azure.

Example output of the az webapp up command

Having issues? Refer first to the Troubleshooting guide, otherwise, let us know.

Note

The command does the following actions:

  • Create a default resource group.

  • Create a default App Service plan.

  • Create an app with the specified name.

  • Zip deploy all files from the current working directory, with build automation enabled.

  • Cache the parameters locally in the .azure/config file so that you don't need to specify them again when deploying later with or other Azure CLI commands. The cached values are used automatically by default.

Browse to the app

Browse to the deployed application in your web browser at the URL . It can take a minute or two for the the app to start, so if you see a default app page, wait a minute and refresh the browser.

The Python sample code is running a Linux container in App Service using a built-in image.

Run a sample Python app in Azure

Congratulations! You've deployed your Python app to App Service.

Having issues? Refer first to the Troubleshooting guide, otherwise, let us know.

Redeploy updates

In this section, you make a small code change and then redeploy the code to Azure. The code change includes a statement to generate logging output that you work with in the next section.

Open app.py in an editor and update the function to match the following code.

Open hello/views.py in an editor and update the function to match the following code.

Save your changes, then redeploy the app using the command again:

This command uses values that are cached locally in the .azure/config file, including the app name, resource group, and App Service plan.

Once deployment is complete, switch back to the browser window open to . Refresh the page, which should display the modified message:

Run an updated sample Python app in Azure

Having issues? Refer first to the Troubleshooting guide, otherwise, let us know.

Stream logs

You can access the console logs generated from inside the app and the container in which it runs. Logs include any output generated using statements.

To stream logs, run the az webapp log tail command:

You can also include the parameter with then command to automatically open the log stream on deployment.

Refresh the app in the browser to generate console logs, which include messages describing HTTP requests to the app. If no output appears immediately, try again in 30 seconds.

You can also inspect the log files from the browser at .

To stop log streaming at any time, press Ctrl+C in the terminal.

Having issues? Refer first to the Troubleshooting guide, otherwise, let us know.

Manage the Azure app

Go to the Azure portal to manage the app you created. Search for and select App Services.

Navigate to App Services in the Azure portal

Select the name of your Azure app.

Navigate to your Python app in App Services in the Azure portal

Selecting the app opens its Overview page, where you can perform basic management tasks like browse, stop, start, restart, and delete.

Manage your Python app in the Overview page in the Azure portal

The App Service menu provides different pages for configuring your app.

Having issues? Refer first to the Troubleshooting guide, otherwise, let us know.

Clean up resources

In the preceding steps, you created Azure resources in a resource group. The resource group has a name like "appsvc_rg_Linux_CentralUS" depending on your location. If you keep the web app running, you will incur some ongoing costs (see App Service pricing).

If you don't expect to need these resources in the future, delete the resource group by running the following command:

The command uses the resource group name cached in the .azure/config file.

The argument allows the command to return before the operation is complete.

Having issues? Let us know.

Next steps

Sours: https://docs.microsoft.com/en-us/azure/app-service/quickstart-python

You will also be interested:

Create a Web App and deploy it to Azure

Here we will look how we can create a webapp and deploy it to azure.

We need to do the following:

  • download a sample app
  • run the app locally just to ensure it works
  • configure a deployment user, this deployment user is required for and to a web app
  • create a resource group, this is needed if you need a new logical grouping for what we are about to do
  • create a service plan, we will need this to specify how we will be charged for this and what kind of container we will create
  • create the web app, we will need to run a command to create the actual web app and we will need to state here how we deploy it, we will choose git deploy, more on that below
  • visit the generated web site
  • push to the site, using git deploy
  • manage updates, let's learn how we can update our app and push changes

Download and run sample app

Let's get a sample app first:

if we want to run it locally we type:

This should run the application and host it on

Configure a deployment user

This deployment user will need to have a name that is globally unique

To create our deployment user we need to use the command . Then we need to provide a user after the flag and a password after the flag. The password needs to be at least 8 characters long and contain two of the following three elements: letters, numbers, symbols. The full command we nee to run looks therefore like this:

Let's call the user and give it the password . Thereby our command now looks like this:

This should give you an output looking like this:

create a resource group

If you want a new group, type the following:

This will create a group called

create a service plan

The full command for creating a service plan is this:

The value means we are on a basic service plan and means we will get a linux container

We are using the command above and the sub command to create our service plan. This should also give us a JSON response back with key having value

create the web app

Below is the command for creating the web app. We will need to state the also the the of the app, the version of Python and lastly how we will deploy it, which is :

A comment on the above command is that the will need to be globally unique. So let's try the followibf

In the JSON response to this we are looking for two interesting pieces of information:

  • the name of the git repository, look for key called .
  • the public url, look for a key called

What you've accomplished is an empty web app with git deployment enabled. What does that mean though?

visit the web site

to visit the web site go to

This should show you a default site looking like this:

That seems to work, great !

push the code to the web site

ok last step is to set up the git deploy properly and push the code and see the site being updated with your code. We set up the git deploy by typing the following:

Now it's time to push the code so we simply type:

This will prompt you for your deployment users password. Just type it and your deployment are under way.

This will take a little while so go and have a warm beverage :) It should finally dump out a long list of logs ending with:

That means that your app deployed successfully and you can now go back to your app url and you should see this:

Manage changes and redeploy

This is quite easy now that we have git deploy activated. Let's do the following:

  • make some changes to a file
  • commit the changes
  • push the code to our remote branch

make some changes

Let's go into and change it to this:

commit changes

We commit as we would normally do in git with:

push the code to our remote

Let's now push to our remote branch by typing:

This should generate a bunch of log entries and end with . Let's verify that that is the case by going to our app url:

That's looking good :)

Summary

We have learned how to deploy an app to azure and even update it and redeploy. That's a lot in one article. Let's have a brief look at the steps we took to accomplish this:

  • downloaded a sample app. Obviously in a real scenario we would have created our own code and not as in this case use a sample app with Python and Flask

  • created a deployment user that we would need for our deployment. That also made us choose deployment type which we chose to be .

  • created a resource group. This created a logical group for our app. This is a group we can reuse for other things like adding a database our something else the app might need to exist.

  • created a service plan. This meant that we decided how we want to be billed for this as well as what kind of container we wanted the app to run in.

  • created the web site itself, or rather a placeholder where our app could live.

  • pushing our code to the newly created web site using git. We also showed how we could use git to update our web site and redeploy.

This taught us the basics of starting with web app development with azure and prepared us for future adventures. Stay tuned for more fun in the cloud :)

Sours: https://chrisnoring.gitbooks.io/road-to-azure/content/deployment/python-web-app-deploy.html


28 29 30 31 32