# fastapi-chameleon
Adds integration of the Chameleon template language to FastAPI. If you are interested in Jinja instead, see the sister project: [github.com/AGeekInside/fastapi-jinja](https://github.com/AGeekInside/fastapi-jinja).
## Installation
Simply `pip install fastapi_chameleon`.
## Usage
This is easy to use. Just create a folder within your web app to hold the templates such as:
```
├── main.py
├── views.py
│
├── templates
│ ├── home
│ │ └── index.pt
│ └── shared
│ └── layout.pt
```
In the app startup, tell the library about the folder you wish to use:
```python
import os
from pathlib import Path
import fastapi_chameleon
dev_mode = True
BASE_DIR = Path(__file__).resolve().parent
template_folder = str(BASE_DIR / 'templates')
fastapi_chameleon.global_init(template_folder, auto_reload=dev_mode)
```
Then just decorate the FastAPI view methods (works on sync and async methods):
```python
@router.post('/')
@fastapi_chameleon.template('home/index.pt')
async def home_post(request: Request):
form = await request.form()
vm = PersonViewModel(**form)
return vm.dict() # {'first':'Michael', 'last':'Kennedy', ...}
```
The view method should return a `dict` to be passed as variables/values to the template.
If a `fastapi.Response` is returned, the template is skipped and the response along with status_code and
other values is directly passed through. This is common for redirects and error responses not meant
for this page template.
## Friendly 404s and errors
A common technique for user-friendly sites is to use a
[custom HTML page for 404 responses](http://www.instantshift.com/2019/10/16/user-friendly-404-pages/).
This is especially important in FastAPI because FastAPI returns a 404 response + JSON by default.
This library has support for friendly 404 pages using the `fastapi_chameleon.not_found()` function.
Here's an example:
```python
@router.get('/catalog/item/{item_id}')
@fastapi_chameleon.template('catalog/item.pt')
async def item(item_id: int):
item = service.get_item_by_id(item_id)
if not item:
fastapi_chameleon.not_found()
return item.dict()
```
This will render a 404 response with using the template file `templates/errors/404.pt`.
You can specify another template to use for the response, but it's not required.
If you need to return errors other than `Not Found` (status code `404`), you can use a more
generic function: `fastapi_chameleon.generic_error(template_file: str, status_code: int)`.
This function will allow you to return different status codes. It's generic, thus you'll have
to pass a path to your error template file as well as a status code you want the user to get
in response. For example:
```python
@router.get('/catalog/item/{item_id}')
@fastapi_chameleon.template('catalog/item.pt')
async def item(item_id: int):
item = service.get_item_by_id(item_id)
if not item:
fastapi_chameleon.generic_error('errors/unauthorized.pt',
fastapi.status.HTTP_401_UNAUTHORIZED)
return item.dict()
```
Raw data
{
"_id": null,
"home_page": null,
"name": "fastapi_chameleon",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": "Chameleon, FastAPI, integration, template",
"author": null,
"author_email": "Michael Kennedy <michael@talkpython.fm>",
"download_url": "https://files.pythonhosted.org/packages/a4/93/9f117c81c1d4ee1d168b59abf49dafed23eb048f40d544e44cfa459b0790/fastapi_chameleon-0.1.16.tar.gz",
"platform": null,
"description": "# fastapi-chameleon\n\nAdds integration of the Chameleon template language to FastAPI. If you are interested in Jinja instead, see the sister project: [github.com/AGeekInside/fastapi-jinja](https://github.com/AGeekInside/fastapi-jinja).\n\n## Installation\n\nSimply `pip install fastapi_chameleon`.\n\n## Usage\n\nThis is easy to use. Just create a folder within your web app to hold the templates such as:\n\n```\n\u251c\u2500\u2500 main.py\n\u251c\u2500\u2500 views.py\n\u2502\n\u251c\u2500\u2500 templates\n\u2502 \u251c\u2500\u2500 home\n\u2502 \u2502 \u2514\u2500\u2500 index.pt\n\u2502 \u2514\u2500\u2500 shared\n\u2502 \u2514\u2500\u2500 layout.pt\n\n```\n\nIn the app startup, tell the library about the folder you wish to use:\n\n```python\nimport os\nfrom pathlib import Path\nimport fastapi_chameleon\n\ndev_mode = True\n\nBASE_DIR = Path(__file__).resolve().parent\ntemplate_folder = str(BASE_DIR / 'templates')\nfastapi_chameleon.global_init(template_folder, auto_reload=dev_mode)\n```\n\nThen just decorate the FastAPI view methods (works on sync and async methods):\n\n```python\n@router.post('/')\n@fastapi_chameleon.template('home/index.pt')\nasync def home_post(request: Request):\n form = await request.form()\n vm = PersonViewModel(**form) \n\n return vm.dict() # {'first':'Michael', 'last':'Kennedy', ...}\n\n```\n\nThe view method should return a `dict` to be passed as variables/values to the template. \n\nIf a `fastapi.Response` is returned, the template is skipped and the response along with status_code and\nother values is directly passed through. This is common for redirects and error responses not meant\nfor this page template.\n\n## Friendly 404s and errors\n\nA common technique for user-friendly sites is to use a \n[custom HTML page for 404 responses](http://www.instantshift.com/2019/10/16/user-friendly-404-pages/).\nThis is especially important in FastAPI because FastAPI returns a 404 response + JSON by default.\nThis library has support for friendly 404 pages using the `fastapi_chameleon.not_found()` function.\n\nHere's an example:\n\n```python\n@router.get('/catalog/item/{item_id}')\n@fastapi_chameleon.template('catalog/item.pt')\nasync def item(item_id: int):\n item = service.get_item_by_id(item_id)\n if not item:\n fastapi_chameleon.not_found()\n \n return item.dict()\n```\n\nThis will render a 404 response with using the template file `templates/errors/404.pt`.\nYou can specify another template to use for the response, but it's not required.\n\nIf you need to return errors other than `Not Found` (status code `404`), you can use a more\ngeneric function: `fastapi_chameleon.generic_error(template_file: str, status_code: int)`.\nThis function will allow you to return different status codes. It's generic, thus you'll have\nto pass a path to your error template file as well as a status code you want the user to get\nin response. For example:\n\n```python\n@router.get('/catalog/item/{item_id}')\n@fastapi_chameleon.template('catalog/item.pt')\nasync def item(item_id: int):\n item = service.get_item_by_id(item_id)\n if not item:\n fastapi_chameleon.generic_error('errors/unauthorized.pt',\n fastapi.status.HTTP_401_UNAUTHORIZED)\n\n return item.dict()\n```\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Adds integration of the Chameleon template language to FastAPI.",
"version": "0.1.16",
"project_urls": {
"Homepage": "https://github.com/mikeckennedy/fastapi-chameleon"
},
"split_keywords": [
"chameleon",
" fastapi",
" integration",
" template"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "bfc80e39a4fbf17f6d6cf9439e2a056cb49777cc0918893801eeb3564611a8c1",
"md5": "7ecc8ec84080edcc8ec2a08500cff457",
"sha256": "170d955d6ac59c1aa67d4a5dfa991fda9798988a73ce4f762d563b30ad4196d0"
},
"downloads": -1,
"filename": "fastapi_chameleon-0.1.16-py3-none-any.whl",
"has_sig": false,
"md5_digest": "7ecc8ec84080edcc8ec2a08500cff457",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 5737,
"upload_time": "2024-11-10T17:55:31",
"upload_time_iso_8601": "2024-11-10T17:55:31.468980Z",
"url": "https://files.pythonhosted.org/packages/bf/c8/0e39a4fbf17f6d6cf9439e2a056cb49777cc0918893801eeb3564611a8c1/fastapi_chameleon-0.1.16-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "a4939f117c81c1d4ee1d168b59abf49dafed23eb048f40d544e44cfa459b0790",
"md5": "dec88590718fbace13a2bb5e333cccc1",
"sha256": "65fd3b73265e045a57fac5d0ba6ef34a52a158f0c4395646adc4f1272bdc0595"
},
"downloads": -1,
"filename": "fastapi_chameleon-0.1.16.tar.gz",
"has_sig": false,
"md5_digest": "dec88590718fbace13a2bb5e333cccc1",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 6683,
"upload_time": "2024-11-10T17:55:33",
"upload_time_iso_8601": "2024-11-10T17:55:33.101942Z",
"url": "https://files.pythonhosted.org/packages/a4/93/9f117c81c1d4ee1d168b59abf49dafed23eb048f40d544e44cfa459b0790/fastapi_chameleon-0.1.16.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-11-10 17:55:33",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "mikeckennedy",
"github_project": "fastapi-chameleon",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"requirements": [],
"tox": true,
"lcname": "fastapi_chameleon"
}