2011-10-04 64 views
7

下面是我使用的中間件:ContentNotRenderedError升級

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 

已完全爲我工作最多的Django 1.3,但是這打破了,當我升級到Django的主幹(1.4+)今天,隨着例外: -

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. 

如果有人使用django trunk將我指向正確的方向,將不勝感激。謝謝!

+1

我不知道。但根據消息的外觀,新版本不允許您訪問process_view中的響應內容,它應該在另一箇中間件視圖中訪問。 =/ –

回答

3

Hacktastic解決方案: 可以防止這種通過檢查響應有一個is_rendered屬性,如果是這樣,這是改變STATS串如下之前真:

if response: 
     if (hasattr(response,'is_rendered') and response.is_rendered or not hasattr(response,'is_rendered')) 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 
+0

當我升級到django 1.4時,這並沒有解決我應用程序中的同樣問題 - 我仍然在尋找解決方案 –