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

new: manage shorthand routes #18

Merged
merged 9 commits into from
Jul 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 3 additions & 1 deletion .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ jobs:
with:
python-version: '3.x'
- name: Install deps
run: python3 -m pip install -U pip wheel twine setuptools
run: |
python3 -m pip install -U pip wheel twine setuptools
pip install -U -r requirements.txt
- name: Build package
run: python3 setup.py sdist bdist_wheel
- name: Upload package
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
2024-07-16 TROUVERIE Joachim <jtrouverie@joakode.fr>
* v0.8
* new: manage shorthand routes
2024-07-10 TROUVERIE Joachim <jtrouverie@joakode.fr>
* v0.7
* new: manage external redirects with server side initiated `window.location` visit.
Expand Down
4 changes: 2 additions & 2 deletions docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
sphinx==4.5.0
sphinx>=7.0.0
vue-lexer==0.0.4
pallets-sphinx-themes==2.0.3
pallets-sphinx-themes>=2.0.0
Flask>=1.1.2
jsmin>=2.2.2
10 changes: 7 additions & 3 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,25 @@

# -- Path setup --------------------------------------------------------------

import os.path as op
import sys

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os.path as op
import sys
from datetime import datetime

sys.path.insert(0, op.abspath(op.dirname(op.dirname(op.dirname(__file__)))))

from flask_inertia import __version__ # noqa: E402

# -- Project information -----------------------------------------------------

today = datetime.today()

project = "flask-inertia"
copyright = "2021, TROUVERIE Joachim"
copyright = f"{today.year}, TROUVERIE Joachim"
author = "TROUVERIE Joachim"

# The full version, including alpha/beta/rc tags
Expand Down
28 changes: 27 additions & 1 deletion docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,38 @@ of Flask ``render_template`` method::

This method take 3 arguments:

* ``component_name``: Your frontend component name (eg "Index" for an Index.vue
* ``component_name``: Your frontend component name (e.g. "Index" for an Index.vue
Component for example)
* ``props``: [OPTIONAL] Data used by your component
* ``view_data``: [OPTIONAL] Data used in your template but not sent to your JavaScript
components

Shorthand routes
++++++++++++++++

If you have a page that does not need a corresponding controller method (i.e. a frontend
component which does not need ``props`` nor ``view_data``), like a "FAQ" or "about" page,
you can route directly to a component via the ``add_shorthand_route`` method::

from flask import Flask
from flask_inertia import Inertia

app = Flask(__name__)
app.config.from_object(__name__)
inertia = Inertia(app)

inertia.add_shorthand_route("/faq/", "FAQ")
inertia.add_shorthand_route("/about/", "About", "My About Page")


This method takes 3 arguments:

* ``url``: The URL rule as string as used in ``flask.add_url_rule``
* ``component_name``: Your frontend component name (e.g. "Index" for an Index.vue
Component for example)
* ``endpoint`` [OPTIONAL]: The endpoint for the registered URL rule. (by default the
``component_name`` in lower case)

Root template data
++++++++++++++++++

Expand Down
2 changes: 1 addition & 1 deletion flask_inertia/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@
from flask_inertia.views import inertia_location, render_inertia

__all__ = ["Inertia", "render_inertia", "inertia_location"]
__version__ = "0.7"
__version__ = "0.8"
25 changes: 25 additions & 0 deletions flask_inertia/inertia.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,14 @@
from werkzeug.exceptions import BadRequest

from flask_inertia.version import get_asset_version
from flask_inertia.views import render_inertia


class Inertia:
"""Inertia Plugin for Flask."""

def __init__(self, app: Optional[Flask] = None):
self.app = None
if app is not None:
self.init_app(app)

Expand All @@ -57,6 +59,7 @@ def init_app(self, app: Flask):
* Register after_request hook
* Set context processor to have an `inertia` value in templates
"""
self.app = app
self._shared_data = {}
if not hasattr(app, "extensions"):
app.extensions = {}
Expand Down Expand Up @@ -166,3 +169,25 @@ def include_router(self) -> Markup:
content_minified = jsmin(content)

return Markup(content_minified)

def add_shorthand_route(
self, url: str, component_name: str, endpoint: Optional[str] = None
) -> None:
"""Connect a URL rule to a frontend component that does not need a controller.

This url does not have dedicated python source code but is linked to a JS component,
(i.e. a frontend component which does not need props nor view_data).

:param url: The URL rule as string as used in ``flask.add_url_rule``
:param component_name: Your frontend component name
:param endpoint: The endpoint for the registered URL rule. (by default
``component_name`` in lower case)
"""
if not self.app:
raise RuntimeError("Extension has not been initialized correctly.")

self.app.add_url_rule(
url,
endpoint or component_name.lower(),
lambda: render_inertia(component_name),
)
24 changes: 23 additions & 1 deletion tests/python/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ def setUp(self):
self.app.add_url_rule("/meta/", "meta", meta)

self.inertia = Inertia(self.app)
self.inertia.add_shorthand_route("/faq/", "FAQ")
self.inertia.add_shorthand_route("/about/", "About", "about page")

self.client = self.app.test_client()

Expand All @@ -95,6 +97,15 @@ def test_extension_init(self):
self.assertIsNotNone(app.extensions)
self.assertIn("inertia", app.extensions)

def test_bad_extension_init(self):
inertia = Inertia()
with self.assertRaises(RuntimeError) as ctx:
inertia.add_shorthand_route("/faq/", "FAQ")

self.assertIn(
"Extension has not been initialized correctly", str(ctx.exception)
)

def test_bad_request(self):
headers = {
"X-Requested-With": "XMLHttpRequest",
Expand Down Expand Up @@ -205,7 +216,7 @@ def test_partial_loading_with_comma_separated_props_in_partial_data_header(self)
def test_include_router(self):
response = self.client.get("/")
self.assertIn(
b'window.routes={"external":"/external/","index":"/","meta":"/meta/","partial":"/partial/","static":"/static/<path:filename>","users":"/users/"}',
b'window.routes={"about page":"/about/","external":"/external/","faq":"/faq/","index":"/","meta":"/meta/","partial":"/partial/","static":"/static/<path:filename>","users":"/users/"}',
response.data,
)

Expand Down Expand Up @@ -246,6 +257,10 @@ def test_backend_redirect(self):
"http://foobar.com/", response.headers["X-Inertia-Location"]
)

def test_shorthand_route(self):
response = self.client.get("/faq/")
self.assertEqual(response.status_code, HTTPStatus.OK)


class TestInertiaTestUtils(unittest.TestCase):
"""Flask-Inertia tests."""
Expand All @@ -261,6 +276,7 @@ def setUp(self):
self.app.add_url_rule("/meta/", "meta", meta)

self.inertia = Inertia(self.app)
self.inertia.add_shorthand_route("/faq/", "FAQ")

self.app.response_class = InertiaTestResponse
self.client = self.app.test_client()
Expand Down Expand Up @@ -340,6 +356,12 @@ def view_data_not_in_js_context(self):
data = response.inertia("app")
self.assertFalse(hasattr(data.props, "description"))

def test_shorthand_route(self):
response = self.client.get("/faq/")
data = response.inertia("app")
self.assertEqual(response.status_code, HTTPStatus.OK)
self.assertEqual(data.component, "FAQ")


if __name__ == "__main__":
unittest.main()