Skip to content

Commit

Permalink
merge, synchronize AZD template/steps, add redis to dev container
Browse files Browse the repository at this point in the history
  • Loading branch information
cephalin committed Nov 28, 2023
2 parents aeb2104 + 88e1d10 commit 2a54cc3
Show file tree
Hide file tree
Showing 18 changed files with 264 additions and 132 deletions.
9 changes: 9 additions & 0 deletions .devcontainer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# .devcontainer directory

This `.devcontainer` directory contains the configuration for a [dev container](https://docs.github.com/codespaces/setting-up-your-project-for-codespaces/adding-a-dev-container-configuration/introduction-to-dev-containers) and isn't used by the sample application.

The dev container configuration lets you open the repository in a [GitHub codespace](https://docs.github.com/codespaces/overview) or a dev container in Visual Studio Code. For your convenience, the dev container is configured with the following:

- Python
- PostgreSQL
- [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/overview) (so you can run `azd` commands directly).
8 changes: 4 additions & 4 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{
"name": "msdocs-django-postgresql-sample-app",
"name": "msdocs-flask-postgresql-sample-app",
"dockerComposeFile": "docker-compose.yml",
"service": "app",
"workspaceFolder": "/workspace",
"features": {
"ghcr.io/azure/azure-dev/azd:latest": {}
},
},
"customizations": {
"vscode": {
// Add the IDs of extensions you want installed when the container is created.
Expand Down Expand Up @@ -51,9 +51,9 @@
}
}
},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// Use 'forwardPorts' to make a list of ports inside the container available locally. 5000 is for Flask, and 5432 is for PostgreSQL.
"forwardPorts": [
8000, 5432
5000, 5432
],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "",
Expand Down
6 changes: 5 additions & 1 deletion .devcontainer/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,16 @@ services:
volumes:
- postgres-data:/var/lib/postgresql/data
environment:
POSTGRES_USER: app_user
POSTGRES_DB: app
POSTGRES_USER: app_user
POSTGRES_PASSWORD: app_password

# Add "forwardPorts": ["5432"] to **devcontainer.json** to forward PostgreSQL locally.
# (Adding the "ports" property to this file will not forward from a Codespace.)

redis:
image: redis
restart: unless-stopped

volumes:
postgres-data:
5 changes: 3 additions & 2 deletions .env.sample
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
DBNAME=<database name>
DBNAME=<database-name>
DBHOST=<database-hostname>
DBUSER=<db-user-name>
DBPASS=<db-password>
SECRET_KEY=<secret key>
CACHELOCATION=<redis-cache-url>
SECRET_KEY=<secret-key>
3 changes: 2 additions & 1 deletion .env.sample.devcontainer
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ DBNAME=app
DBHOST=localhost
DBUSER=app_user
DBPASS=app_password
SECRET_KEY=secret_key
CACHELOCATION=redis://redis:6379/0
SECRET_KEY=secret_key
61 changes: 0 additions & 61 deletions .github/workflows/azure-dev.yaml

This file was deleted.

3 changes: 3 additions & 0 deletions .vscode/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# .vscode directory

This `.vscode` directory contains configuration that lets you launch and debug in Visual Studio Code and isn't used by the sample application.
72 changes: 22 additions & 50 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,70 +2,61 @@

This is a Python web app using the Django framework and the Azure Database for PostgreSQL relational database service. The Django app is hosted in a fully managed Azure App Service. This app is designed to be be run locally and then deployed to Azure. You can either deploy this project by following the tutorial [*Deploy a Python (Django or Flask) web app with PostgreSQL in Azure*](https://docs.microsoft.com/azure/app-service/tutorial-python-postgresql-app) or by using the [Azure Developer CLI (azd)](https://learn.microsoft.com/azure/developer/azure-developer-cli/overview) according to the instructions below.

Additionally, the sample application demonstrates Azure Redis Cache access by caching the restaurant details page for 60 seconds. You can add the Azure Redis Cache integration in the [secure-by-default web app + database creation wizard](https://portal.azure.com/?feature.customportal=false#create/Microsoft.AppServiceWebAppDatabaseV3), and it's also included in the [AZD template](https://github.com/Azure-Samples/python-app-service-postgresql-infra).

## Requirements

The [requirements.txt](./requirements.txt) has the following packages:
The [requirements.txt](./requirements.txt) has the following packages, all used by a typical data-driven Django application:

| Package | Description |
| ------- | ----------- |
| [Django](https://pypi.org/project/Django/) | Web application framework. |
| [pyscopg2-binary](https://pypi.org/project/psycopg-binary/) | PostgreSQL database adapter for Python. |
| [python-dotenv](https://pypi.org/project/python-dotenv/) | Read key-value pairs from .env file and set them as environment variables. In this sample app, those variables describe how to connect to the database locally. <br><br> This package is used in the [manage.py](./manage.py) file to load environment variables. |
| [whitenoise](https://pypi.org/project/whitenoise/) | Static file serving for WSGI applications, used in the deployed app. <br><br> This package is used in the [azureproject/production.py](./azureproject/production.py) file, which configures production settings. |
| [django-redis](https://pypi.org/project/django-redis/) | Redis cache backend for Django. |

## Using this project with the Azure Developer CLI (azd)
## Run the sample

This project is designed to work well with the [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/overview),
which makes it easier to develop apps locally, deploy them to Azure, and monitor them.
This project has a [dev container configuration](.devcontainer/), which makes it easier to develop apps locally, deploy them to Azure, and monitor them. The easiest way to run this sample application is inside a GitHub codespace. Follow these steps:

### Local development
1. Fork this repository to your account. For instructions, see [Fork a repo](https://docs.github.com/get-started/quickstart/fork-a-repo).

This project has Dev Container support, so you can open it in Github Codespaces or local VS Code with the Dev Containers extension. If you're unable to open the Dev Container,
then it's best to first [create a Python virtual environment](https://docs.python.org/3/tutorial/venv.html#creating-virtual-environments) and activate that.
1. From the repository root of your fork, select **Code** > **Codespaces** > **+**.

1. Install the requirements:
1. In the codespace terminal, run the following commands:

```shell
# Install requirements
python3 -m pip install -r requirements.txt
```

2. Create an `.env` file using `.env.sample` as a guide. Set the value of `DBNAME` to the name of an existing database in your local PostgreSQL instance. Set the values of `DBHOST`, `DBUSER`, and `DBPASS` as appropriate for your local PostgreSQL instance. If you're in the Dev Container, copy the values from `.env.sample.devcontainer`.

3. In the `.env` file, fill in a secret value for `SECRET_KEY`. You can use this command to generate an appropriate value:

```shell
python -c 'import secrets; print(secrets.token_hex())'
```

4. Run the migrations: (or use VS Code "Run" button and select "Migrate")

```shell
# Create .env with environment variables
cp .env.sample.devcontainer .env
# Run database migrations
python3 manage.py migrate
```

5. Run the local server: (or use VS Code "Run" button and select "Run server")
```shell
# Start the development server
python3 manage.py runserver
```

### Deployment
1. When you see the message `Your application running on port 8000 is available.`, click **Open in Browser**.

This repo is set up for deployment on Azure App Service (w/PostGreSQL server) using the configuration files in the `infra` folder.
### Quick deploy

🎥 Watch a deployment of the code in [this screencast](https://www.youtube.com/watch?v=JDlZ4TgPKYc).
This project is designed to work well with the [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/overview), which makes it easier to develop apps locally, deploy them to Azure, and monitor them.

🎥 Watch a deployment of the code in [this screencast](https://www
.youtube.com/watch?v=JDlZ4TgPKYc).

Steps for deployment:

1. Sign up for a [free Azure account](https://azure.microsoft.com/free/)
2. Install the [Azure Dev CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd). (If you opened this repository in a Dev Container, that part will be done for you.)
2. Install the [Azure Dev CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd). (If you opened this repository in a Dev Container, it's already installed for you.)
3. Initialize a new `azd` environment:
```shell
azd init
```
It will prompt you to provide a name (like "django-app") that will later be used in the name of the deployed resources.
It will prompt you to provide a name (like "django-app"), which will later be used in the name of the deployed resources.
4. Provision and deploy all the resources:
Expand All @@ -91,25 +82,6 @@ Steps for deployment:
azd deploy
```
### CI/CD pipeline
This project includes a Github workflow for deploying the resources to Azure
on every push. That workflow requires several Azure-related authentication secrets to be stored as Github action secrets. To set that up, run:
```shell
azd pipeline config
```
### Monitoring
The deployed resources include a Log Analytics workspace with an Application Insights dashboard to measure metrics like server response time.
To open that dashboard, just run:
```shell
azd monitor --overview
```
## Getting help
If you're working with this project and running into issues, please post in [Issues](/issues).
28 changes: 26 additions & 2 deletions azure.yaml
Original file line number Diff line number Diff line change
@@ -1,10 +1,34 @@
# yaml-language-server: $schema=https://raw.githubusercontent.com/Azure/azure-dev/main/schemas/v1.0/azure.yaml.json
# azure.yaml is an azd configuration file and isn't used by the sample application.

name: django-postgresql-sample-app
name: python-app-service-postgresql-redis-infra
metadata:
template: django-postgresql-sample-app@0.0.1-beta
template: python-app-service-postgresql-redis-infra@0.0.1-beta
services:
web:
project: .
language: py
host: appservice
hooks:
postprovision:
posix:
shell: sh
run: echo $'\n\nApp Service app has the following settings:\n' && echo "$WEB_APP_SETTINGS" | jq -r '.[]' | sed 's/\(.*\)/\t- \1/' && echo -e $"\nSee the settings in the portal:\033[1;36m $WEB_APP_CONFIG"
interactive: true
continueOnError: true
windows:
shell: pwsh
run: Write-Host "`n`nApp Service app has the following settings:`n" $WEB_APP_SETTINGS | ConvertFrom-Json | ForEach-Object { Write-Host "\t- $_" }
interactive: true
continueOnError: true
postdeploy:
posix:
shell: sh
run: echo -e $"\n\nOpen SSH session to App Service container at:\033[1;36m $WEB_APP_SSH\033[0m" && echo -e $"Stream App Service logs at:\033[1;36m $WEB_APP_LOG_STREAM"
interactive: true
continueOnError: true
windows:
shell: pwsh
run: Write-Host "`n`nOpen SSH session to App Service container at:`n" $WEB_APP_SSH; Write-Host "Stream App Service logs at:`n" $WEB_APP_LOG_STREAM
interactive: true
continueOnError: true
12 changes: 12 additions & 0 deletions azureproject/production.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Expand All @@ -38,3 +39,14 @@
'PASSWORD': conn_str_params['password'],
}
}

CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": os.environ.get('AZURE_REDIS_CONNECTIONSTRING'),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor",
},
}
}
10 changes: 10 additions & 0 deletions azureproject/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
ROOT_URLCONF = 'azureproject.urls'

TEMPLATES = [
Expand Down Expand Up @@ -119,6 +120,15 @@
},
]

CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": os.environ.get('CACHELOCATION'),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
}
}

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
Expand Down
3 changes: 3 additions & 0 deletions infra/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# infra directory

This `infra` directory contains azd files used for `azd provision` and isn't used by the sample application.
4 changes: 4 additions & 0 deletions infra/main.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,7 @@ module resources 'resources.bicep' = {
output AZURE_LOCATION string = location
output APPLICATIONINSIGHTS_CONNECTION_STRING string = resources.outputs.APPLICATIONINSIGHTS_CONNECTION_STRING
output WEB_URI string = resources.outputs.WEB_URI
output WEB_APP_SETTINGS array = resources.outputs.WEB_APP_SETTINGS
output WEB_APP_LOG_STREAM string = resources.outputs.WEB_APP_LOG_STREAM
output WEB_APP_SSH string = resources.outputs.WEB_APP_SSH
output WEB_APP_CONFIG string = resources.outputs.WEB_APP_CONFIG
Loading

0 comments on commit 2a54cc3

Please sign in to comment.