Skip to content

Commit 658b748

Browse files
committed
More
1 parent 9c1e535 commit 658b748

File tree

14 files changed

+34
-216
lines changed

14 files changed

+34
-216
lines changed

bolt-auth/bolt/auth/forms.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import unicodedata
22

33
from bolt import forms
4-
from bolt.templates import Template
54
from bolt.auth import authenticate, get_user_model, password_validation
65
from bolt.auth.models import User
76
from bolt.auth.tokens import default_token_generator
87
from bolt.db.forms import ModelForm
98
from bolt.exceptions import ValidationError
109
from bolt.mail import EmailMultiAlternatives
10+
from bolt.templates import Template
1111
from bolt.utils.encoding import force_bytes
1212
from bolt.utils.http import urlsafe_base64_encode
1313

bolt-htmx/bolt/htmx/views.py

-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import re
22

3-
from bolt.http import HttpResponse
4-
53

64
class HTMXViewMixin:
75
htmx_template_name = ""

bolt-staff/bolt/admin/cards/base.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from enum import Enum
22

3-
from bolt import jinja
43
from bolt.admin.dates import DatetimeRange, DatetimeRangeAliases
4+
from bolt.templates import Template
55
from bolt.utils.text import slugify
66

77

@@ -39,8 +39,7 @@ def render(self, request, datetime_range):
3939
# If fixed, show that on the card too (I guess you could use description for this)
4040
else:
4141
self.datetime_range = datetime_range
42-
template = jinja.environment.get_template(self.template_name)
43-
return template.render(self.get_context())
42+
return Template(self.template_name).render(self.get_context())
4443

4544
@classmethod
4645
def view_name(cls) -> str:

bolt-staff/bolt/querystats/middleware.py

-12
Original file line numberDiff line numberDiff line change
@@ -86,15 +86,3 @@ def is_staff_request(request):
8686
return request.impersonator and request.impersonator.is_staff
8787

8888
return hasattr(request, "user") and request.user and request.user.is_staff
89-
90-
def process_template_response(self, request, response):
91-
# Template hasn't been rendered yet, so we can't include querystats themselves
92-
# unless we're pulling the previous page stats from the session storage
93-
if (
94-
response.context_data is not None
95-
and hasattr(_local, "querystats")
96-
and self.is_staff_request(request)
97-
):
98-
response.context_data["querystats_enabled"] = True
99-
100-
return response

bolt-staff/bolt/toolbar/templates/toolbar/toolbar.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
{% endif %}
2323
</div>
2424
<div class="flex items-center space-x-4">
25-
{% if querystats_enabled|default(false) %}{% include "querystats/toolbar.html" %}{% endif %}
25+
{% include "querystats/toolbar.html" %}
2626

2727
<div class="flex items-center space-x-3 transition-all">
2828
{% include "toolbar/links.html" %}

bolt/http/response.py

