-
Notifications
You must be signed in to change notification settings - Fork 2
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
Allow directory with template overrides #9
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,8 +3,10 @@ | |
import json | ||
import pathlib | ||
from dataclasses import dataclass, field | ||
from typing import Any, Callable, Optional | ||
from os import PathLike | ||
from typing import Any, Callable, List, Optional, Union | ||
|
||
import jinja2 | ||
from geojson_pydantic.geometries import Polygon | ||
|
||
from tifeatures import model | ||
|
@@ -16,20 +18,65 @@ | |
from tifeatures.settings import APISettings | ||
|
||
from fastapi import APIRouter, Depends, Path, Query | ||
from fastapi.templating import Jinja2Templates | ||
|
||
from starlette.datastructures import QueryParams | ||
from starlette.requests import Request | ||
from starlette.responses import HTMLResponse | ||
from starlette.templating import Jinja2Templates, _TemplateResponse | ||
|
||
if hasattr(jinja2, "pass_context"): | ||
pass_context = jinja2.pass_context # type: ignore | ||
else: # pragma: nocover | ||
pass_context = jinja2.contextfunction # type: ignore[attr-defined] | ||
|
||
template_dir = str(pathlib.Path(__file__).parent.joinpath("templates")) | ||
templates = Jinja2Templates(directory=template_dir) | ||
settings = APISettings() | ||
|
||
|
||
class SearchPathTemplates(Jinja2Templates): | ||
""" | ||
templates = DefaultTemplates("templates") | ||
return templates.TemplateResponse("index.html", {"request": request}) | ||
""" | ||
|
||
def __init__( | ||
self, | ||
directory: Union[str, PathLike, List[Union[str, None, PathLike]]], | ||
**env_options: Any, | ||
) -> None: | ||
"""Initialize Search Path Template.""" | ||
assert jinja2 is not None, "jinja2 must be installed to use Jinja2Templates" | ||
self.env = self._create_env(directory, **env_options) | ||
|
||
def _create_env( | ||
self, | ||
directory: Union[str, PathLike, List[Union[str, None, PathLike]]], | ||
**env_options: Any, | ||
) -> "jinja2.Environment": | ||
@pass_context | ||
def url_for(context: dict, name: str, **path_params: Any) -> str: | ||
request = context["request"] | ||
return request.url_for(name, **path_params) | ||
|
||
if isinstance(directory, list): | ||
loader = jinja2.FileSystemLoader([d for d in directory if d]) | ||
else: | ||
loader = jinja2.FileSystemLoader(directory) | ||
env_options.setdefault("loader", loader) | ||
env_options.setdefault("autoescape", True) | ||
|
||
env = jinja2.Environment(**env_options) | ||
env.globals["url_for"] = url_for | ||
return env | ||
|
||
|
||
default_template_dir = str(pathlib.Path(__file__).parent.joinpath("templates")) | ||
templates = SearchPathTemplates( | ||
directory=[settings.template_directory, default_template_dir] | ||
) | ||
|
||
|
||
def create_html_response( | ||
request: Request, data: str, template_name: str | ||
) -> HTMLResponse: | ||
) -> _TemplateResponse: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
"""Create Template response.""" | ||
urlpath = request.url.path | ||
crumbs = [] | ||
|
@@ -480,9 +527,8 @@ async def items( | |
|
||
if (matched_items - items_returned) > offset: | ||
next_offset = offset + items_returned | ||
query_params = QueryParams( | ||
{**request.query_params, "offset": next_offset} | ||
) | ||
query_params = {**request.query_params, "offset": next_offset} | ||
|
||
url = ( | ||
self.url_for(request, "items", collectionId=collection.id) | ||
+ f"?{query_params}" | ||
|
@@ -496,13 +542,13 @@ async def items( | |
query_params.pop("offset") | ||
prev_offset = max(offset - items_returned, 0) | ||
if prev_offset: | ||
query_params = QueryParams({**query_params, "offset": prev_offset}) | ||
query_params = {**query_params, "offset": prev_offset} | ||
else: | ||
query_params = QueryParams({**query_params}) | ||
query_params = {**query_params} | ||
|
||
url = self.url_for(request, "items", collectionId=collection.id) | ||
if query_params: | ||
url += f"?{query_params}" | ||
url += f"?{QueryParams(**query_params)}" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. is this related to the PR topic? I'm fine with the change, but I worry that I did use this kind of style at multiple places 🤷♂️ There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Again, mypy didn't like that query_params was a dict in some places and QueryParama elsewhere |
||
|
||
links.append( | ||
model.Link(href=url, rel="prev", type=MediaType.geojson), | ||
|
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
@@ -8,7 +8,7 @@ | |||||||||||||||||||||||||||||||||||||||||||
from buildpg import asyncpg, clauses | ||||||||||||||||||||||||||||||||||||||||||||
from buildpg import funcs as pg_funcs | ||||||||||||||||||||||||||||||||||||||||||||
from buildpg import render | ||||||||||||||||||||||||||||||||||||||||||||
from geojson_pydantic import Feature, FeatureCollection | ||||||||||||||||||||||||||||||||||||||||||||
from geojson_pydantic.features import Feature, FeatureCollection | ||||||||||||||||||||||||||||||||||||||||||||
from pydantic import BaseModel, Field, root_validator | ||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||
|
@@ -41,7 +41,7 @@ async def features( | |||||||||||||||||||||||||||||||||||||||||||
limit: int = None, | ||||||||||||||||||||||||||||||||||||||||||||
offset: int = None, | ||||||||||||||||||||||||||||||||||||||||||||
**kwargs: Any, | ||||||||||||||||||||||||||||||||||||||||||||
) -> Items: | ||||||||||||||||||||||||||||||||||||||||||||
) -> FeatureCollection: | ||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ? tifeatures/tifeatures/model.py Lines 114 to 134 in 28afbd8
(Gives better documentation) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Mypy was complaining, i was just trying to get the tests to pass (same with everything in that last commit). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 I'll check that 🙏 |
||||||||||||||||||||||||||||||||||||||||||||
"""Return a FeatureCollection.""" | ||||||||||||||||||||||||||||||||||||||||||||
... | ||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||
|
@@ -85,7 +85,7 @@ async def features( | |||||||||||||||||||||||||||||||||||||||||||
limit: int = None, | ||||||||||||||||||||||||||||||||||||||||||||
offset: int = None, | ||||||||||||||||||||||||||||||||||||||||||||
**kwargs: Any, | ||||||||||||||||||||||||||||||||||||||||||||
) -> Items: | ||||||||||||||||||||||||||||||||||||||||||||
) -> FeatureCollection: | ||||||||||||||||||||||||||||||||||||||||||||
"""Return a FeatureCollection.""" | ||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||
limit = limit or 10 | ||||||||||||||||||||||||||||||||||||||||||||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what about something a bit simpler:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The thing i like about extending SearchPathTemplates is that it allows us to use the native tooling in jinja and could handle several paths if anyone needed as well.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍 it seems you can do this without re-writing your own class encode/starlette#1214