Skip to content

Commit

Permalink
Feat/introduce jinja2 (#23)
Browse files Browse the repository at this point in the history
- Introduces Jinja templates instead of raw HTML string
- Bump version to 1.0.0
- Remove support for deprecated features
  • Loading branch information
hxjo authored Jul 18, 2024
1 parent 4a98c1e commit 0f422ca
Show file tree
Hide file tree
Showing 29 changed files with 671 additions and 965 deletions.
Binary file modified .coverage
Binary file not shown.
14 changes: 13 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,20 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.0.0] - 2024-07-18

- [BREAKING CHANGE] Introduce templating via Jinja2 instead of a raw HTML string
- For migration guide, see [the migration guide](./DEPRECATION_AND_MIGRATION_GUIDE.md#use-jinja2-template-instead-of-a-raw-html-string)
- [BREAKING CHANGE] Remove deprecated use of `requests`
- For migration guide, see [the migration guide](./DEPRECATION_AND_MIGRATION_GUIDE.md#requests-package-for-ssr)
- [BREAKING CHANGE] Remove deprecated use of `use_typescript`
- For migration guide, see [the migration guide](./DEPRECATION_AND_MIGRATION_GUIDE.md#use_typescript-configuration-option)

## [0.1.7] - 2024-07-18

- Deprecate `requests` package for SSR in favour of `httpx` package
- Removed in 1.0.0
- For migration guide, see [the migration guide](./DEPRECATION_AND_MIGRATION_GUIDE.md#requests-package-for-ssr)
- Test for deprecation warning for `httpx` package and `use_typescript` configuration option

## [0.1.6] - 2024-07-17
Expand All @@ -16,7 +27,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Better type vite manifest
- Allow for multiple css files to be in the manifest file
- Deprecate `use_typescript` in favour of `entrypoint_filename` in InertiaConfig
- Will be removed in 1.0.0
- Removed in 1.0.0
- For migration guide, see [the migration guide](./DEPRECATION_AND_MIGRATION_GUIDE.md#use_typescript-configuration-option)
- Introduce root_directory to InertiaConfig instead of assuming it
- Introduce assets_prefix to InertiaConfig instead of assuming it

Expand Down
49 changes: 49 additions & 0 deletions DEPRECATION_AND_MIGRATION_GUIDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Deprecated features and migration guide

- [Deprecated features and migration guide](#deprecated-features-and-migration-guide)
- [`use_typescript` configuration option](#use_typescript-configuration-option)
- [Migration guide](#migration-guide)
- [`requests` package for SSR](#requests-package-for-ssr)
- [Migration guide](#migration-guide-1)
- [Use Jinja2 Template instead of a raw HTML string](#use-jinja2-template-instead-of-a-raw-html-string)
- [Migration guide](#migration-guide-2)

> [!WARNING]
> The items mentioned in this part are deprecated and will be removed in a future version.
## `use_typescript` configuration option

The `use_typescript` configuration option has been deprecated in favour of `entrypoint_filename`.
It has been done for the following reason(s):

- To ensure library users are not restricted to the `main.{ext}` pattern when it comes to the entrypoint

### Migration guide

- Remove the `use_typescript` from your configuration options
- Add the `entrypoint_filename` option to the configuration ; the value would be `main.ts` if it is your webapp entrypoint's filename.

## `requests` package for SSR

The `requests` package requirement has been changed for a `httpx` package requirement.
It has been done for the following reason(s):

- To leverage the async capabilities of httpx.AsyncClient

### Migration guide

- Install the `httpx` package
- (Optionally, if not used elsewhere in your application) Remove the `requests` package

## Use Jinja2 Template instead of a raw HTML string

Remove the usage of raw HTML strings in favour of Jinja2Templates.
It has been done for the following reason(s):

- So that library users can customize the HTML more easily, without having to override the Inertia object.

### Migration guide

- Create a Jinja2Templates instance, for example one from `fastapi.templating.Jinja2Templates`. Ensure you have a valid inertia template in the directory given to the instance.
- Pass this instance to the InertiaConfig, under the `templates` key
- Pass the inertia template filename to the InertiaConfig, under the `root_template_filename` key
81 changes: 34 additions & 47 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,9 @@
- [Inertia.js FastAPI Adapter](#inertiajs-fastapi-adapter)
- [Installation](#installation)
- [Configuration](#configuration)
- [Deprecated features and migration guide](#deprecated-features-and-migration-guide)
- [`use_typescript` configuration option](#use_typescript-configuration-option)
- [Migration guide](#migration-guide)
- [`requests` package for SSR](#requests-package-for-ssr)
- [Migration guide](#migration-guide-1)
- [Examples](#examples)
- [Usage](#usage)
- [Create a Jinja2Template](#create-a-jinja2template)
- [Set up the dependency](#set-up-the-dependency)
- [Rendering a page](#rendering-a-page)
- [Rendering assets](#rendering-assets)
Expand Down Expand Up @@ -39,58 +35,49 @@ pip install fastapi-inertia
You can configure the adapter by passing a `InertiaConfig` object to the `Inertia` class.
The following options are available:

| key | default | options | description |
| ------------------- | ---------------------- | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| environment | development | development,production | The environment to use |
| version | 1.0.0 | Any valid string | The version of your server |
| json_encoder | InertiaJsonEncoder | Any class that extends json.JSONEncoder | The JSON encoder used to encode page data when HTML is returned |
| manifest_json_path | "" | Any valid path | The path to the manifest.json file. Needed in production |
| dev_url | http://localhost:5173 | Any valid url | The URL to the development server |
| ssr_url | http://localhost:13714 | Any valid url | The URL to the SSR server |
| ssr_enabled | False | True,False | Whether to [enable SSR](#enable-ssr). You need to install the `httpx` package, to have set the manifest_json_path and started the SSR server |
| root_directory | src | Any valid path | The directory in which is located the javascript code in your frontend. Will be used to find the relevant files in your manifest.json. |
| entrypoint_filename | main.js | Any valid file | The entrypoint for you frontend. Will be used to find the relevant files in your manifest.json. |
| assets_prefix | "" | Any valid string | An optional prefix for your assets. Will prefix the links generated from the assets mentioned in manifest.json. |
| use_typescript | False | True,False | Whether to use TypeScript |
| use_flash_messages | False | True,False | Whether to use [flash messages](#flash-messages). You need to use Starlette's SessionMiddleware to use this feature |
| flash_message_key | messages | Any valid string | The key to use for [flash errors](#flash-errors) |
| use_flash_errors | False | True,False | Whether to use flash errors |
| flash_error_key | errors | Any valid string | The key to use for flash errors |
| key | default | options | description |
| ---------------------- | ---------------------- | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| environment | development | development,production | The environment to use |
| version | 1.0.0 | Any valid string | The version of your server |
| json_encoder | InertiaJsonEncoder | Any class that extends json.JSONEncoder | The JSON encoder used to encode page data when HTML is returned |
| manifest_json_path | "" | Any valid path | The path to the manifest.json file. Needed in production |
| dev_url | http://localhost:5173 | Any valid url | The URL to the development server |
| ssr_url | http://localhost:13714 | Any valid url | The URL to the SSR server |
| ssr_enabled | False | True,False | Whether to [enable SSR](#enable-ssr). You need to install the `httpx` package, to have set the manifest_json_path and started the SSR server |
| root_directory | src | Any valid path | The directory in which is located the javascript code in your frontend. Will be used to find the relevant files in your manifest.json. |
| entrypoint_filename | main.js | Any valid file | The entrypoint for you frontend. Will be used to find the relevant files in your manifest.json. |
| assets_prefix | "" | Any valid string | An optional prefix for your assets. Will prefix the links generated from the assets mentioned in manifest.json. |
| use_flash_messages | False | True,False | Whether to use [flash messages](#flash-messages). You need to use Starlette's SessionMiddleware to use this feature |
| flash_message_key | messages | Any valid string | The key to use for [flash errors](#flash-errors) |
| use_flash_errors | False | True,False | Whether to use flash errors |
| flash_error_key | errors | Any valid string | The key to use for flash errors |
| templates | None | A Jinja2Templates instance | The templates instance in which Inertia will look for the `root_template_filename` template |
| root_template_filename | index.html | Any valid jinja2 template file | The file which will be used to render your inertia application |

## Deprecated features and migration guide

> [!WARNING]
> The items mentioned in this part are deprecated and will be removed in a future version.
### `use_typescript` configuration option

The `use_typescript` configuration option has been deprecated in favour of `entrypoint_filename`.
It has been done for the following reason(s):

- To ensure library users are not restricted to the `main.{ext}` pattern when it comes to the entrypoint

#### Migration guide
## Examples

- Remove the `use_typescript` from your configuration options
- Add the `entrypoint_filename` option to the configuration ; the value would be `main.ts` if it is your webapp entrypoint's filename.
You can see different full examples in the [following repository](https://github.com/hxjo/fastapi-inertia-examples).

### `requests` package for SSR
## Usage

The `requests` package requirement has been changed for a `httpx` package requirement.
It has been done for the following reason(s):
### Create a Jinja2Template

- To leverage the async capabilities of httpx.AsyncClient
In order to use the Inertia.js adapter, you have to create a Jinja2Template that the library will use.

#### Migration guide
It **must** have both an `inertia_head` and an `inertia_body` tag in it.

- Install the `httpx` package
- (Optionally, if not used elsewhere in your application) Remove the `requests` package
- `inertia_head` is where the library will place the code that supposedly goes inside the HTML `head` tag
- `inertia_body` is where the library will place the code that supposedly goes inside the HTML `body` tag

## Examples
You can find the simplest example in `inertia/tests/templates/index.html`.
You should then register the folder in which you put this file as the directory of your Jinja2Templates

You can see different full examples in the [following repository](https://github.com/hxjo/fastapi-inertia-examples).
```python
templates = Jinja2Templates(directory=template_dir)
```

## Usage
This option should be passed to the InertiaConfig class presented below, under the `templates` key.
If you choose a different template file name than `index.html`, you can also pass the `root_template_filename` key with, as value, your template file name.

### Set up the dependency

Expand Down
2 changes: 2 additions & 0 deletions inertia/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
)
from .config import InertiaConfig
from .utils import lazy
from .templating import InertiaExtension

__all__ = [
"InertiaResponse",
Expand All @@ -16,4 +17,5 @@
"InertiaVersionConflictException",
"InertiaConfig",
"lazy",
"InertiaExtension",
]
39 changes: 5 additions & 34 deletions inertia/config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from functools import lru_cache
import json
from typing import Literal, Type, Optional, TypedDict, Dict, Union, cast
import warnings
from typing import Literal, Type
from json import JSONEncoder

from fastapi.templating import Jinja2Templates
from .utils import InertiaJsonEncoder
from dataclasses import dataclass

Expand All @@ -13,6 +12,7 @@ class InertiaConfig:
Configuration class for Inertia
"""

templates: Jinja2Templates
environment: Literal["development", "production"] = "development"
version: str = "1.0"
json_encoder: Type[JSONEncoder] = InertiaJsonEncoder
Expand All @@ -21,39 +21,10 @@ class InertiaConfig:
ssr_enabled: bool = False
manifest_json_path: str = ""
root_directory: str = "src"
root_template_filename: str = "index.html"
entrypoint_filename: str = "main.js"
use_flash_messages: bool = False
use_flash_errors: bool = False
flash_message_key: str = "messages"
flash_error_key: str = "errors"
assets_prefix: str = ""
use_typescript: Union[bool, None] = None

def __post_init__(self) -> None:
if self.use_typescript is not None:
warnings.warn(
"use_typescript is deprecated: Please use entrypoint_filename instead. It will be removed in 1.0.0",
DeprecationWarning,
stacklevel=2,
)
self.entrypoint_filename = "main.ts" if self.use_typescript else "main.js"


class ViteManifestChunk(TypedDict):
file: str
src: Optional[str]
isEntry: Optional[bool]
isDynamicEntry: Optional[bool]
dynamicImports: Optional[list[str]]
css: Optional[list[str]]
assets: Optional[list[str]]
imports: Optional[list[str]]


ViteManifest = Dict[str, ViteManifestChunk]


@lru_cache
def _read_manifest_file(path: str) -> ViteManifest:
with open(path, "r") as manifest_file:
return cast(ViteManifest, json.load(manifest_file))
Loading

0 comments on commit 0f422ca

Please sign in to comment.