This is an automated email from the ASF dual-hosted git repository.
sbp pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-release.git
The following commit(s) were added to refs/heads/main by this push:
new 13bbd01 Allow route functions to be used to construct URLs in
templates
13bbd01 is described below
commit 13bbd017d68f0a88290912e1491f579e235bf7d7
Author: Sean B. Palmer <[email protected]>
AuthorDate: Wed Mar 26 16:44:06 2025 +0200
Allow route functions to be used to construct URLs in templates
---
atr/routes/__init__.py | 149 +++++++++++++++-
atr/routes/candidate_draft.py | 232 +++++++------------------
atr/server.py | 34 +---
atr/templates/candidate-draft-add-project.html | 2 +-
atr/templates/candidate-draft-add.html | 4 +-
atr/templates/candidate-draft-check.html | 2 +-
atr/templates/candidate-draft-list.html | 10 +-
atr/templates/candidate-draft-tools.html | 8 +-
atr/templates/includes/sidebar.html | 2 +-
atr/util.py | 8 +-
docs/conventions.html | 2 +-
docs/conventions.md | 2 +-
12 files changed, 239 insertions(+), 216 deletions(-)
diff --git a/atr/routes/__init__.py b/atr/routes/__init__.py
index 9872888..f43464b 100644
--- a/atr/routes/__init__.py
+++ b/atr/routes/__init__.py
@@ -15,18 +15,30 @@
# specific language governing permissions and limitations
# under the License.
+from __future__ import annotations
+
import asyncio
import functools
import logging
import time
-from collections.abc import Awaitable, Callable, Coroutine
-from typing import Any, Final, ParamSpec, TypeVar
+from typing import TYPE_CHECKING, Any, Final, NoReturn, ParamSpec, Protocol,
TypeVar
import aiofiles
import aiofiles.os
import asfquart
+import asfquart.auth as auth
+import asfquart.base as base
+import asfquart.session as session
import quart
-import werkzeug.datastructures as datastructures
+
+if TYPE_CHECKING:
+ from collections.abc import Awaitable, Callable, Coroutine
+ from types import ModuleType
+
+ import werkzeug.datastructures as datastructures
+
+import atr.db.models as models
+import atr.user as user
if asfquart.APP is ...:
raise RuntimeError("APP is not set")
@@ -156,7 +168,7 @@ route_logger.setLevel(logging.INFO)
route_logger.propagate = False
-def app_route(path: str, methods: list[str] | None = None) -> Callable:
+def app_route(path: str, methods: list[str] | None = None, endpoint: str |
None = None) -> Callable:
"""Register a route with the Flask app with built-in performance
logging."""
def decorator(f: Callable[P, Coroutine[Any, Any, T]]) -> Callable[P,
Awaitable[T]]:
@@ -166,7 +178,7 @@ def app_route(path: str, methods: list[str] | None = None)
-> Callable:
else:
measured_func = f
# Then apply the original route decorator
- return asfquart.APP.route(path, methods=methods)(measured_func)
+ return asfquart.APP.route(path, methods=methods,
endpoint=endpoint)(measured_func)
return decorator
@@ -294,3 +306,130 @@ async def get_form(request: quart.Request) ->
datastructures.MultiDict:
if blockbuster is not None:
blockbuster.activate()
return form
+
+
+R = TypeVar("R", covariant=True)
+
+
+# This is the type of functions to which we apply @committer_get
+# In other words, functions which accept CommitterSession as their first arg
+class CommitterRouteHandler(Protocol[R]):
+ """Protocol for @committer_get decorated functions."""
+
+ __name__: str
+ __doc__: str | None
+
+ def __call__(self, session: CommitterSession, *args: Any, **kwargs: Any)
-> Awaitable[R]: ...
+
+
+class CommitterSession:
+ """Session with extra information about committers."""
+
+ def __init__(self, web_session: session.ClientSession) -> None:
+ self._projects: list[models.Project] | None = None
+ self._session = web_session
+
+ def __getattr__(self, name: str) -> Any:
+ # TODO: Not type safe, should subclass properly if possible
+ # For example, we can access session.no_such_attr and the type
checkers won't notice
+ return getattr(self._session, name)
+
+ @property
+ def host(self) -> str:
+ request_host = quart.request.host
+ if ":" in request_host:
+ domain, port = request_host.split(":")
+ # Could be an IPv6 address, so need to check whether port is a
valid integer
+ if port.isdigit():
+ return domain
+ return request_host
+
+ @property
+ async def user_candidate_drafts(self) -> list[models.Release]:
+ return await user.candidate_drafts(self.uid,
user_projects=self._projects)
+
+ @property
+ async def user_projects(self) -> list[models.Project]:
+ if self._projects is None:
+ self._projects = await user.projects(self.uid)
+ return self._projects
+
+ @property
+ async def user_releases(self) -> list[models.Release]:
+ return await user.releases(self.uid)
+
+
+# This is the type of functions to which we apply @app_route
+# In other words, functions which accept no session
+class RouteHandler(Protocol[R]):
+ """Protocol for @app_route decorated functions."""
+
+ __name__: str
+ __doc__: str | None
+
+ def __call__(self, *args: Any, **kwargs: Any) -> Awaitable[R]: ...
+
+
+# This decorator is an adaptor between @committer_get and @app_route functions
+def committer_route(
+ path: str, methods: list[str] | None = None
+) -> Callable[[CommitterRouteHandler[R]], RouteHandler[R]]:
+ """Decorator for committer GET routes that provides an enhanced session
object."""
+
+ def decorator(func: CommitterRouteHandler[R]) -> RouteHandler[R]:
+ async def wrapper(*args: Any, **kwargs: Any) -> R:
+ web_session = await session.read()
+ if web_session is None:
+ _authentication_failed()
+
+ enhanced_session = CommitterSession(web_session)
+ return await func(enhanced_session, *args, **kwargs)
+
+ # Generate a unique endpoint name
+ endpoint = func.__module__ + "_" + func.__name__
+
+ # Set the name before applying decorators
+ wrapper.__name__ = func.__name__
+ wrapper.__doc__ = func.__doc__
+ wrapper.__annotations__["endpoint"] = endpoint
+
+ # Apply decorators in reverse order
+ decorated = auth.require(auth.Requirements.committer)(wrapper)
+ decorated = app_route(path, methods=methods or ["GET"],
endpoint=endpoint)(decorated)
+
+ return decorated
+
+ return decorator
+
+
+def _authentication_failed() -> NoReturn:
+ """Handle authentication failure with an exception."""
+ # NOTE: This is a separate function to fix a problem with analysis flow in
mypy
+ raise base.ASFQuartException("Not authenticated", errorcode=401)
+
+
+def modules() -> dict[str, ModuleType]:
+ """Return a dictionary of all modules in the current package."""
+ import atr.routes.candidate as candidate
+ import atr.routes.candidate_draft as candidate_draft
+ import atr.routes.committees as committees
+ import atr.routes.dev as dev
+ import atr.routes.docs as docs
+ import atr.routes.download as download
+ import atr.routes.keys as keys
+ import atr.routes.projects as projects
+ import atr.routes.release as release
+ import atr.routes.root as root
+
+ return {
+ "candidate": candidate,
+ "candidate_draft": candidate_draft,
+ "committees": committees,
+ "dev": dev,
+ "docs": docs,
+ "download": download,
+ "keys": keys,
+ "projects": projects,
+ "release": release,
+ "root": root,
+ }
diff --git a/atr/routes/candidate_draft.py b/atr/routes/candidate_draft.py
index 5b91b84..2de0b94 100644
--- a/atr/routes/candidate_draft.py
+++ b/atr/routes/candidate_draft.py
@@ -25,12 +25,11 @@ import hashlib
import logging
import pathlib
import re
-from typing import TYPE_CHECKING, Any, Final, NoReturn, Protocol, TypeVar
+import sys
+from typing import Final
import aiofiles.os
-import asfquart.auth as auth
import asfquart.base as base
-import asfquart.session as session
import quart
import werkzeug.datastructures as datastructures
import werkzeug.wrappers.response as response
@@ -41,77 +40,12 @@ import atr.db as db
import atr.db.models as models
import atr.routes as routes
import atr.tasks as tasks
-import atr.user as user
import atr.util as util
-if TYPE_CHECKING:
- from collections.abc import Awaitable, Callable
-
-R = TypeVar("R", covariant=True)
-
# _CONFIG: Final = config.get()
_LOGGER: Final = logging.getLogger(__name__)
-# This is the type of functions to which we apply @committer_get
-# In other words, functions which accept CommitterSession as their first arg
-class CommitterRouteHandler(Protocol[R]):
- """Protocol for @committer_get decorated functions."""
-
- __name__: str
- __doc__: str | None
-
- def __call__(self, session: CommitterSession, *args: Any, **kwargs: Any)
-> Awaitable[R]: ...
-
-
-class CommitterSession:
- """Session with extra information about committers."""
-
- def __init__(self, web_session: session.ClientSession) -> None:
- self._projects: list[models.Project] | None = None
- self._session = web_session
-
- def __getattr__(self, name: str) -> Any:
- # TODO: Not type safe, should subclass properly if possible
- # For example, we can access session.no_such_attr and the type
checkers won't notice
- return getattr(self._session, name)
-
- @property
- def host(self) -> str:
- request_host = quart.request.host
- if ":" in request_host:
- domain, port = request_host.split(":")
- # Could be an IPv6 address, so need to check whether port is a
valid integer
- if port.isdigit():
- return domain
- return request_host
-
- @property
- async def user_candidate_drafts(self) -> list[models.Release]:
- return await user.candidate_drafts(self.uid,
user_projects=self._projects)
-
- @property
- async def user_projects(self) -> list[models.Project]:
- if self._projects is None:
- self._projects = await user.projects(self.uid)
- return self._projects
-
- @property
- async def user_releases(self) -> list[models.Release]:
- return await user.releases(self.uid)
-
-
-# This is the type of functions to which we apply @app_route
-# In other words, functions which accept no session
-class RouteHandler(Protocol[R]):
- """Protocol for @app_route decorated functions."""
-
- __name__: str
- __doc__: str | None
-
- def __call__(self, *args: Any, **kwargs: Any) -> Awaitable[R]: ...
-
-
class FilesAddOneForm(util.QuartFormTyped):
"""Form for adding a single file to a release candidate."""
@@ -120,12 +54,6 @@ class FilesAddOneForm(util.QuartFormTyped):
submit = wtforms.SubmitField("Add file")
-def _authentication_failed() -> NoReturn:
- """Handle authentication failure with an exception."""
- # NOTE: This is a separate function to fix a problem with analysis flow in
mypy
- raise base.ASFQuartException("Not authenticated", errorcode=401)
-
-
async def _number_of_release_files(release: models.Release) -> int:
"""Return the number of files in the release."""
path_project = release.project.name
@@ -226,36 +154,8 @@ def _path_warnings_errors_metadata(
return warnings, errors
-# This decorator is an adaptor between @committer_get and @app_route functions
-def committer_route(
- path: str, methods: list[str] | None = None
-) -> Callable[[CommitterRouteHandler[R]], RouteHandler[R]]:
- """Decorator for committer GET routes that provides an enhanced session
object."""
-
- def decorator(func: CommitterRouteHandler[R]) -> RouteHandler[R]:
- async def wrapper(*args: Any, **kwargs: Any) -> R:
- web_session = await session.read()
- if web_session is None:
- _authentication_failed()
-
- enhanced_session = CommitterSession(web_session)
- return await func(enhanced_session, *args, **kwargs)
-
- # Set the name before applying decorators
- wrapper.__name__ = func.__name__
- wrapper.__doc__ = func.__doc__
-
- # Apply decorators in reverse order
- decorated = auth.require(auth.Requirements.committer)(wrapper)
- decorated = routes.app_route(path, methods=methods or
["GET"])(decorated)
-
- return decorated
-
- return decorator
-
-
-@committer_route("/candidate/draft/add")
-async def root_candidate_draft_add(session: CommitterSession) -> str:
[email protected]_route("/candidate/draft/add")
+async def add(session: routes.CommitterSession) -> str:
"""Show a page to allow the user to rsync files to candidate drafts."""
# Do them outside of the template rendering call to ensure order
# The user_candidate_drafts call can use cached results from user_projects
@@ -269,6 +169,7 @@ async def root_candidate_draft_add(session:
CommitterSession) -> str:
server_domain=session.host,
number_of_release_files=_number_of_release_files,
candidate_drafts=user_candidate_drafts,
+ candidate_draft=sys.modules[__name__],
)
@@ -300,9 +201,9 @@ async def _add_one(
await f.write(chunk)
-@committer_route("/candidate/draft/add/<project_name>/<version_name>",
methods=["GET", "POST"])
-async def root_candidate_draft_add_project(
- session: CommitterSession, project_name: str, version_name: str
[email protected]_route("/candidate/draft/add/<project_name>/<version_name>",
methods=["GET", "POST"])
+async def add_project(
+ session: routes.CommitterSession, project_name: str, version_name: str
) -> response.Response | str:
"""Show a page to allow the user to add a single file to a candidate
draft."""
form = await FilesAddOneForm.create_form()
@@ -317,9 +218,7 @@ async def root_candidate_draft_add_project(
await _add_one(project_name, version_name, file_path, file_data)
await quart.flash("File added successfully", "success")
- return quart.redirect(
- quart.url_for("root_candidate_draft_list",
project_name=project_name, version_name=version_name)
- )
+ return quart.redirect(util.as_url(files,
project_name=project_name, version_name=version_name))
except Exception as e:
logging.exception("Error adding file:")
await quart.flash(f"Error adding file: {e!s}", "error")
@@ -331,11 +230,12 @@ async def root_candidate_draft_add_project(
project_name=project_name,
version_name=version_name,
form=form,
+ candidate_draft=sys.modules[__name__],
)
-@committer_route("/candidate/draft/list/<project_name>/<version_name>")
-async def root_candidate_draft_list(session: CommitterSession, project_name:
str, version_name: str) -> str:
[email protected]_route("/candidate/draft/files/<project_name>/<version_name>")
+async def files(session: routes.CommitterSession, project_name: str,
version_name: str) -> str:
"""Show all the files in the rsync upload directory for a release."""
# Check that the user has access to the project
if not any((p.name == project_name) for p in (await
session.user_projects)):
@@ -411,13 +311,12 @@ async def root_candidate_draft_list(session:
CommitterSession, project_name: str
modified=path_modified,
tasks=path_tasks,
models=models,
+ candidate_draft=sys.modules[__name__],
)
-@committer_route("/candidate/draft/checks/<project_name>/<version_name>/<path:file_path>")
-async def root_candidate_draft_checks(
- session: CommitterSession, project_name: str, version_name: str,
file_path: str
-) -> str:
[email protected]_route("/candidate/draft/checks/<project_name>/<version_name>/<path:file_path>")
+async def checks(session: routes.CommitterSession, project_name: str,
version_name: str, file_path: str) -> str:
"""Show the status of all checks for a specific file."""
# Check that the user has access to the project
if not any((p.name == project_name) for p in (await
session.user_projects)):
@@ -464,53 +363,13 @@ async def root_candidate_draft_checks(
tasks=tasks,
all_tasks_completed=all_tasks_completed,
format_file_size=routes.format_file_size,
+ candidate_draft=sys.modules[__name__],
)
-@committer_route("/candidate/draft/tools/<project_name>/<version_name>/<path:file_path>")
-async def root_candidate_draft_tools(
- session: CommitterSession, project_name: str, version_name: str,
file_path: str
-) -> str:
- """Show the tools for a specific file."""
- # Check that the user has access to the project
- if not any((p.name == project_name) for p in (await
session.user_projects)):
- raise base.ASFQuartException("You do not have access to this project",
errorcode=403)
-
- async with db.session() as data:
- # Check that the release exists
- release = await data.release(name=f"{project_name}-{version_name}",
_project=True).demand(
- base.ASFQuartException("Release does not exist", errorcode=404)
- )
-
- full_path = str(util.get_candidate_draft_dir() / project_name /
version_name / file_path)
-
- # Check that the file exists
- if not await aiofiles.os.path.exists(full_path):
- raise base.ASFQuartException("File does not exist", errorcode=404)
-
- modified = int(await aiofiles.os.path.getmtime(full_path))
- file_size = await aiofiles.os.path.getsize(full_path)
-
- file_data = {
- "filename": pathlib.Path(file_path).name,
- "bytes_size": file_size,
- "uploaded": datetime.datetime.fromtimestamp(modified, tz=datetime.UTC),
- }
-
- return await quart.render_template(
- "candidate-draft-tools.html",
- project_name=project_name,
- version_name=version_name,
- file_path=file_path,
- file_data=file_data,
- release=release,
- format_file_size=routes.format_file_size,
- )
-
-
-@committer_route("/candidate/draft/delete/<project_name>/<version_name>/<path:file_path>",
methods=["POST"])
-async def root_candidate_draft_delete(
- session: CommitterSession, project_name: str, version_name: str,
file_path: str
[email protected]_route("/candidate/draft/delete/<project_name>/<version_name>/<path:file_path>",
methods=["POST"])
+async def delete(
+ session: routes.CommitterSession, project_name: str, version_name: str,
file_path: str
) -> response.Response:
"""Delete a specific file from the release candidate."""
# Check that the user has access to the project
@@ -533,14 +392,12 @@ async def root_candidate_draft_delete(
await aiofiles.os.remove(full_path)
await quart.flash("File deleted successfully", "success")
- return quart.redirect(
- quart.url_for("root_candidate_draft_list", project_name=project_name,
version_name=version_name)
- )
+ return quart.redirect(util.as_url(files, project_name=project_name,
version_name=version_name))
-@committer_route("/candidate/draft/generate-hash/<project_name>/<version_name>/<path:file_path>",
methods=["POST"])
-async def root_candidate_draft_generate_hash(
- session: CommitterSession, project_name: str, version_name: str,
file_path: str
[email protected]_route("/candidate/draft/hashgen/<project_name>/<version_name>/<path:file_path>",
methods=["POST"])
+async def hashgen(
+ session: routes.CommitterSession, project_name: str, version_name: str,
file_path: str
) -> response.Response:
"""Generate an sha256 or sha512 hash file for a candidate draft file."""
# Check that the user has access to the project
@@ -591,6 +448,45 @@ async def root_candidate_draft_generate_hash(
await data.commit()
await quart.flash(f"{hash_type} file generated successfully", "success")
- return quart.redirect(
- quart.url_for("root_candidate_draft_list", project_name=project_name,
version_name=version_name)
+ return quart.redirect(util.as_url(files, project_name=project_name,
version_name=version_name))
+
+
[email protected]_route("/candidate/draft/tools/<project_name>/<version_name>/<path:file_path>")
+async def tools(session: routes.CommitterSession, project_name: str,
version_name: str, file_path: str) -> str:
+ """Show the tools for a specific file."""
+ # Check that the user has access to the project
+ if not any((p.name == project_name) for p in (await
session.user_projects)):
+ raise base.ASFQuartException("You do not have access to this project",
errorcode=403)
+
+ async with db.session() as data:
+ # Check that the release exists
+ release = await data.release(name=f"{project_name}-{version_name}",
_project=True).demand(
+ base.ASFQuartException("Release does not exist", errorcode=404)
+ )
+
+ full_path = str(util.get_candidate_draft_dir() / project_name /
version_name / file_path)
+
+ # Check that the file exists
+ if not await aiofiles.os.path.exists(full_path):
+ raise base.ASFQuartException("File does not exist", errorcode=404)
+
+ modified = int(await aiofiles.os.path.getmtime(full_path))
+ file_size = await aiofiles.os.path.getsize(full_path)
+
+ file_data = {
+ "filename": pathlib.Path(file_path).name,
+ "bytes_size": file_size,
+ "uploaded": datetime.datetime.fromtimestamp(modified, tz=datetime.UTC),
+ }
+
+ return await quart.render_template(
+ "candidate-draft-tools.html",
+ asf_id=session.uid,
+ project_name=project_name,
+ version_name=version_name,
+ file_path=file_path,
+ file_data=file_data,
+ release=release,
+ format_file_size=routes.format_file_size,
+ candidate_draft=sys.modules[__name__],
)
diff --git a/atr/server.py b/atr/server.py
index 9f82a68..cf1b35c 100644
--- a/atr/server.py
+++ b/atr/server.py
@@ -55,18 +55,11 @@ class ApiOnlyOpenAPIProvider(quart_schema.OpenAPIProvider):
yield rule
-def register_routes(app: base.QuartApp) -> tuple[str, ...]:
+def register_routes(app: base.QuartApp) -> None:
# NOTE: These imports are for their side effects only
- import atr.routes.candidate as candidate
- import atr.routes.candidate_draft as candidate_draft
- import atr.routes.committees as committees
- import atr.routes.dev as dev
- import atr.routes.docs as docs
- import atr.routes.download as download
- import atr.routes.keys as keys
- import atr.routes.projects as projects
- import atr.routes.release as release
- import atr.routes.root as root
+ import atr.routes as routes
+
+ routes.modules()
# Add a global error handler to show helpful error messages with
tracebacks.
@app.errorhandler(Exception)
@@ -92,20 +85,6 @@ def register_routes(app: base.QuartApp) -> tuple[str, ...]:
async def handle_not_found(error: Exception) -> Any:
return await quart.render_template("notfound.html", error="404 Not
Found", traceback="", status_code=404), 404
- # Must do this otherwise ruff "fixes" this function by removing the imports
- return (
- candidate.__name__,
- candidate_draft.__name__,
- committees.__name__,
- dev.__name__,
- docs.__name__,
- download.__name__,
- keys.__name__,
- projects.__name__,
- release.__name__,
- root.__name__,
- )
-
def app_dirs_setup(app_config: type[config.AppConfig]) -> None:
"""Setup application directories."""
@@ -154,13 +133,16 @@ def app_setup_context(app: base.QuartApp) -> None:
async def app_wide() -> dict[str, Any]:
import atr.db.service as service
import atr.metadata as metadata
+ import atr.routes as routes
import atr.util as util
return {
+ "as_url": util.as_url,
+ "commit": metadata.commit,
"current_user": await asfquart.session.read(),
"is_admin_fn": util.is_admin,
"is_project_lead_fn": service.is_project_lead,
- "commit": metadata.commit,
+ "routes": routes.modules(),
"version": metadata.version,
}
diff --git a/atr/templates/candidate-draft-add-project.html
b/atr/templates/candidate-draft-add-project.html
index d27d4f3..9ddb951 100644
--- a/atr/templates/candidate-draft-add-project.html
+++ b/atr/templates/candidate-draft-add-project.html
@@ -9,7 +9,7 @@
{% endblock description %}
{% block content %}
- <a href="{{ url_for('root_candidate_draft_add') }}" class="back-link">← Back
to Create and modify</a>
+ <a href="{{ as_url(routes.candidate_draft.add) }}" class="back-link">← Back
to Create and modify</a>
<h1>Add file to {{ project_name }} {{ version_name }}</h1>
<p class="intro">Use this form to add a single file to this candidate
draft.</p>
diff --git a/atr/templates/candidate-draft-add.html
b/atr/templates/candidate-draft-add.html
index 68b9fcb..95fafc8 100644
--- a/atr/templates/candidate-draft-add.html
+++ b/atr/templates/candidate-draft-add.html
@@ -34,11 +34,11 @@
{% endif %}
<p class="card-text">
{% if number_of_release_files(release) > 0 %}
- This candidate draft has <a href="{{
url_for('root_candidate_draft_list', project_name=release.project.name,
version_name=release.version) }}">{{ number_of_release_files(release) }}
file(s)</a>.
+ This candidate draft has <a href="{{
as_url(routes.candidate_draft.files, project_name=release.project.name,
version_name=release.version) }}">{{ number_of_release_files(release) }}
file(s)</a>.
{% else %}
This candidate draft doesn't have any files yet.
{% endif %}
- <a href="{{ url_for('root_candidate_draft_add_project',
project_name=release.project.name, version_name=release.version) }}">Upload a
file using the browser</a>,
+ <a href="{{ as_url(routes.candidate_draft.add_project,
project_name=release.project.name, version_name=release.version) }}">Upload a
file using the browser</a>,
or use the command below to add or modify files in this draft:
</p>
</div>
diff --git a/atr/templates/candidate-draft-check.html
b/atr/templates/candidate-draft-check.html
index 2813b44..3cc936e 100644
--- a/atr/templates/candidate-draft-check.html
+++ b/atr/templates/candidate-draft-check.html
@@ -9,7 +9,7 @@
{% endblock description %}
{% block content %}
- <a href="{{ url_for('root_candidate_draft_list', project_name=project_name,
version_name=version_name) }}"
+ <a href="{{ as_url(routes.candidate_draft.files, project_name=project_name,
version_name=version_name) }}"
class="back-link">← Back to Files List</a>
<div class="p-3 mb-4 bg-light border rounded">
diff --git a/atr/templates/candidate-draft-list.html
b/atr/templates/candidate-draft-list.html
index 275002c..12a0e9f 100644
--- a/atr/templates/candidate-draft-list.html
+++ b/atr/templates/candidate-draft-list.html
@@ -49,7 +49,7 @@
<div class="card mb-4">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">Files</h5>
- <a href="{{ url_for('root_candidate_draft_add') }}"
+ <a href="{{ as_url(routes.candidate_draft.add) }}"
class="btn btn-sm btn-outline-secondary">Back to Create and modify</a>
</div>
<div class="card-body">
@@ -127,10 +127,10 @@
<td class="atr-sans">
<a href="{{ url_for('root_download',
phase='candidate-draft', project=release.project.name, version=release.version,
path=path) }}"
class="btn btn-sm btn-outline-primary fs-6">Download</a>
- <a href="{{ url_for('root_candidate_draft_tools',
project_name=project_name, version_name=version_name, file_path=path) }}"
+ <a href="{{ as_url(routes.candidate_draft.tools,
project_name=project_name, version_name=version_name, file_path=path) }}"
class="btn btn-sm btn-outline-primary fs-6 small
ms-2">Tools</a>
{% if path in tasks and tasks[path]|length > 0 %}
- <a href="{{ url_for('root_candidate_draft_checks',
project_name=project_name, version_name=version_name, file_path=path) }}"
+ <a href="{{ as_url(routes.candidate_draft.checks,
project_name=project_name, version_name=version_name, file_path=path) }}"
class="btn btn-sm btn-outline-primary fs-6 small
ms-2">Check results</a>
{% endif %}
</td>
@@ -173,7 +173,7 @@
</details>
{% else %}
<div class="alert alert-info">
- This release does not have any files yet. You can add files using
rsync from the <a href="{{ url_for('root_candidate_draft_add') }}">add
files</a> page.
+ This release does not have any files yet. You can add files using
rsync from the <a href="{{ as_url(routes.candidate_draft.add) }}">add files</a>
page.
</div>
{% endif %}
</div>
@@ -185,7 +185,7 @@
</div>
<div class="card-body">
<p>
- <a href="{{ url_for('root_candidate_draft_add_project',
project_name=release.project.name, version_name=release.version) }}">Upload a
file in the browser</a>, or use the command below to add or modify files in
this release using rsync:
+ <a href="{{ as_url(routes.candidate_draft.add_project,
project_name=release.project.name, version_name=release.version) }}">Upload a
file in the browser</a>, or use the command below to add or modify files in
this release using rsync:
</p>
</div>
<pre class="card-footer bg-light border-1 pt-4 small">
diff --git a/atr/templates/candidate-draft-tools.html
b/atr/templates/candidate-draft-tools.html
index 787c2d9..3f0aa62 100644
--- a/atr/templates/candidate-draft-tools.html
+++ b/atr/templates/candidate-draft-tools.html
@@ -9,7 +9,7 @@
{% endblock description %}
{% block content %}
- <a href="{{ url_for('root_candidate_draft_list', project_name=project_name,
version_name=version_name) }}"
+ <a href="{{ as_url(routes.candidate_draft.files, project_name=project_name,
version_name=version_name) }}"
class="back-link">← Back to Files List</a>
<div class="p-3 mb-4 bg-light border rounded">
@@ -35,12 +35,12 @@
</div>
<div class="d-flex gap-2 mb-4">
<form method="post"
- action="{{ url_for('root_candidate_draft_generate_hash',
project_name=project_name, version_name=version_name, file_path=file_path) }}">
+ action="{{ as_url(routes.candidate_draft.generate_hash,
project_name=project_name, version_name=version_name, file_path=file_path) }}">
<input type="hidden" name="hash_type" value="sha256" />
<button type="submit" class="btn btn-outline-secondary">Generate
SHA256</button>
</form>
<form method="post"
- action="{{ url_for('root_candidate_draft_generate_hash',
project_name=project_name, version_name=version_name, file_path=file_path) }}">
+ action="{{ as_url(routes.candidate_draft.generate_hash,
project_name=project_name, version_name=version_name, file_path=file_path) }}">
<input type="hidden" name="hash_type" value="sha512" />
<button type="submit" class="btn btn-outline-secondary">Generate
SHA512</button>
</form>
@@ -49,7 +49,7 @@
<h3>Delete file</h3>
<p>This tool deletes the file from the candidate draft.</p>
<form method="post"
- action="{{ url_for('root_candidate_draft_delete',
project_name=project_name, version_name=version_name, file_path=file_path) }}">
+ action="{{ as_url(routes.candidate_draft.delete,
project_name=project_name, version_name=version_name, file_path=file_path) }}">
<button type="submit"
class="btn btn-danger"
onclick="return confirm('Are you sure you want to delete this
file?')">Delete file</button>
diff --git a/atr/templates/includes/sidebar.html
b/atr/templates/includes/sidebar.html
index 622147a..dd42a23 100644
--- a/atr/templates/includes/sidebar.html
+++ b/atr/templates/includes/sidebar.html
@@ -50,7 +50,7 @@
<h3>Candidate drafts</h3>
<ul>
<li>
- <a href="{{ url_for('root_candidate_draft_add') }}"
+ <a href="{{ as_url(routes.candidate_draft.add) }}"
{% if request.endpoint == 'root_candidate_draft_add'
%}class="active"{% endif %}>Create and modify</a>
</li>
<!-- TODO: Don't show this if the user doesn't have any release
candidates? -->
diff --git a/atr/util.py b/atr/util.py
index f2f8af1..060e4bb 100644
--- a/atr/util.py
+++ b/atr/util.py
@@ -19,7 +19,7 @@ import dataclasses
import functools
import hashlib
import pathlib
-from collections.abc import Mapping
+from collections.abc import Callable, Mapping
from typing import Annotated, Any, TypeVar
import aiofiles.os
@@ -27,6 +27,7 @@ import asfquart.base as base
import asfquart.session as session
import pydantic
import pydantic_core
+import quart
import quart_wtf
import quart_wtf.typing
@@ -81,6 +82,11 @@ class QuartFormTyped(quart_wtf.QuartForm):
return form
+def as_url(func: Callable, **kwargs: Any) -> str:
+ """Return the URL for a function."""
+ return quart.url_for(func.__annotations__["endpoint"], **kwargs)
+
+
def compute_sha3_256(file_data: bytes) -> str:
"""Compute SHA3-256 hash of file data."""
return hashlib.sha3_256(file_data).hexdigest()
diff --git a/docs/conventions.html b/docs/conventions.html
index 1e20591..03410d9 100644
--- a/docs/conventions.html
+++ b/docs/conventions.html
@@ -57,7 +57,7 @@ r.s()
from p.q.r import s
s()
</code></pre>
-<p>The collections.abc and typing modules are an exception to this rule.
Always import collections.abc and typing identifiers directly using the
<code>from</code> syntax:</p>
+<p>The <code>collections.abc</code>, <code>types</code>, and
<code>typing</code> modules are an exception to this rule. Always import
<code>collections.abc</code>, <code>types</code> and <code>typing</code>
interfaces directly using the <code>from</code> syntax:</p>
<pre><code class="language-python"># Preferred
from typing import Final
diff --git a/docs/conventions.md b/docs/conventions.md
index 2e1080d..797df60 100644
--- a/docs/conventions.md
+++ b/docs/conventions.md
@@ -91,7 +91,7 @@ from p.q.r import s
s()
```
-The collections.abc and typing modules are an exception to this rule. Always
import collections.abc and typing identifiers directly using the `from` syntax:
+The `collections.abc`, `types`, and `typing` modules are an exception to this
rule. Always import `collections.abc`, `types` and `typing` interfaces directly
using the `from` syntax:
```python
# Preferred
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]