You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The advantage of the PRG pattern is that it is very straightforward to implement and keeps most of the rendering logic on the server side. The disadvantage is that it requires an extra round trip to the database to fetch the updated data, and re-rendering the entire page template may be less efficient than a partial page update on the client side.
62
+
The advantage of the PRG pattern is that it is very straightforward to implement and keeps most of the rendering logic on the server side. One disadvantage is that it requires an extra round trip to the database to fetch the updated data, and re-rendering the entire page template may be less efficient than a partial page update on the client side. Another disadvantage is that it if the user makes an invalid form submission, they will see an error page and will have to click the browser's "back" button to get back to the form with their original form inputs.
63
63
64
-
## Form validation flow
65
-
66
-
We've experimented with several approaches to validating form inputs in the FastAPI endpoints.
67
-
68
-
### Objectives
69
-
70
-
Ideally, on an invalid input, we would redirect the user back to the form, preserving their inputs and displaying an error message about which input was invalid.
71
-
72
-
This would keep the error handling consistent with the PRG pattern described in the [Architecture](https://promptlytechnologies.com/fastapi-jinja2-postgres-webapp/docs/architecture) section of this documentation.
73
-
74
-
To keep the code DRY, we'd also like to handle such validation with Pydantic dependencies, Python exceptions, and exception-handling middleware as much as possible.
75
-
76
-
### Obstacles
77
-
78
-
One challenge is that if we redirect back to the page with the form, the page is re-rendered with empty form fields.
79
-
80
-
This can be overcome by passing the inputs from the request as context variables to the template.
81
-
82
-
But that's a bit clunky, because then we have to support form-specific context variables in every form page and corresponding GET endpoint.
83
-
84
-
Also, we have to:
85
-
86
-
1. access the request object (which is not by default available to our middleware), and
87
-
2. extract the form inputs (at least one of which is invalid in this error case), and
88
-
3. pass the form inputs to the template (which is a bit challenging to do in a DRY way since there are different sets of form inputs for different forms).
89
-
90
-
Solving these challenges is possible, but gets high-complexity pretty quickly.
91
-
92
-
### Approaches
93
-
94
-
The best solution, I think, is to use really robust client-side form validation to prevent invalid inputs from being sent to the server in the first place. That makes it less important what we do on the server side, although we still need to handle the server-side error case as a backup in the event that something slips past our validation on the client side.
95
-
96
-
Here are some patterns we've considered for server-side error handling:
97
-
98
-
<style>
99
-
.styled-table, .styled-tableth, .styled-tabletd {
100
-
border: 1pxsolidblack;
101
-
padding: 8px;
102
-
border-collapse: collapse;
103
-
}
104
-
105
-
.styled-tableth:nth-child(1) { width: 50%; }
106
-
.styled-tableth:nth-child(2),
107
-
.styled-tableth:nth-child(3),
108
-
.styled-tableth:nth-child(4) { width: 15%; }
109
-
.styled-tableth:nth-child(5) { width: 10%; }
110
-
</style>
111
-
112
-
<tableclass="styled-table">
113
-
<thead>
114
-
<tr>
115
-
<th>Approach</th>
116
-
<th>Returns to same page</th>
117
-
<th>Preserves form inputs</th>
118
-
<th>Follows PRG pattern</th>
119
-
<th>Complexity</th>
120
-
</tr>
121
-
</thead>
122
-
<tbody>
123
-
<tr>
124
-
<td>Validate with Pydantic dependency, catch and redirect from middleware (with exception message as context) to an error page with "go back" button</td>
125
-
<td>No</td>
126
-
<td>Yes</td>
127
-
<td>Yes</td>
128
-
<td>Low</td>
129
-
</tr>
130
-
<tr>
131
-
<td>Validate in FastAPI endpoint function body, redirect to origin page with error message query param</td>
132
-
<td>Yes</td>
133
-
<td>No</td>
134
-
<td>Yes</td>
135
-
<td>Medium</td>
136
-
</tr>
137
-
<tr>
138
-
<td>Validate in FastAPI endpoint function body, redirect to origin page with error message query param and form inputs as context so we can re-render page with original form inputs</td>
139
-
<td>Yes</td>
140
-
<td>Yes</td>
141
-
<td>Yes</td>
142
-
<td>High</td>
143
-
</tr>
144
-
<tr>
145
-
<td>Validate with Pydantic dependency, use session context to get form inputs from request, redirect to origin page from middleware with exception message and form inputs as context so we can re-render page with original form inputs</td>
146
-
<td>Yes</td>
147
-
<td>Yes</td>
148
-
<td>Yes</td>
149
-
<td>High</td>
150
-
</tr>
151
-
<tr>
152
-
<td>Validate in either Pydantic dependency or function endpoint body and directly return error message or error toast HTML partial in JSON, then mount error toast with HTMX or some simple layout-level Javascript</td>
153
-
<td>Yes</td>
154
-
<td>Yes</td>
155
-
<td>No</td>
156
-
<td>Low</td>
157
-
</tr>
158
-
</tbody>
159
-
</table>
160
-
161
-
Presently this template primarily uses option 1 but also supports option 2. Ultimately, I think option 5 will be preferable; support for that [is planned](https://github.com/Promptly-Technologies-LLC/fastapi-jinja2-postgres-webapp/issues/5) for a future update or fork of this template.
64
+
A future iteration of this application will use HTMX to update the page in place, so that on an invalid submission an error toast is displayed without a page reload (thus preserving the user's scroll position and form inputs).
Copy file name to clipboardExpand all lines: docs/contributing.qmd
+8-4Lines changed: 8 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -43,13 +43,17 @@ To contribute code to the project:
43
43
44
44
### Rendering the documentation
45
45
46
-
The README and documentation website are rendered with [Quarto](https://quarto.org/docs/). If you ,make changes to the `.qmd` files in the root folder and the `docs` folder, run the following commands to re-render the docs:
46
+
The README and documentation website are rendered with [Quarto](https://quarto.org/docs/). If you make changes to the `.qmd` files in the root folder and the `docs` folder, you will need to re-render the docs with Quarto.
47
+
48
+
Quarto expects environment variables to be set in a file called `_environment`, so before running Quarto render commands, you should copy your `.env` file to `_environment`.
47
49
48
50
```bash
51
+
# To copy the .env file to _environment
52
+
cp .env _environment
49
53
# To render the documentation website
50
-
quarto render
54
+
uv run quarto render
51
55
# To render the README
52
-
quarto render index.qmd --output-dir . --output README.md --to gfm
56
+
uv run quarto render index.qmd --output-dir . --output README.md --to gfm
53
57
```
54
58
55
59
Due to a quirk of Quarto, an unnecessary `index.html` file is created in the root folder when the README is rendered. This file can be safely deleted.
@@ -74,5 +78,5 @@ When creating new features,
74
78
To publish the documentation to GitHub Pages, run the following command:
Copy file name to clipboardExpand all lines: docs/customization.qmd
+17-12Lines changed: 17 additions & 12 deletions
Original file line number
Diff line number
Diff line change
@@ -31,17 +31,19 @@ The following fixtures, defined in `tests/conftest.py`, are available in the tes
31
31
-`engine`: Creates a new SQLModel engine for the test database.
32
32
-`set_up_database`: Sets up the test database before running the test suite by dropping all tables and recreating them to ensure a clean state.
33
33
-`session`: Provides a session for database operations in tests.
34
-
-`clean_db`: Cleans up the database tables before each test by deleting all entries in the `PasswordResetToken` and `User` tables.
34
+
-`clean_db`: Cleans up the database tables before each test by deleting all entries in the `PasswordResetToken`, `EmailUpdateToken`, `User`, `Role`, `Organization`, and `Account` tables.
35
+
-`test_account`: Creates a test account with a predefined email and hashed password.
36
+
-`test_user`: Creates a test user in the database linked to the test account.
35
37
-`auth_client`: Provides a `TestClient` instance with access and refresh token cookies set, overriding the `get_session` dependency to use the `session` fixture.
36
38
-`unauth_client`: Provides a `TestClient` instance without authentication cookies set, overriding the `get_session` dependency to use the `session` fixture.
37
-
-`test_user`: Creates a test user in the database with a predefined name, email, and hashed password.
39
+
-`test_organization`: Creates a test organization for use in tests.
38
40
39
41
To run the tests, use these commands:
40
42
41
-
- Run all tests: `pytest`
42
-
- Run tests in debug mode (includes logs and print statements in console output): `pytest -s`
43
-
- Run particular test files by name: `pytest <test_file_name>`
44
-
- Run particular tests by name: `pytest -k <test_name>`
43
+
- Run all tests: `uv run pytest`
44
+
- Run tests in debug mode (includes logs and print statements in console output): `uv run pytest -s`
45
+
- Run particular test files by name: `uv run pytest <test_file_name>`
46
+
- Run particular tests by name: `uv run pytest -k <test_name>`
45
47
46
48
### Type checking with mypy
47
49
@@ -72,11 +74,13 @@ We also create POST endpoints, which accept form submissions so the user can cre
72
74
#### Customizable folders and files
73
75
74
76
- FastAPI application entry point and homepage GET route: `main.py`
@@ -86,8 +90,8 @@ We also create POST endpoints, which accept form submissions so the user can cre
86
90
- Database helpers: `db.py`
87
91
- FastAPI dependencies: `dependencies.py`
88
92
- Enums: `enums.py`
89
-
- Database models: `models.py`
90
93
- Image helpers: `images.py`
94
+
- Database models: `models.py`
91
95
- Exceptions: `exceptions/`
92
96
- HTTP exceptions: `http_exceptions.py`
93
97
- Other custom exceptions: `exceptions.py`
@@ -99,7 +103,6 @@ We also create POST endpoints, which accept form submissions so the user can cre
99
103
- Website source: `index.qmd` + `docs/`
100
104
- Configuration: `_quarto.yml`
101
105
102
-
103
106
Most everything else is auto-generated and should not be manually modified.
104
107
105
108
## Backend
@@ -108,7 +111,7 @@ Most everything else is auto-generated and should not be manually modified.
108
111
109
112
The GET route for the homepage is defined in the main entry point for the application, `main.py`. The entrypoint imports router modules from the `routers/` directory, which contain the other GET and POST routes for the application. In CRUD style, the router modules are named after the resource they manage, e.g., `account.py` for account management.
110
113
111
-
We name our GET routes using the convention `read_<name>`, where `<name>` is the name of the page, to indicate that they are read-only endpoints that do not modify the database. In POST routes that modify the database, you can use the `get_session` dependency as an argument to get a database session.
114
+
We name our GET routes using the convention `read_<name>`, where `<name>` is the name of the resource, to indicate that they are read-only endpoints that do not modify the database. In POST routes that modify the database, you can use the `get_session` dependency as an argument to get a database session.
112
115
113
116
Routes that require authentication generally take the `get_authenticated_account` dependency as an argument. Unauthenticated GET routes generally take the `get_optional_user` dependency as an argument. If a route should *only* be seen by authenticated users (i.e., a login page), you can redirect to the dashboard if `get_optional_user` returns a `User` object.
114
117
@@ -120,6 +123,7 @@ Context refers to Python variables passed to a template to populate the HTML. In
120
123
@app.get("/welcome")
121
124
asyncdefwelcome(request: Request):
122
125
return templates.TemplateResponse(
126
+
request,
123
127
"welcome.html",
124
128
{"username": "Alice"}
125
129
)
@@ -176,11 +180,12 @@ SQLModel is an Object-Relational Mapping (ORM) library that allows us to interac
176
180
Our database models are defined in `utils/models.py`. Each model is a Python class that inherits from `SQLModel` and represents a database table. The key models are:
177
181
178
182
-`Account`: Represents a user account with email and password hash
179
-
-`User`: Represents a user profile with name, email, and avatar
183
+
-`User`: Represents a user profile with details like name and avatar; the email and password hash are stored in the related `Account` model
180
184
-`Organization`: Represents a company or team
181
185
-`Role`: Represents a set of permissions within an organization
182
186
-`Permission`: Represents specific actions a user can perform (defined by ValidPermissions enum)
183
187
-`PasswordResetToken`: Manages password reset functionality with expiration
188
+
-`EmailUpdateToken`: Manages email update confirmation functionality with expiration
184
189
185
190
Two additional models are used by SQLModel to manage many-to-many relationships; you generally will not need to interact with them directly:
0 commit comments