Skip to content

Commit 4582661

Browse files
committed
Match the other samples
1 parent 643c3f1 commit 4582661

9 files changed

Lines changed: 74 additions & 96 deletions

File tree

‎.devcontainer/Dockerfile‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
FROM mcr.microsoft.com/devcontainers/python:3.12-bullseye
2+
3+
RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
4+
&& apt-get -y install --no-install-recommends postgresql-client \
5+
&& apt-get clean -y && rm -rf /var/lib/apt/lists/*

‎.devcontainer/Dockerfile_dev‎

Lines changed: 0 additions & 11 deletions
This file was deleted.

‎.devcontainer/devcontainer.json‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
// Update the 'dockerComposeFile' list if you have more compose files or use different names.
77
// The .devcontainer/docker-compose.yml file contains any overrides you need/want to make.
8-
"dockerComposeFile": "docker-compose_dev.yml",
8+
"dockerComposeFile": "docker-compose.yml",
99
// The 'service' property is the name of the service for the container that VS Code should
1010
// use. Update this value and .devcontainer/docker-compose.yml to the real service name.
1111
"service": "app",
@@ -16,6 +16,9 @@
1616
"8000": {"label": "frontend web port", "onAutoForward": "notify"},
1717
"5432": {"label": "PostgreSQL Port", "onAutoForward": "silent"}
1818
},
19+
"features": {
20+
"ghcr.io/azure/azure-dev/azd:latest": {}
21+
},
1922
"customizations": {
2023
"vscode": {
2124
"extensions": [
@@ -42,10 +45,6 @@
4245
}
4346
}
4447
}
45-
},
46-
"features": {
47-
"ghcr.io/azure/azure-dev/azd:latest": {}
48-
},
49-
"postCreateCommand": "pip install -e src && python3 src/fastapi_app/seed_data.py"
48+
}
5049
}
5150

Original file line numberDiff line numberDiff line change
@@ -1,42 +1,37 @@
1-
version: '3'
21
services:
3-
db:
4-
image: postgres:14
5-
6-
environment:
7-
POSTGRES_USER: postgres
8-
POSTGRES_DB: relecloud
9-
POSTGRES_PASSWORD: postgres
10-
11-
restart: unless-stopped
12-
13-
volumes:
14-
- postgres-data:/var/lib/postgresql/data
15-
16-
healthcheck:
17-
test: ["CMD-SHELL", "pg_isready -U postgres -d relecloud"]
18-
interval: 5s
19-
timeout: 5s
20-
retries: 5
212

223
app:
234
build:
245
context: ..
25-
dockerfile: ./.devcontainer/Dockerfile_dev
6+
dockerfile: ./.devcontainer/Dockerfile
267
depends_on:
278
db:
289
condition: service_healthy
29-
network_mode: service:db
30-
environment:
31-
POSTGRES_USERNAME: postgres
32-
POSTGRES_DATABASE: relecloud
33-
POSTGRES_HOST: db
34-
POSTGRES_PASSWORD: postgres
3510

11+
volumes:
12+
- ..:/workspace:cached
13+
14+
# Overrides default command so things don't shut down after the process ends.
3615
command: sleep infinity
3716

17+
# Runs app on the same network as the database container, allows "forwardPorts" in devcontainer.json function.
18+
network_mode: service:db
19+
20+
db:
21+
image: postgres:14
22+
restart: unless-stopped
3823
volumes:
39-
- ..:/workspace:cached
24+
- postgres-data:/var/lib/postgresql/data
25+
environment:
26+
POSTGRES_DB: app
27+
POSTGRES_USER: app_user
28+
POSTGRES_PASSWORD: app_password
29+
30+
healthcheck:
31+
test: ["CMD-SHELL", "pg_isready -U postgres -d relecloud"]
32+
interval: 5s
33+
timeout: 5s
34+
retries: 5
4035

4136
volumes:
4237
postgres-data:

‎.env.sample‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
POSTGRES_DATABASE=<database name>
2-
POSTGRES_HOST=<database-hostname>
3-
POSTGRES_PORT=5432
4-
POSTGRES_USERNAME=<db-user-name>
5-
POSTGRES_PASSWORD=<db-password>
1+
DBNAME=app
2+
DBHOST=db
3+
DBPORT=5432
4+
DBUSER=app_user
5+
DBPASS=app_password

‎README.md‎

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -22,42 +22,36 @@ description: This project deploys a restaurant review web application using Fast
2222

2323
This project deploys a web application for a restaurnant review site using FastAPI. The application can be deployed to Azure with Azure App Service using the [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/overview).
2424

25-
## Opening the project
2625

27-
This project has [Dev Container support](https://code.visualstudio.com/docs/devcontainers/containers), so it will be setup automatically if you open it in Github Codespaces or in local VS Code with the [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers).
26+
## Run the sample
2827

29-
If you're *not* using one of those options for opening the project, then you'll need to:
28+
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:
3029

31-
1. Start up a local PostgreSQL server, create a database for the app, and set the following environment variables according to your database configuration.
30+
1. Fork this repository to your account. For instructions, see [Fork a repo](https://docs.github.com/get-started/quickstart/fork-a-repo).
3231

33-
```shell
34-
export POSTGRES_HOST=localhost
35-
export POSTGRES_PORT=5432
36-
export POSTGRES_DATABASE=<YOUR DATABASE>
37-
export POSTGRES_USERNAME=<YOUR USERNAME>
38-
export POSTGRES_PASSWORD=<YOUR PASSWORD>
39-
```
32+
1. From the repository root of your fork, select **Code** > **Codespaces** > **+**.
4033

41-
1. Create a [Python virtual environment](https://docs.python.org/3/tutorial/venv.html#creating-virtual-environments) and activate it.
34+
1. In the codespace terminal, run the following commands:
4235

43-
1. Install production requirements:
36+
```shell
37+
# Create .env with environment variables
38+
cp .env.sample .env
4439

45-
```sh
40+
# Install requirements
4641
python3 -m pip install -r src/requirements.txt
47-
```
48-
49-
1. Install the app as an editable package:
5042

51-
```sh
43+
# Install the app as an editable package
5244
python3 -m pip install -e src
53-
```
54-
55-
1. Apply database migrations:
5645

57-
```sh
46+
# Run database migrations
5847
python3 src/fastapi_app/seed_data.py
48+
49+
# Start the development server
50+
python3 -m uvicorn fastapi_app:app --reload --port=8000
5951
```
6052

53+
1. When you see the message `Your application running on port 8000 is available.`, click **Open in Browser**.
54+
6155
## Running locally
6256

6357
If you're running the app inside VS Code or GitHub Codespaces, you can use the "Run and Debug" button to start the app.

‎infra/resources.bicep‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -182,15 +182,7 @@ resource web 'Microsoft.Web/sites@2022-03-01' = {
182182
properties: {
183183
SCM_DO_BUILD_DURING_DEPLOYMENT: 'true'
184184
AZURE_POSTGRESQL_CONNECTIONSTRING: 'dbname=${pythonAppDatabase.name} host=${postgresServer.name}.postgres.database.azure.com port=5432 sslmode=require user=${postgresServer.properties.administratorLogin} password=${databasePassword}'
185-
POSTGRES_HOST: '${postgresServer.name}.postgres.database.azure.com'
186-
POSTGRES_DATABASE: pythonAppDatabase.name
187-
POSTGRES_PORT: '5432'
188-
POSTGRES_USERNAME: postgresServer.properties.administratorLogin
189-
POSTGRES_PASSWORD: databasePassword
190-
POSTGRES_SSL: 'require'
191185
SECRET_KEY: secretKey
192-
// FLASK_DEBUG: 'False'
193-
//Added for Azure Redis Cache
194186
AZURE_REDIS_CONNECTIONSTRING: 'rediss://:${redisCache.listKeys().primaryKey}@${redisCache.name}.redis.cache.windows.net:6380/0'
195187
}
196188
}

‎src/fastapi_app/models.py‎

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,33 @@
33
from datetime import datetime
44
from urllib.parse import quote_plus
55

6+
from dotenv import load_dotenv
67
from sqlmodel import Field, SQLModel, create_engine
78

89
sql_url = ""
9-
if os.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING"):
10+
if os.getenv("WEBSITE_HOSTNAME"):
11+
print("Connecting to Azure PostgreSQL Flexible server based on AZURE_POSTGRESQL_CONNECTIONSTRING...")
1012
env_connection_string = os.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING")
11-
12-
# Parse the connection string
13-
details = dict(item.split('=') for item in env_connection_string.split())
14-
15-
# Properly format the URL for SQLAlchemy
16-
sql_url = (
17-
f"postgresql://{quote_plus(details['user'])}:{quote_plus(details['password'])}"
18-
f"@{details['host']}:{details['port']}/{details['dbname']}?sslmode={details['sslmode']}"
19-
)
13+
if env_connection_string is None:
14+
print("Missing environment variable AZURE_POSTGRESQL_CONNECTIONSTRING")
15+
else:
16+
# Parse the connection string
17+
details = dict(item.split('=') for item in env_connection_string.split())
18+
19+
# Properly format the URL for SQLAlchemy
20+
sql_url = (
21+
f"postgresql://{quote_plus(details['user'])}:{quote_plus(details['password'])}"
22+
f"@{details['host']}:{details['port']}/{details['dbname']}?sslmode={details['sslmode']}"
23+
)
2024

2125
else:
22-
POSTGRES_USERNAME = os.environ.get("POSTGRES_PASSWORD")
23-
POSTGRES_PASSWORD = os.environ.get("POSTGRES_PASSWORD")
24-
POSTGRES_HOST = os.environ.get("POSTGRES_HOST")
25-
POSTGRES_DATABASE = os.environ.get("POSTGRES_DATABASE")
26-
POSTGRES_PORT = os.environ.get("POSTGRES_PORT", 5432)
26+
print("Connecting to local PostgreSQL server based on .env file...")
27+
load_dotenv()
28+
POSTGRES_USERNAME = os.environ.get("DBUSER")
29+
POSTGRES_PASSWORD = os.environ.get("DBPASS")
30+
POSTGRES_HOST = os.environ.get("DBHOST")
31+
POSTGRES_DATABASE = os.environ.get("DBNAME")
32+
POSTGRES_PORT = os.environ.get("DBPORT", 5432)
2733

2834
sql_url = f"postgresql://{POSTGRES_USERNAME}:{POSTGRES_PASSWORD}@{POSTGRES_HOST}:{POSTGRES_PORT}/{POSTGRES_DATABASE}"
2935

‎src/fastapi_app/seed_data.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from dotenv import load_dotenv
21
from sqlmodel import SQLModel
32

43
from fastapi_app.models import Restaurant, Review, create_db_and_tables, engine
@@ -12,5 +11,4 @@ def drop_all():
1211

1312

1413
if __name__ == "__main__":
15-
load_dotenv()
1614
create_db_and_tables()

0 commit comments

Comments
 (0)