import re
from pathlib import Path
import jinja2
from q2_sdk.core.q2_logging.logger import Q2LoggerType
from .base_query import BaseQuery
[docs]
class JinjaQuery(BaseQuery):
WHITESPACE_REGEX = re.compile(r"[ \t\r\f\v]*\n[ \t\r\f\v]*")
def __init__(
self,
logger: Q2LoggerType,
templates_path: Path,
request_template: str,
mock_response_template: str,
context: dict | None = None,
mock_failure=False,
collapse_whitespace=False,
):
"""
Same behavior as BaseQuery, though build and mock
are handled by passed in Jinja template
:param logger: Reference to calling request's logger (self.logger in your extension)
:param templates_path: Path to the templates
:param request_template: Filename for the template for the request
:param mock_response_template: Filename for the mock response
:param context: Context to use during rendering
:param mock_failure: Inherited from base
:param collapse_whitespace: Removes new lines and whitespace around it
"""
self.templates_path: Path = templates_path
self.request_template = request_template
self.mock_response_template = mock_response_template
self.context = context
self.collapse_whitespace = collapse_whitespace
super().__init__(logger, mock_failure)
def build(self) -> str:
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(str(self.templates_path)),
autoescape=jinja2.select_autoescape(["xml"]),
)
template = jinja_environment.get_template(self.request_template)
result = template.render(self.context)
if self.collapse_whitespace:
result = self.WHITESPACE_REGEX.sub("", result)
return result
[docs]
def mock_response(self) -> str:
with (self.templates_path / self.mock_response_template).open() as f_handle:
return f_handle.read()