templating.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import typing as t
  2. from jinja2 import BaseLoader
  3. from jinja2 import Environment as BaseEnvironment
  4. from jinja2 import Template
  5. from jinja2 import TemplateNotFound
  6. from .globals import _cv_app
  7. from .globals import _cv_request
  8. from .globals import current_app
  9. from .globals import request
  10. from .helpers import stream_with_context
  11. from .signals import before_render_template
  12. from .signals import template_rendered
  13. if t.TYPE_CHECKING: # pragma: no cover
  14. from .app import Flask
  15. from .scaffold import Scaffold
  16. def _default_template_ctx_processor() -> t.Dict[str, t.Any]:
  17. """Default template context processor. Injects `request`,
  18. `session` and `g`.
  19. """
  20. appctx = _cv_app.get(None)
  21. reqctx = _cv_request.get(None)
  22. rv: t.Dict[str, t.Any] = {}
  23. if appctx is not None:
  24. rv["g"] = appctx.g
  25. if reqctx is not None:
  26. rv["request"] = reqctx.request
  27. rv["session"] = reqctx.session
  28. return rv
  29. class Environment(BaseEnvironment):
  30. """Works like a regular Jinja2 environment but has some additional
  31. knowledge of how Flask's blueprint works so that it can prepend the
  32. name of the blueprint to referenced templates if necessary.
  33. """
  34. def __init__(self, app: "Flask", **options: t.Any) -> None:
  35. if "loader" not in options:
  36. options["loader"] = app.create_global_jinja_loader()
  37. BaseEnvironment.__init__(self, **options)
  38. self.app = app
  39. class DispatchingJinjaLoader(BaseLoader):
  40. """A loader that looks for templates in the application and all
  41. the blueprint folders.
  42. """
  43. def __init__(self, app: "Flask") -> None:
  44. self.app = app
  45. def get_source( # type: ignore
  46. self, environment: Environment, template: str
  47. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable]]:
  48. if self.app.config["EXPLAIN_TEMPLATE_LOADING"]:
  49. return self._get_source_explained(environment, template)
  50. return self._get_source_fast(environment, template)
  51. def _get_source_explained(
  52. self, environment: Environment, template: str
  53. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable]]:
  54. attempts = []
  55. rv: t.Optional[t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]]
  56. trv: t.Optional[
  57. t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]
  58. ] = 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. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable]]:
  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[t.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) -> t.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: t.Dict[str, t.Any]) -> str:
  103. app.update_template_context(context)
  104. before_render_template.send(app, template=template, context=context)
  105. rv = template.render(context)
  106. template_rendered.send(app, template=template, context=context)
  107. return rv
  108. def render_template(
  109. template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]],
  110. **context: t.Any
  111. ) -> str:
  112. """Render a template by name with the given context.
  113. :param template_name_or_list: The name of the template to render. If
  114. a list is given, the first name to exist will be rendered.
  115. :param context: The variables to make available in the template.
  116. """
  117. app = current_app._get_current_object() # type: ignore[attr-defined]
  118. template = app.jinja_env.get_or_select_template(template_name_or_list)
  119. return _render(app, template, context)
  120. def render_template_string(source: str, **context: t.Any) -> str:
  121. """Render a template from the given source string with the given
  122. context.
  123. :param source: The source code of the template to render.
  124. :param context: The variables to make available in the template.
  125. """
  126. app = current_app._get_current_object() # type: ignore[attr-defined]
  127. template = app.jinja_env.from_string(source)
  128. return _render(app, template, context)
  129. def _stream(
  130. app: "Flask", template: Template, context: t.Dict[str, t.Any]
  131. ) -> t.Iterator[str]:
  132. app.update_template_context(context)
  133. before_render_template.send(app, template=template, context=context)
  134. def generate() -> t.Iterator[str]:
  135. yield from template.generate(context)
  136. template_rendered.send(app, template=template, context=context)
  137. rv = generate()
  138. # If a request context is active, keep it while generating.
  139. if request:
  140. rv = stream_with_context(rv)
  141. return rv
  142. def stream_template(
  143. template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]],
  144. **context: t.Any
  145. ) -> t.Iterator[str]:
  146. """Render a template by name with the given context as a stream.
  147. This returns an iterator of strings, which can be used as a
  148. streaming response from a view.
  149. :param template_name_or_list: The name of the template to render. If
  150. a list is given, the first name to exist will be rendered.
  151. :param context: The variables to make available in the template.
  152. .. versionadded:: 2.2
  153. """
  154. app = current_app._get_current_object() # type: ignore[attr-defined]
  155. template = app.jinja_env.get_or_select_template(template_name_or_list)
  156. return _stream(app, template, context)
  157. def stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]:
  158. """Render a template from the given source string with the given
  159. context as a stream. This returns an iterator of strings, which can
  160. be used as a streaming response from a view.
  161. :param source: The source code of the template to render.
  162. :param context: The variables to make available in the template.
  163. .. versionadded:: 2.2
  164. """
  165. app = current_app._get_current_object() # type: ignore[attr-defined]
  166. template = app.jinja_env.from_string(source)
  167. return _stream(app, template, context)