-114
Original file line numberDiff line numberDiff line change
@@ -717,117 +717,3 @@ def __init__(
717717
kwargs.setdefault("content_type", "application/json")
718718
data = json.dumps(data, cls=encoder, **json_dumps_params)
719719
super().__init__(content=data, **kwargs)
720-
721-
722-
class ContentNotRenderedError(Exception):
723-
pass
724-
725-
726-
class RenderableResponse(HttpResponse):
727-
non_picklable_attrs = HttpResponse.non_picklable_attrs | frozenset(
728-
["render_func", "context_data", "_post_render_callbacks", "_request"]
729-
)
730-
731-
def __init__(
732-
self,
733-
render_func,
734-
context=None,
735-
content_type=None,
736-
status=None,
737-
charset=None,
738-
headers=None,
739-
):
740-
self.render_func = render_func
741-
742-
# It would seem obvious to call these next two members 'template' and
743-
# 'context', but those names are reserved as part of the test Client
744-
# API. To avoid the name collision, we use different names.
745-
self.context_data = context
746-
747-
self._post_render_callbacks = []
748-
749-
# content argument doesn't make sense here because it will be replaced
750-
# with rendered template so we always pass empty string in order to
751-
# prevent errors and provide shorter signature.
752-
super().__init__("", content_type, status, charset=charset, headers=headers)
753-
754-
# _is_rendered tracks whether the template and context has been baked
755-
# into a final response.
756-
# Super __init__ doesn't know any better than to set self.content to
757-
# the empty string we just gave it, which wrongly sets _is_rendered
758-
# True, so we initialize it to False after the call to super __init__.
759-
self._is_rendered = False
760-
761-
def __getstate__(self):
762-
"""
763-
Raise an exception if trying to pickle an unrendered response. Pickle
764-
only rendered data, not the data used to construct the response.
765-
"""
766-
if not self._is_rendered:
767-
raise ContentNotRenderedError(
768-
"The response content must be rendered before it can be pickled."
769-
)
770-
return super().__getstate__()
771-
772-
@property
773-
def rendered_content(self):
774-
"""Return the freshly rendered content for the template and context
775-
described by the TemplateResponse.
776-
777-
This *does not* set the final content of the response. To set the
778-
response content, you must either call render(), or set the
779-
content explicitly using the value of this property.
780-
"""
781-
return self.render_func(self.context_data)
782-
783-
def add_post_render_callback(self, callback):
784-
"""Add a new post-rendering callback.
785-
786-
If the response has already been rendered,
787-
invoke the callback immediately.
788-
"""
789-
if self._is_rendered:
790-
callback(self)
791-
else:
792-
self._post_render_callbacks.append(callback)
793-
794-
def render(self):
795-
"""Render (thereby finalizing) the content of the response.
796-
797-
If the content has already been rendered, this is a no-op.
798-
799-
Return the baked response instance.
800-
"""
801-
retval = self
802-
if not self._is_rendered:
803-
self.content = self.rendered_content
804-
for post_callback in self._post_render_callbacks:
805-
newretval = post_callback(retval)
806-
if newretval is not None:
807-
retval = newretval
808-
return retval
809-
810-
@property
811-
def is_rendered(self):
812-
return self._is_rendered
813-
814-
def __iter__(self):
815-
if not self._is_rendered:
816-
raise ContentNotRenderedError(
817-
"The response content must be rendered before it can be iterated over."
818-
)
819-
return super().__iter__()
820-
821-
@property
822-
def content(self):
823-
if not self._is_rendered:
824-
raise ContentNotRenderedError(
825-
"The response content must be rendered before it can be accessed."
826-
)
827-
return super().content
828-
829-
@content.setter
830-
def content(self, value):
831-
"""Set the content for the response."""
832-
HttpResponse.content.fset(self, value)
833-
self._is_rendered = True

bolt/internal/handlers/base.py

-27
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515

1616
class BaseHandler:
1717
_view_middleware = None
18-
_template_response_middleware = None
1918
_exception_middleware = None
2019
_middleware_chain = None
2120

@@ -26,7 +25,6 @@ def load_middleware(self):
2625
Must be called after the environment is fixed (see __call__ in subclasses).
2726
"""
2827
self._view_middleware = []
29-
self._template_response_middleware = []
3028
self._exception_middleware = []
3129

3230
get_response = self._get_response
@@ -61,10 +59,6 @@ def load_middleware(self):
6159
0,
6260
self.adapt_method_mode(mw_instance.process_view),
6361
)
64-
if hasattr(mw_instance, "process_template_response"):
65-
self._template_response_middleware.append(
66-
self.adapt_method_mode(mw_instance.process_template_response),
67-
)
6862
if hasattr(mw_instance, "process_exception"):
6963
# The exception-handling stack is still always synchronous for
7064
# now, so adapt that way.
@@ -145,27 +139,6 @@ def _get_response(self, request):
145139
# Complain if the view returned None (a common error).
146140
self.check_response(response, callback)
147141

148-
# If the response supports deferred rendering, apply template
149-
# response middleware and then render the response
150-
if hasattr(response, "render") and callable(response.render):
151-
for middleware_method in self._template_response_middleware:
152-
response = middleware_method(request, response)
153-
# Complain if the template response middleware returned None
154-
# (a common error).
155-
self.check_response(
156-
response,
157-
middleware_method,
158-
name="{}.process_template_response".format(
159-
middleware_method.__self__.__class__.__name__
160-
),
161-
)
162-
try:
163-
response = response.render()
164-
except Exception as e:
165-
response = self.process_exception_by_middleware(e, request)
166-
if response is None:
167-
raise
168-
169142
return response
170143

171144
def resolve_request(self, request):

bolt/runtime/global_settings.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -196,4 +196,4 @@
196196
#############
197197

198198
JINJA_LOADER = "jinja2.loaders.FileSystemLoader"
199-
JINJA_ENVIRONMENT = "bolt.jinja.defaults.create_default_environment"
199+
JINJA_ENVIRONMENT = "bolt.templates.jinja.defaults.create_default_environment"

bolt/templates/core.py

-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ class TemplateFileMissing(Exception):
88

99

1010
class Template:
11-
# TODO allow str template content?
1211
def __init__(self, filename: str) -> None:
1312
self.filename = filename
1413

bolt/utils/decorators.py

+2-16
Original file line numberDiff line numberDiff line change
@@ -122,22 +122,8 @@ def _wrapper_view(request, *args, **kwargs):
122122
if result is not None:
123123
return result
124124
raise
125-
if hasattr(response, "render") and callable(response.render):
126-
if hasattr(middleware, "process_template_response"):
127-
response = middleware.process_template_response(
128-
request, response
129-
)
130-
# Defer running of process_response until after the template
131-
# has been rendered:
132-
if hasattr(middleware, "process_response"):
133-
134-
def callback(response):
135-
return middleware.process_response(request, response)
136-
137-
response.add_post_render_callback(callback)
138-
else:
139-
if hasattr(middleware, "process_response"):
140-
return middleware.process_response(request, response)
125+
if hasattr(middleware, "process_response"):
126+
return middleware.process_response(request, response)
141127
return response
142128

143129
return _wrapper_view

bolt/views/base.py

-32
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,16 @@
11
import logging
22

3-
from bolt.csrf.middleware import get_token
43
from bolt.http import (
54
HttpRequest,
65
HttpResponse,
76
HttpResponseBase,
87
HttpResponseNotAllowed,
98
JsonResponse,
109
)
11-
from bolt.http.response import RenderableResponse
12-
from bolt.templates import Template
1310
from bolt.utils.decorators import classonlymethod
14-
from bolt.utils.functional import lazy
15-
from bolt.utils.html import format_html
16-
from bolt.utils.safestring import SafeString
1711

1812
from .exceptions import HttpResponseException
1913

20-
21-
def csrf_input(request):
22-
return format_html(
23-
'<input type="hidden" name="csrfmiddlewaretoken" value="{}">',
24-
get_token(request),
25-
)
26-
27-
28-
csrf_input_lazy = lazy(csrf_input, SafeString, str)
29-
csrf_token_lazy = lazy(get_token, str)
30-
3114
logger = logging.getLogger("bolt.request")
3215

3316

@@ -70,16 +53,6 @@ def view(request, *args, **kwargs):
7053

7154
return view
7255

73-
def get_base_context(self) -> dict:
74-
return {
75-
"request": self.request,
76-
"csrf_input": csrf_input_lazy(self.request),
77-
"csrf_token": csrf_token_lazy(self.request),
78-
}
79-
80-
def get_context(self) -> dict:
81-
return {}
82-
8356
def get_request_handler(self) -> callable:
8457
"""Return the handler for the current request method."""
8558

@@ -118,11 +91,6 @@ def get_response(self) -> HttpResponseBase:
11891
if isinstance(result, dict):
11992
return JsonResponse(result)
12093

121-
# TODO or see if has a render func?
122-
if isinstance(result, Template):
123-
context = {**self.get_base_context(), **self.get_context()}
124-
return RenderableResponse(result.render, context)
125-
12694
raise ValueError(f"Unexpected view return type: {type(result)}")
12795

12896
def _http_method_not_allowed(self) -> HttpResponse:

bolt/views/forms.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def form_invalid(self, form: "BaseForm") -> HttpResponse:
5656
**self.get_context(),
5757
"form": form,
5858
}
59-
return self.get_template_response(context)
59+
return self.get_template().render(context)
6060

6161
def get_context(self) -> dict:
6262
"""Insert the form into the context dict."""

bolt/views/objects.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ class ObjectTemplateViewMixin:
1010

1111
def get(self) -> HttpResponse:
1212
self.load_object()
13-
return self.get_template()
13+
return self.render_template()
1414

1515
def load_object(self) -> None:
1616
try:
@@ -191,7 +191,7 @@ class ListView(TemplateView):
191191

192192
def get(self) -> HttpResponse:
193193
self.objects = self.get_queryset()
194-
return self.get_template_response()
194+
return super().get()
195195

196196
def get_queryset(self): # Intentionally untyped... subclasses must override this.
197197
raise NotImplementedError(

0 commit comments

Comments
 (0)