templating.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. from __future__ import annotations
  2. import typing as t
  3. from jinja2 import BaseLoader
  4. from jinja2 import Environment as BaseEnvironment
  5. from jinja2 import Template
  6. from jinja2 import TemplateNotFound
  7. from .globals import _cv_app
  8. from .globals import _cv_request
  9. from .globals import current_app
  10. from .globals import request
  11. from .helpers import stream_with_context
  12. from .signals import before_render_template
  13. from .signals import template_rendered
  14. if t.TYPE_CHECKING: # pragma: no cover
  15. from .app import Flask
  16. from .sansio.app import App
  17. from .sansio.scaffold import Scaffold
  18. def _default_template_ctx_processor() -> dict[str, t.Any]:
  19. """Default template context processor. Injects `request`,
  20. `session` and `g`.
  21. """
  22. appctx = _cv_app.get(None)
  23. reqctx = _cv_request.get(None)
  24. rv: dict[str, t.Any] = {}
  25. if appctx is not None:
  26. rv["g"] = appctx.g
  27. if reqctx is not None:
  28. rv["request"] = reqctx.request
  29. rv["session"] = reqctx.session
  30. return rv
  31. class Environment(BaseEnvironment):
  32. """Works like a regular Jinja2 environment but has some additional
  33. knowledge of how Flask's blueprint works so that it can prepend the
  34. name of the blueprint to referenced templates if necessary.
  35. """
  36. def __init__(self, app: App, **options: t.Any) -> None:
  37. if "loader" not in options:
  38. options["loader"] = app.create_global_jinja_loader()
  39. BaseEnvironment.__init__(self, **options)
  40. self.app = app
  41. class DispatchingJinjaLoader(BaseLoader):
  42. """A loader that looks for templates in the application and all
  43. the blueprint folders.
  44. """
  45. def __init__(self, app: App) -> None:
  46. self.app = app
  47. def get_source( # type: ignore
  48. self, environment: Environment, template: str
  49. ) -> tuple[str, str | None, t.Callable | None]:
  50. if self.app.config["EXPLAIN_TEMPLATE_LOADING"]:
  51. return self._get_source_explained(environment, template)
  52. return self._get_source_fast(environment, template)
  53. def _get_source_explained(
  54. self, environment: Environment, template: str
  55. ) -> tuple[str, str | None, t.Callable | None]:
  56. attempts = []
  57. rv: tuple[str, str | None, t.Callable[[], bool] | None] | None
  58. trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None
  59. for srcobj, loader in self._iter_loaders(template):
  60. try:
  61. rv = loader.get_source(environment, template)
  62. if trv is None:
  63. trv = rv
  64. except TemplateNotFound:
  65. rv = None
  66. attempts.append((loader, srcobj, rv))
  67. from .debughelpers import explain_template_loading_attempts
  68. explain_template_loading_attempts(self.app, template, attempts)
  69. if trv is not None:
  70. return trv
  71. raise TemplateNotFound(template)
  72. def _get_source_fast(
  73. self, environment: Environment, template: str
  74. ) -> tuple[str, str | None, t.Callable | None]:
  75. for _srcobj, loader in self._iter_loaders(template):
  76. try:
  77. return loader.get_source(environment, template)
  78. except TemplateNotFound:
  79. continue
  80. raise TemplateNotFound(template)
  81. def _iter_loaders(
  82. self, template: str
  83. ) -> t.Generator[tuple[Scaffold, BaseLoader], None, None]:
  84. loader = self.app.jinja_loader
  85. if loader is not None:
  86. yield self.app, loader
  87. for blueprint in self.app.iter_blueprints():
  88. loader = blueprint.jinja_loader
  89. if loader is not None:
  90. yield blueprint, loader
  91. def list_templates(self) -> list[str]:
  92. result = set()
  93. loader = self.app.jinja_loader
  94. if loader is not None:
  95. result.update(loader.list_templates())
  96. for blueprint in self.app.iter_blueprints():
  97. loader = blueprint.jinja_loader
  98. if loader is not None:
  99. for template in loader.list_templates():
  100. result.add(template)
  101. return list(result)
  102. def _render(app: Flask, template: Template, context: dict[str, t.Any]) -> str:
  103. app.update_template_context(context)
  104. before_render_template.send(
  105. app, _async_wrapper=app.ensure_sync, template=template, context=context
  106. )
  107. rv = template.render(context)
  108. template_rendered.send(
  109. app, _async_wrapper=app.ensure_sync, template=template, context=context
  110. )
  111. return rv
  112. def render_template(
  113. template_name_or_list: str | Template | list[str | Template],
  114. **context: t.Any,
  115. ) -> str:
  116. """Render a template by name with the given context.
  117. :param template_name_or_list: The name of the template to render. If
  118. a list is given, the first name to exist will be rendered.
  119. :param context: The variables to make available in the template.
  120. """
  121. app = current_app._get_current_object() # type: ignore[attr-defined]
  122. template = app.jinja_env.get_or_select_template(template_name_or_list)
  123. return _render(app, template, context)
  124. def render_template_string(source: str, **context: t.Any) -> str:
  125. """Render a template from the given source string with the given
  126. context.
  127. :param source: The source code of the template to render.
  128. :param context: The variables to make available in the template.
  129. """
  130. app = current_app._get_current_object() # type: ignore[attr-defined]
  131. template = app.jinja_env.from_string(source)
  132. return _render(app, template, context)
  133. def _stream(
  134. app: Flask, template: Template, context: dict[str, t.Any]
  135. ) -> t.Iterator[str]:
  136. app.update_template_context(context)
  137. before_render_template.send(
  138. app, _async_wrapper=app.ensure_sync, template=template, context=context
  139. )
  140. def generate() -> t.Iterator[str]:
  141. yield from template.generate(context)
  142. template_rendered.send(
  143. app, _async_wrapper=app.ensure_sync, template=template, context=context
  144. )
  145. rv = generate()
  146. # If a request context is active, keep it while generating.
  147. if request:
  148. rv = stream_with_context(rv)
  149. return rv
  150. def stream_template(
  151. template_name_or_list: str | Template | list[str | Template],
  152. **context: t.Any,
  153. ) -> t.Iterator[str]:
  154. """Render a template by name with the given context as a stream.
  155. This returns an iterator of strings, which can be used as a
  156. streaming response from a view.
  157. :param template_name_or_list: The name of the template to render. If
  158. a list is given, the first name to exist will be rendered.
  159. :param context: The variables to make available in the template.
  160. .. versionadded:: 2.2
  161. """
  162. app = current_app._get_current_object() # type: ignore[attr-defined]
  163. template = app.jinja_env.get_or_select_template(template_name_or_list)
  164. return _stream(app, template, context)
  165. def stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]:
  166. """Render a template from the given source string with the given
  167. context as a stream. This returns an iterator of strings, which can
  168. be used as a streaming response from a view.
  169. :param source: The source code of the template to render.
  170. :param context: The variables to make available in the template.
  171. .. versionadded:: 2.2
  172. """
  173. app = current_app._get_current_object() # type: ignore[attr-defined]
  174. template = app.jinja_env.from_string(source)
  175. return _stream(app, template, context)