-
Notifications
You must be signed in to change notification settings - Fork 1
Add FastAPI pub/sub example with real-world PGMQ usage patterns #32
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
a0dff47
Initial plan
Copilot a138376
Add FastAPI pub/sub example with tests and GitHub Action
Copilot 147f471
Fix tests for FastAPI pub/sub example
Copilot a256a18
Fix consumer to work with async event loop properly
Copilot aca65a3
Address code review feedback: use lifespan, improve exception handling
Copilot 0a6d22e
Add workflow permissions to examples GitHub Action
Copilot 0d2e4bf
Address review comments: fix transaction, use pgmq methods, add messa…
Copilot 8c40f42
Fix code review issues: move imports to top of file and remove unused…
Copilot 01992d8
Simplify consumer code and add pyproject.toml for example
Copilot 71a5868
Update pytest flags to -vss for better test output visibility
Copilot d351aef
Add pre-commit hooks and scripts for async method checks in PGMQueue
jason810496 20e2fba
WIP
jason810496 d2fa1df
Merge branch 'main' into copilot/add-fastapi-pub-sub-example
jason810496 615beea
Add MultiSubprocessesRenderer utils
jason810496 e36cc8f
Fix MultiSubprocessesRenderer not rendering issue
jason810496 efa27b5
Add timeout arg and verify stop_condition_callable
jason810496 40cabda
Refactor FastAPI example and add create orders coordinator script
jason810496 fc86752
Remove Python 3.9 from examples workflow matrix
jason810496 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| name: Examples Tests | ||
|
|
||
| on: | ||
| push: | ||
| branches: [main, develop] | ||
| paths: | ||
| - 'examples/**' | ||
| - 'examples_tests/**' | ||
| - 'pgmq_sqlalchemy/**' | ||
| - '.github/workflows/examples.yml' | ||
| pull_request: | ||
| branches: [main, develop] | ||
| paths: | ||
| - 'examples/**' | ||
| - 'examples_tests/**' | ||
| - 'pgmq_sqlalchemy/**' | ||
| - '.github/workflows/examples.yml' | ||
|
|
||
| jobs: | ||
| test-examples: | ||
| runs-on: ubuntu-latest | ||
|
|
||
| permissions: | ||
| contents: read | ||
|
|
||
| strategy: | ||
| matrix: | ||
| python-version: ["3.10", "3.11", "3.12"] | ||
|
|
||
| name: Test Examples (Python ${{ matrix.python-version }}) | ||
|
|
||
| steps: | ||
| - uses: actions/checkout@v4 | ||
|
|
||
| - name: Set up Python ${{ matrix.python-version }} | ||
| uses: actions/setup-python@v5 | ||
| with: | ||
| python-version: ${{ matrix.python-version }} | ||
|
|
||
| - name: Install uv | ||
| run: | | ||
| curl -LsSf https://astral.sh/uv/install.sh | sh | ||
| echo "$HOME/.local/bin" >> $GITHUB_PATH | ||
|
|
||
| - name: Install dependencies | ||
| run: | | ||
| uv sync --all-groups --no-group docs | ||
|
|
||
| - name: Start PostgreSQL | ||
| run: | | ||
| cp pgmq_postgres.template.env pgmq_postgres.env | ||
| cp pgmq_tests.template.env pgmq_tests.env | ||
| make start-db | ||
|
|
||
| - name: Setup database for examples tests | ||
| run: | | ||
| docker compose exec -T pgmq_postgres psql -U postgres -c "CREATE EXTENSION IF NOT EXISTS pgmq CASCADE;" | ||
|
|
||
| - name: Run examples tests | ||
| run: | | ||
| uv run pytest examples_tests --cov=examples --cov-report=xml:coverage-examples-py${{ matrix.python-version }}.xml -vss | ||
|
|
||
| - name: Upload coverage artifact | ||
| if: always() | ||
| uses: actions/upload-artifact@v4 | ||
| with: | ||
| name: coverage-examples-py${{ matrix.python-version }} | ||
| path: coverage-examples-py${{ matrix.python-version }}.xml | ||
| retention-days: 1 | ||
|
|
||
| - name: Cleanup | ||
| if: always() | ||
| run: | | ||
| docker compose down |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| # FastAPI Pub/Sub Example with PGMQ | ||
|
|
||
| This example demonstrates a real-world scenario of using PGMQ with FastAPI for an order management system. It shows how to: | ||
|
|
||
| - Use PGMQ with FastAPI and sync SQLAlchemy sessions (psycopg2) | ||
| - Publish messages using `PGMQOperation` (op) in a web API | ||
| - Consume messages asynchronously using `PGMQueue` with asyncpg | ||
|
|
||
| ## Architecture | ||
|
|
||
| - **API Server (api.py)**: FastAPI application that creates orders and publishes them to PGMQ | ||
| - Uses sync database driver (psycopg2) | ||
| - Uses `PGMQOperation` (imported as `op`) for publishing messages | ||
| - Provides REST endpoints for creating and retrieving orders | ||
|
|
||
| - **Consumer (consumer.py)**: Async worker that processes orders from the queue | ||
| - Uses async database driver (asyncpg) | ||
| - Uses `PGMQueue` class for reading messages | ||
| - Processes messages concurrently with asyncio | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - PostgreSQL with PGMQ extension installed | ||
| - Python 3.9 or higher | ||
|
|
||
| Quick setup: | ||
| ```bash | ||
| docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 quay.io/tembo/pg16-pgmq:latest | ||
| ``` | ||
|
|
||
| ## Installation | ||
|
|
||
| Install required dependencies using uv with the example's pyproject.toml: | ||
|
|
||
| ```bash | ||
| cd examples/fastapi_pub_sub | ||
| uv pip install -e . | ||
| ``` | ||
|
|
||
| Or install dependencies directly: | ||
|
|
||
| ```bash | ||
| uv pip install fastapi uvicorn psycopg2-binary asyncpg pgmq-sqlalchemy | ||
| ``` | ||
|
|
||
| Or install from the project root with uv: | ||
|
|
||
| ```bash | ||
| cd /path/to/pgmq-sqlalchemy | ||
| uv pip install -e ".[psycopg2-binary,asyncpg]" | ||
| ``` | ||
|
|
||
| ## Running the Example | ||
|
|
||
| ### 1. Start the API Server | ||
|
|
||
| ```bash | ||
| python api.py | ||
| ``` | ||
|
|
||
| The API will be available at http://localhost:8000 | ||
|
|
||
| ### 2. Start the Consumer | ||
|
|
||
| In a separate terminal: | ||
|
|
||
| ```bash | ||
| python consumer.py | ||
| ``` | ||
|
|
||
| ### 3. Create Orders | ||
|
|
||
| Create an order via the API: | ||
|
|
||
| ```bash | ||
| curl -X POST "http://localhost:8000/orders" \ | ||
| -H "Content-Type: application/json" \ | ||
| -d '{ | ||
| "customer_name": "John Doe", | ||
| "product_name": "Widget", | ||
| "quantity": 5, | ||
| "price": 29.99 | ||
| }' | ||
| ``` | ||
|
|
||
| You should see: | ||
| - The API returns the created order with a message ID | ||
| - The consumer logs show the order being processed | ||
|
|
||
| ### 4. View Order | ||
|
|
||
| Get an order by ID: | ||
|
|
||
| ```bash | ||
| curl "http://localhost:8000/orders/1" | ||
| ``` | ||
|
|
||
| ## API Endpoints | ||
|
|
||
| - `POST /orders` - Create a new order | ||
| - `GET /orders/{order_id}` - Get order by ID | ||
| - `GET /health` - Health check endpoint | ||
|
|
||
| ## How It Works | ||
|
|
||
| 1. When an order is created via the API: | ||
| - The order is saved to the database | ||
| - A message is published to PGMQ using `op.send()` | ||
| - The message contains order details | ||
|
|
||
| 2. The consumer: | ||
| - Continuously polls the queue for new messages | ||
| - Processes messages concurrently using asyncio | ||
| - Deletes successfully processed messages | ||
| - Leaves failed messages in the queue for retry | ||
|
|
||
| ## Configuration | ||
|
|
||
| You can modify the following constants in the files: | ||
|
|
||
| - `DATABASE_URL`: PostgreSQL connection string | ||
| - `QUEUE_NAME`: Name of the PGMQ queue (default: "order_queue") | ||
| - `batch_size`: Number of messages to process in each batch (consumer.py) | ||
| - `vt`: Visibility timeout in seconds (consumer.py) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use
uvto manage the dependencies instead ofrequirements.txtThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in commit 0d2e4bf. Updated README to use
uv pip installcommands instead of pip with requirements.txt.