Skip to content
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

Implement Python sample app #1

Merged
merged 34 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
15997a5
Add TODO.
Nov 21, 2024
392da91
Remove references to files that don't exist.
Nov 22, 2024
d1e9f14
Update .gitignore.
Nov 22, 2024
3cb4c24
Add a unit test.
Nov 22, 2024
6a12243
Add test_ prefix to help test discovery.
Nov 22, 2024
7bee734
Use setup-python action to install from requirements.txt.
Dec 3, 2024
5ce72eb
Install from requirements.txt, and use npm caching.
Dec 3, 2024
37ec5be
Simplify schema push by using --active flag.
Dec 3, 2024
ab38b65
Use --dir flag instead of adding schema to .fauna-project file.
Dec 3, 2024
c286c9f
Make npm install separate step.
Dec 3, 2024
7b6ae10
Go back to installing fauna-shell as separate step.
Dec 3, 2024
93d9e3d
Remove stray .fauna-project file, and fail setup.sh on error.
Dec 4, 2024
53d9a7b
Some cleanup of curl command.
Dec 4, 2024
0db6b82
Build out sample app.
Dec 6, 2024
9832a85
README.md: Update README.
Dec 12, 2024
c3e71c9
Fix path to app.py.
Dec 12, 2024
df5be8f
Update README.md
findgriffin Dec 13, 2024
f820011
Update README.md
findgriffin Dec 13, 2024
02981d1
Update .gitignore
findgriffin Dec 13, 2024
49e3102
Update ecommerce_app/models/order.py
findgriffin Dec 13, 2024
47734cc
PR feedback.
Dec 13, 2024
297097a
Change Flask run command.
Dec 16, 2024
f3dbd0b
Move scripts from test to scripts directory.
Dec 16, 2024
a9514c8
PR feedback.
Dec 16, 2024
922e294
Implement new_customer API.
Dec 16, 2024
e7a54e5
test.yml: Fix typo.
Dec 16, 2024
a1cf33d
test.yml: Modify run command.
Dec 16, 2024
455f08e
README.md: Change reference to validate.sh, and include instructions …
Dec 16, 2024
72fac00
Changes to make type checker happy.
Dec 16, 2024
1c2ac3c
A couple of nips and tucks.
Dec 16, 2024
c09dd8a
PR feedback: Use -r instead of xargs.
Dec 17, 2024
a334815
PR feedback: projection.
Dec 17, 2024
3a0cfbd
Add a comment to validate.sh.
Dec 17, 2024
449695b
Rename validate.sh -> smoke_test.sh.
Dec 17, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions .fauna-project

This file was deleted.

36 changes: 23 additions & 13 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,27 @@ jobs:
ports:
- 8443:8443
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: 'pip' # caching pip dependencies
- name: Install Python dependencies
run: pip install -r requirements.txt
- name: Run unit tests
run: python3 -m unittest discover
- name: Install fauna-shell
run:
npm install -g fauna-shell
- name: Setup Test Database
run: ./scripts/setup.sh

- name: Install fauna-shell
run:
npm install -g fauna-shell
- name: Setup Test Database
run: ./test/setup.sh

- name: Test sample app
run: |
FAUNA_ENDPOINT=http://localhost:8443 FAUNA_SECRET=`cat .fauna_key` python3 app.py > app.log 2>&1 &
./test/validate.sh
cat bootrun.log
- name: Test sample app
run: |
cd ecommerce_app
FAUNA_ENDPOINT=http://localhost:8443 FAUNA_SECRET=`cat ../.fauna_key` python3 -m flask run > ../app.log 2>&1 &
cd ..
./scripts/smoke_test.sh
cat app.log
13 changes: 12 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,12 @@
myenv/
myenv/
venv/
.idea/*

__pycache__/*
*/__pycache__/*
**/__pycache__

**/.DS_Store

**/.env
.fauna_project
218 changes: 218 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
# Fauna Python sample app

