Skip to content

Commit 2259f11

Browse files
Merge pull request #47 from Promptly-Technologies-LLC/28-populate-customization-page-on-documentation-website
28 populate customization page on documentation website
2 parents bebe165 + 8bac936 commit 2259f11

File tree

7 files changed

+468
-68
lines changed

7 files changed

+468
-68
lines changed

docs/customization.qmd

Lines changed: 281 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,284 @@
22
title: "Customization"
33
---
44

5+
## Development workflow
6+
7+
### Dependency management with Poetry
8+
9+
The project uses Poetry to manage dependencies:
10+
11+
- Add new dependency: `poetry add <dependency>`
12+
- Add development dependency: `poetry add --dev <dependency>`
13+
- Remove dependency: `poetry remove <dependency>`
14+
- Update lock file: `poetry lock`
15+
- Install dependencies: `poetry install`
16+
- Update all dependencies: `poetry update`
17+
18+
### Testing
19+
20+
The project uses Pytest for unit testing. It's highly recommended to write and run tests before committing code to ensure nothing is broken!
21+
22+
The following fixtures, defined in `tests/conftest.py`, are available in the test suite:
23+
24+
- `engine`: Creates a new SQLModel engine for the test database.
25+
- `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.
26+
- `session`: Provides a session for database operations in tests.
27+
- `clean_db`: Cleans up the database tables before each test by deleting all entries in the `PasswordResetToken` and `User` tables.
28+
- `client`: Provides a `TestClient` instance with the session fixture, overriding the `get_session` dependency to use the test session.
29+
- `test_user`: Creates a test user in the database with a predefined name, email, and hashed password.
30+
31+
To run the tests, use these commands:
32+
33+
- Run all tests: `pytest`
34+
- Run tests in debug mode (includes logs and print statements in console output): `pytest -s`
35+
- Run particular test files by name: `pytest <test_file_name>`
36+
- Run particular tests by name: `pytest -k <test_name>`
37+
38+
### Type checking with mypy
39+
40+
The project uses type annotations and mypy for static type checking. To run mypy, use this command from the root directory:
41+
42+
```bash
43+
mypy
44+
```
45+
46+
We find that mypy is an enormous time-saver, catching many errors early and greatly reducing time spent debugging unit tests. However, note that mypy requires you type annotate every variable, function, and method in your code base, so taking advantage of it is a lifestyle change!
47+
48+
## Project structure
49+
50+
### Customizable folders and files
51+
52+
- FastAPI application entry point and GET routes: `main.py`
53+
- FastAPI POST routes: `routers/`
54+
- User authentication endpoints: `auth.py`
55+
- User profile management endpoints: `user.py`
56+
- Organization management endpoints: `organization.py`
57+
- Role management endpoints: `role.py`
58+
- Jinja2 templates: `templates/`
59+
- Static assets: `static/`
60+
- Unit tests: `tests/`
61+
- Test database configuration: `docker-compose.yml`
62+
- Helper functions: `utils/`
63+
- Auth helpers: `auth.py`
64+
- Database helpers: `db.py`
65+
- Database models: `models.py`
66+
- Environment variables: `.env`
67+
- CI/CD configuration: `.github/`
68+
- Project configuration: `pyproject.toml`
69+
- Quarto documentation:
70+
- Source: `index.qmd` + `docs/`
71+
- Configuration: `_quarto.yml`
72+
73+
Most everything else is auto-generated and should not be manually modified.
74+
75+
### Defining a web backend with FastAPI
76+
77+
We use FastAPI to define the "API endpoints" of our application. An API endpoint is simply a URL that accepts user requests and returns responses. When a user visits a page, their browser sends what's called a "GET" request to an endpoint, and the server processes it (often querying a database), and returns a response (typically HTML). The browser renders the HTML, displaying the page.
78+
79+
We also create POST endpoints, which accept form submissions so the user can create, update, and delete data in the database. This template follows the Post-Redirect-Get (PRG) pattern to handle POST requests. When a form is submitted, the server processes the data and then returns a "redirect" response, which sends the user to a GET endpoint to re-render the page with the updated data. (See [Architecture](https://promptlytechnologies.com/fastapi-jinja2-postgres-webapp/docs/architecture.html) for more details.)
80+
81+
#### Routing patterns in this template
82+
83+
In this template, GET routes are defined in the main entry point for the application, `main.py`. POST routes are organized into separate modules within the `routers/` directory. 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.
84+
85+
We divide our GET routes into authenticated and unauthenticated routes, using commented section headers in our code that look like this:
86+
87+
```python
88+
# -- Authenticated Routes --
89+
```
90+
91+
Some of our routes take request parameters, which we pass as keyword arguments to the route handler. These parameters should be type annotated for validation purposes. Some parameters are shared across all authenticated or unauthenticated routes, so we define them in the `common_authenticated_parameters` and `common_unauthenticated_parameters` dependencies defined in `main.py`.
92+
93+
### HTML templating with Jinja2
94+
95+
To generate the HTML pages to be returned from our GET routes, we use Jinja2 templates. Jinja2's hierarchical templates allow creating a base template (`templates/base.html`) that defines the overall layout of our web pages (e.g., where the header, body, and footer should go). Individual pages can then extend this base template. We can also template reusable components that can be injected into our layout or page templates.
96+
97+
With Jinja2, we can use the `{% block %}` tag to define content blocks, and the `{% extends %}` tag to extend a base template. We can also use the `{% include %}` tag to include a component in a parent template. See the [Jinja2 documentation on template inheritance](https://jinja.palletsprojects.com/en/stable/templates/#template-inheritance) for more details.
98+
99+
#### Context variables
100+
101+
Context refers to Python variables passed to a template to populate the HTML. In a FastAPI GET route, we can pass context to a template using the `templates.TemplateResponse` method, which takes the request and any context data as arguments. For example:
102+
103+
```python
104+
@app.get("/welcome")
105+
async def welcome(request: Request):
106+
return templates.TemplateResponse(
107+
"welcome.html",
108+
{"username": "Alice"}
109+
)
110+
```
111+
112+
In this example, the `welcome.html` template will receive two pieces of context: the user's `request`, which is always passed automatically by FastAPI, and a `username` variable, which we specify as "Alice". We can then use the `{{ username }}` syntax in the `welcome.html` template (or any of its parent or child templates) to insert the value into the HTML.
113+
114+
#### Form validation strategy
115+
116+
While this template includes comprehensive server-side validation through Pydantic models and custom validators, it's important to note that server-side validation should be treated as a fallback security measure. If users ever see the `validation_error.html` template, it indicates that our client-side validation has failed to catch invalid input before it reaches the server.
117+
118+
Best practices dictate implementing thorough client-side validation via JavaScript and/or HTML `input` element `pattern` attributes to:
119+
- Provide immediate feedback to users
120+
- Reduce server load
121+
- Improve user experience by avoiding round-trips to the server
122+
- Prevent malformed data from ever reaching the backend
123+
124+
Server-side validation remains essential as a security measure against malicious requests that bypass client-side validation, but it should rarely be encountered during normal user interaction. See `templates/authentication/register.html` for a client-side form validation example involving both JavaScript and HTML regex `pattern` matching.
125+
126+
### Writing type annotated code
127+
128+
Pydantic is used for data validation and serialization. It ensures that the data received in requests meets the expected format and constraints. Pydantic models are used to define the structure of request and response data, making it easy to validate and parse JSON payloads.
129+
130+
If a user-submitted form contains data that has the wrong number, names, or types of fields, Pydantic will raise a `RequestValidationError`, which is caught by middleware and converted into an HTTP 422 error response.
131+
132+
For other, custom validation logic, we add Pydantic `@field_validator` methods to our Pydantic request models and then add the models as dependencies in the signatures of corresponding POST routes. FastAPI's dependency injection system ensures that dependency logic is executed before the body of the route handler.
133+
134+
#### Defining request models and custom validators
135+
136+
For example, in the `UserRegister` request model in `routers/authentication.py`, we add a custom validation method to ensure that the `confirm_password` field matches the `password` field. If not, it raises a custom `PasswordMismatchError`:
137+
138+
```python
139+
class PasswordMismatchError(HTTPException):
140+
def __init__(self, field: str = "confirm_password"):
141+
super().__init__(
142+
status_code=422,
143+
detail={
144+
"field": field,
145+
"message": "The passwords you entered do not match"
146+
}
147+
)
148+
149+
class UserRegister(BaseModel):
150+
name: str
151+
email: EmailStr
152+
password: str
153+
confirm_password: str
154+
155+
# Custom validators are added as class attributes
156+
@field_validator("confirm_password", check_fields=False)
157+
def validate_passwords_match(cls, v: str, values: dict[str, Any]) -> str:
158+
if v != values["password"]:
159+
raise PasswordMismatchError()
160+
return v
161+
# ...
162+
```
163+
164+
We then add this request model as a dependency in the signature of our POST route:
165+
166+
```python
167+
@app.post("/register")
168+
async def register(request: UserRegister = Depends()):
169+
# ...
170+
```
171+
172+
When the user submits the form, Pydantic will first check that all expected fields are present and match the expected types. If not, it raises a `RequestValidationError`. Then, it runs our custom `field_validator`, `validate_passwords_match`. If it finds that the `confirm_password` field does not match the `password` field, it raises a `PasswordMismatchError`. These exceptions can then be caught and handled by our middleware.
173+
174+
(Note that these examples are simplified versions of the actual code.)
175+
176+
#### Converting form data to request models
177+
178+
In addition to custom validation logic, we also need to define a method on our request models that converts form data into the request model. Here's what that looks like in the `UserRegister` request model from the previous example:
179+
180+
```python
181+
class UserRegister(BaseModel):
182+
# ...
183+
184+
@classmethod
185+
async def as_form(
186+
cls,
187+
name: str = Form(...),
188+
email: EmailStr = Form(...),
189+
password: str = Form(...),
190+
confirm_password: str = Form(...)
191+
):
192+
return cls(
193+
name=name,
194+
email=email,
195+
password=password,
196+
confirm_password=confirm_password
197+
)
198+
```
199+
200+
#### Middleware exception handling
201+
202+
Middlewares—which process requests before they reach the route handlers and responses before they are sent back to the client—are defined in `main.py`. They are commonly used in web development for tasks such as error handling, authentication token validation, logging, and modifying request/response objects.
203+
204+
This template uses middlewares exclusively for global exception handling; they only affect requests that raise an exception. This allows for consistent error responses and centralized error logging. Middleware can catch exceptions raised during request processing and return appropriate HTTP responses.
205+
206+
Middleware functions are decorated with `@app.exception_handler(ExceptionType)` and are executed in the order they are defined in `main.py`, from most to least specific.
207+
208+
Here's a middleware for handling the `PasswordMismatchError` exception from the previous example, which renders the `errors/validation_error.html` template with the error details:
209+
210+
```python
211+
@app.exception_handler(PasswordMismatchError)
212+
async def password_mismatch_exception_handler(request: Request, exc: PasswordMismatchError):
213+
return templates.TemplateResponse(
214+
request,
215+
"errors/validation_error.html",
216+
{
217+
"status_code": 422,
218+
"errors": {"error": exc.detail}
219+
},
220+
status_code=422,
221+
)
222+
```
223+
224+
### Database configuration and access with SQLModel
225+
226+
SQLModel is an Object-Relational Mapping (ORM) library that allows us to interact with our PostgreSQL database using Python classes instead of writing raw SQL. It combines the features of SQLAlchemy (a powerful database toolkit) with Pydantic's data validation.
227+
228+
#### Models and relationships
229+
230+
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:
231+
232+
- `Organization`: Represents a company or team
233+
- `User`: Represents a user account
234+
- `Role`: Represents a discrete set of user permissions within an organization
235+
- `Permission`: Represents specific actions a user can perform
236+
- `RolePermissionLink`: Maps roles to their allowed permissions
237+
- `PasswordResetToken`: Manages password reset functionality
238+
239+
Here's an entity-relationship diagram (ERD) of the current database schema, automatically generated from our SQLModel definitions:
240+
241+
```{python}
242+
#| echo: false
243+
#| warning: false
244+
import sys
245+
sys.path.append("..")
246+
from utils.models import *
247+
from utils.db import engine
248+
from sqlalchemy import MetaData
249+
from sqlalchemy_schemadisplay import create_schema_graph
250+
251+
# Create the directed graph
252+
graph = create_schema_graph(
253+
engine=engine,
254+
metadata=SQLModel.metadata,
255+
show_datatypes=True,
256+
show_indexes=True,
257+
rankdir='TB',
258+
concentrate=False
259+
)
260+
261+
# Save the graph
262+
graph.write_png('static/schema.png')
263+
```
264+
265+
![Database Schema](static/schema.png)
266+
267+
268+
#### Database operations
269+
270+
Database operations are handled by helper functions in `utils/db.py`. Key functions include:
271+
272+
- `set_up_db()`: Initializes the database schema and default data (which we do on every application start in `main.py`)
273+
- `get_connection_url()`: Creates a database connection URL from environment variables in `.env`
274+
- `get_session()`: Provides a database session for performing operations
275+
276+
To perform database operations in route handlers, inject the database session as a dependency:
277+
278+
```python
279+
@app.get("/users")
280+
async def get_users(session: Session = Depends(get_session)):
281+
users = session.exec(select(User)).all()
282+
return users
283+
```
284+
285+
The session automatically handles transaction management, ensuring that database operations are atomic and consistent.

docs/static/schema.png

52.4 KB
Loading

migrations/set_up_db.py

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

0 commit comments

Comments
 (0)