Skip to content

Commit

Permalink
Initial commit with project files
Browse files Browse the repository at this point in the history
  • Loading branch information
saknius committed Dec 5, 2024
1 parent 178f72d commit 5170a3b
Show file tree
Hide file tree
Showing 6 changed files with 233 additions and 1 deletion.
83 changes: 82 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,82 @@
# dbos-fastapi-starter
# Welcome to DBOS!

This is a template app built with DBOS and FastAPI.

### Getting Started

To get started building, edit `app/main.py`.
Then, commit your changes and visit the [cloud console](https://console.dbos.dev/applications) to redeploy it from GitHub!

To include new packages or dependencies, add them to `requirements.txt`.

<details>
<summary><strong>Deploying via the DBOS Cloud CLI</strong></summary>

You can also deploy this app via the DBOS Cloud CLI.
Install it with this command (requires Node):

```shell
npm i -g @dbos-inc/dbos-cloud
```

Then, run this command to deploy your app:

```shell
dbos-cloud app deploy
```
</details>

### Developing Locally

To run this app locally, you need to connect it to a Postgres database.
You can use a DBOS Cloud database, a Docker container, or a local Postgres installation.

<details>
<summary><strong>Connecting to a DBOS Cloud Postgres database</strong></summary>

First install the DBOS Cloud CLI (requires Node):

```shell
npm i -g @dbos-inc/dbos-cloud
```

Then set a password for your DBOS Cloud database:

```shell
dbos-cloud db reset-password
```

Then connect your local app to your cloud database. When prompted, enter the password you just set.

```shell
dbos-cloud db local
```
</details>

<details>
<summary><strong>Starting Postgres with Docker</strong></summary>

If you have Docker, you can start a Postgres database locally with:

```shell
export PGPASSWORD=dbos
python3 start_postgres_docker.py
```
</details>


After connecting to Postgres, create a virtual environment and install dependencies:

```shell
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```

Then start your app:

```shell
dbos start
```

Visit [`http://localhost:8000`](http://localhost:8000) to see your app!
Empty file added app/__init__.py
Empty file.
63 changes: 63 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from fastapi import FastAPI
from fastapi.responses import HTMLResponse

from dbos import DBOS

# Welcome to DBOS!
# This is a template application built with DBOS and FastAPI.

app = FastAPI()
DBOS(fastapi=app)

# This is a simple DBOS workflow with two steps.
# It is served via FastAPI from the /hello endpoint.
# You can use workflows to build crashproof applications.
# Learn more here: https://docs.dbos.dev/python/programming-guide


@DBOS.step()
def hello_step() -> str:
return "Hello"


@DBOS.step()
def world_step() -> str:
return "world"


@app.get("/hello")
@DBOS.workflow()
def hello_world() -> str:
hello = hello_step()
world = world_step()
return f"{hello}, {world}!"


# This code uses FastAPI to serve an HTML + CSS readme from the root path.


@app.get("/")
def readme() -> HTMLResponse:
readme = """
<!DOCTYPE html>
<html lang="en">
<head>
<title>Welcome to DBOS!</title>
<link rel="icon" href="https://dbos-blog-posts.s3.us-west-1.amazonaws.com/live-demo/favicon.ico" type="image/x-icon">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="font-sans text-gray-800 p-6 max-w-2xl mx-auto">
<h1 class="text-xl font-semibold mb-4">Welcome to DBOS!</h1>
<p class="mb-4">
This is a template built with DBOS and FastAPI. Visit <code class="bg-gray-100 px-1 rounded"><a href="/hello" target="_blank" class="text-blue-600 hover:underline">/hello</a></code> to see a "Hello, World!" message.
</p>
<p class="mb-4">
To start building, edit <code class="bg-gray-100 px-1 rounded">app/main.py</code>, commit your changes, then visit the <a href="https://console.dbos.dev/applications" target="_blank" class="text-blue-600 hover:underline">cloud console</a> to redeploy your app.
</p>
<p class="mb-4">
To learn how to build crashproof apps with DBOS, visit the <a href="https://docs.dbos.dev/python/programming-guide" target="_blank" class="text-blue-600 hover:underline">docs</a>!
</p>
</body>
</html>
"""
return HTMLResponse(readme)
20 changes: 20 additions & 0 deletions dbos-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# To enable auto-completion and validation for this file in VSCode, install the RedHat YAML extension
# https://marketplace.visualstudio.com/items?itemName=redhat.vscode-yaml

# yaml-language-server: $schema=https://raw.githubusercontent.com/dbos-inc/dbos-transact-py/main/dbos/dbos-config.schema.json

name: dbos-fastapi-template
language: python
runtimeConfig:
start:
- "fastapi run app/main.py"
database:
hostname: localhost
port: 5432
username: postgres
password: ${PGPASSWORD}
migrate:
- echo 'No migrations specified'
telemetry:
logs:
logLevel: INFO
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dbos==0.12.0
67 changes: 67 additions & 0 deletions start_postgres_docker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import os
import subprocess
import sys
import time

# Default PostgreSQL port
port = "5432"

# Set the host PostgreSQL port with the -p/--port flag
for i, arg in enumerate(sys.argv):
if arg in ["-p", "--port"]:
if i + 1 < len(sys.argv):
port = sys.argv[i + 1]

if "PGPASSWORD" not in os.environ:
print("Error: PGPASSWORD is not set.")
sys.exit(1)

try:
subprocess.run(
[
"docker",
"run",
"--rm",
"--name=dbos-db",
f'--env=POSTGRES_PASSWORD={os.environ["PGPASSWORD"]}',
"--env=PGDATA=/var/lib/postgresql/data",
"--volume=/var/lib/postgresql/data",
"-p",
f"{port}:5432",
"-d",
"pgvector/pgvector:pg16",
],
check=True,
)

print("Waiting for PostgreSQL to start...")
attempts = 30

while attempts > 0:
try:
subprocess.run(
[
"docker",
"exec",
"dbos-db",
"psql",
"-U",
"postgres",
"-c",
"SELECT 1;",
],
check=True,
capture_output=True,
)
print("PostgreSQL started!")
print("Database started successfully!")
break
except subprocess.CalledProcessError:
attempts -= 1
time.sleep(1)

if attempts == 0:
print("Failed to start PostgreSQL.")

except subprocess.CalledProcessError as error:
print(f"Error starting PostgreSQL in Docker: {error}")

0 comments on commit 5170a3b

Please sign in to comment.