This sample app shows how you can use [Fauna](https://fauna.com) in a
production application.

The app uses Python 3 and the Fauna Python driver to create HTTP API
endpoints for an e-commerce store. The source code includes comments that highlight
best practices for the driver and Fauna Query Language (FQL) queries.

This README covers how to set up and run the app locally. For an overview of
Fauna, see the [Fauna
docs](https://docs.fauna.com/fauna/current/get_started/overview).

## Highlights
The sample app demonstrates using several Fauna features:

- **[Document type
enforcement](https://docs.fauna.com/fauna/current/learn/schema/#type-enforcement):**
Collection schemas enforce a structure for the app's documents. Fauna rejects
document writes that don't conform to the schema, ensuring data consistency.
[Zero-downtime
migrations](https://docs.fauna.com/fauna/current/learn/schema/#schema-migrations)
let you safely change the schemas at any time.

- **[Relationships](https://docs.fauna.com/fauna/current/learn/query/relationships/):**
Normalized references link documents across collections. The app's queries use
[projection](https://docs.fauna.com/fauna/current/reference/fql/projection/)
to dynamically retrieve linked documents, even when deeply nested. No complex
joins, aggregations, or duplication needed.

- **[Computed
fields](https://docs.fauna.com/fauna/current/learn/schema/#computed-fields):**
Computed fields dynamically calculate their values at query time. For example,
each customer's `orders` field uses a query to fetch a set of filtered orders.
Similarly, each order's `total` is calculated at query time based on linked
product prices and quantity.

- **[Constraints](https://docs.fauna.com/fauna/current/learn/schema/#unique-constraints):**
The app uses constraints to ensure field values are valid. For example, the
app uses unique constraints to ensure each customer has a unique email address
and each product has a unique name. Similarly, check constraints ensure each
customer has only one cart at a time and that product prices are not negative.

- **[User-defined functions
(UDFs)](https://docs.fauna.com/fauna/current/learn/data-model/user-defined-functions/):**
The app uses UDFs to store business logic as reusable queries. For example,
the app uses a `checkout()` UDF to process order updates. `checkout()` calls
another UDF, `validateOrderStatusTransition()`, to validate `status`
transitions for orders.

## Requirements
To run the app, you'll need:

- A [Fauna account](https://dashboard.fauna.com/register). You can sign up for a
free account at https://dashboard.fauna.com/register.

- Python 3.9 or later

- [Fauna CLI](https://docs.fauna.com/fauna/current/tools/shell/) v3.0.0 or later.

To install the CLI, run:

```sh
npm install -g fauna-shell@latest
```

You should also be familiar with basic Fauna CLI commands and usage. For an
overview, see the [Fauna CLI
docs](https://docs.fauna.com/fauna/current/tools/shell/).

## Setup

1. Clone the repo and navigate to the `python-sample-app` directory:

```sh
git clone [email protected]:fauna/python-sample-app.git
cd python-sample-app
```
2. Setup a Python virtual environment, and install the requirements:

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

3. Log in to Fauna using the Fauna CLI:

```sh
fauna cloud-login
```

When prompted, enter:

* **Endpoint name:** `cloud` (Press Enter)
* **Email address:** The email address for your Fauna account.
* **Password:** The password for your Fauna account.
* **Which endpoint would you like to set as default?** The `cloud-*`
endpoint for your preferred region group. For example, to use the US
region group, use `cloud-us`.

The command requires an email and password login. If you log in to Fauna
using GitHub or Netlify, you can enable email and password login using the
[Forgot Password](https://dashboard.fauna.com/forgot-password) workflow.

4. Use the Fauna CLI to create the `ECommercePython` database:

```sh
fauna create-database ECommercePython
```

5. Create a
[`.fauna-project`](https://docs.fauna.com/fauna/current/tools/shell/#proj-config)
config file for the project:

```sh
fauna project init
```

When prompted, enter:

* `schema` as the schema directory.
* `dev` as the environment name.
* The default endpoint.
* `ECommercePython` as the database.

6. Push the `.fsl` files in the `schema` directory to the `ECommercePython`
database:

```sh
fauna schema push
```

When prompted, accept and stage the schema.

7. Check the status of the staged schema:

```sh
fauna schema status
```

8. When the status is `ready`, commit the staged schema to the database:

```sh
fauna schema commit
```

The commit applies the staged schema to the database. The commit creates the
collections and user-defined functions (UDFs) defined in the `.fsl` files of the
`schema` directory.

9. Create a key with the `server` role for the `ECommercePython` database:

```sh
fauna create-key --environment='' ECommercePython server
```

Copy the returned `secret`. The app can use the key's secret to authenticate
requests to the database.

## Run the app

The app runs an HTTP API server. From the root directory, run:

```sh
cd ecommerce_app
FAUNA_SECRET=<secret> python3 -m flask run
```

Once started, the local server is available at http://localhost:5000

## Make HTTP API requests

```

You can use the endpoints to make API requests that read and write data from
the `ECommercePython` database.

For example, with the local server running in a separate terminal tab, run the
following curl request to the `POST /customers` endpoint. The request creates a
`Customer` collection document in the `ECommercePython` database.

curl -v \
http://localhost:5000/customers \
-H "Content-Type: application/json" \
-d '{
"name": "Alice Appleseed",
"email": "[email protected]",
"address": {
"street": "87856 Mendota Court",
"city": "Washington",
"state": "DC",
"postalCode": "20220",
"country": "USA"
}
}'
```

You can view the documents for the collection in the [Fauna
Dashboard](https://dashboard.fauna.com/).

## Run unit tests
Some example unit tests in the `tests/` directory show how you can test a Python Flask app that uses Fauna.
```sh
python3 -m unittest discover -s tests
```

## Seed some data
If you want to seed some data in your app, you can do the following (also see `scripts/setup.sh`):

```sh
fauna import --collection Category --path seed/categories.json
fauna import --collection Customer --path seed/customers.json
fauna eval --file seed/products.fql
fauna eval --file seed/orders.fql
```

If you've seeded the DB, then you can run `source scripts/smoke_test.sh`
86 changes: 0 additions & 86 deletions Readme.md

This file was deleted.

Binary file removed __pycache__/routes.cpython-312.pyc
Binary file not shown.
13 changes: 0 additions & 13 deletions app.py

This file was deleted.

Loading
Loading