Dưới đây là một trung gian mà tôi sử dụng:ContentNotRenderedError sau một django nâng cấp
class StatsMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
# get number of db queries before we do anything
n = len(connection.queries)
# time the view
start = time.time()
response = view_func(request, *view_args, **view_kwargs)
totTime = time.time() - start
# compute the db time for the queries just run
queries = len(connection.queries) - n
if queries:
dbTime = reduce(add, [float(q['time'])
for q in connection.queries[n:]])
else:
dbTime = 0.0
# and backout python time
pyTime = totTime - dbTime
stats = {
'totTime': totTime,
'pyTime': pyTime,
'dbTime': dbTime,
'queries': queries,
'sql': '<br />'.join([ '<div class="stats_sql_query">%s</div><div class="stats_sql_time">%s s</div>' % (q['sql'], q['time']) for q in connection.queries[n:]]),
}
# clean query cache
db.reset_queries()
# replace the comment if found
if response and response.content:
s = response.content
regexp = re.compile(r'(?P<cmt><!--\s*STATS:(?P<fmt>.*?)-->)')
match = regexp.search(s)
if match:
s = s[:match.start('cmt')] + \
match.group('fmt') % stats + \
s[match.end('cmt'):]
response.content = s
return response
Nó đã làm việc một cách hoàn hảo cho tôi lên đến django 1.3 nhưng điều này đã phá vỡ khi tôi nâng cấp lên django thân cây (1.4+) hôm nay, với sự ngoại lệ: -
Traceback:
File "./../django-trunk/django/core/handlers/base.py" in get_response
105. response = middleware_method(request, callback, callback_args, callback_kwargs)
File "misc/middleware.py" in process_view
63. if response and response.content:
File "./../django-trunk/django/template/response.py" in _get_content
123. raise ContentNotRenderedError('The response content must be '
Exception Type: ContentNotRenderedError at/
Exception Value: The response content must be rendered before it can be accessed.
Sẽ đánh giá cao nếu một số người dùng django trunk chỉ cho tôi đi đúng hướng. Cảm ơn!
Tôi không biết. Nhưng do giao diện của thông báo, phiên bản mới hơn không cho phép bạn truy cập vào nội dung phản hồi trong process_view nữa, nó sẽ được truy cập trong một chế độ xem trung gian khác. =/ –