import locale
import logging
import traceback

from channelguide import util
from exceptions import AuthError
from models import Channel, User
from models.user import AnonymousUser
from auth import SESSION_KEY

class UserMiddleware(object):
    """Add a User object to each request.

    Catch AuthError exceptions and redirect the user to the login page.
    """

    def process_request(self, req):
        if SESSION_KEY in req.session:
            try:
                username, password = req.session[SESSION_KEY]
            except:
                logging.warn("Error reading user session info:")
                logging.warn(traceback.format_exc())
                del req.session[SESSION_KEY]
                req.user = AnonymousUser()
                return
            query = User.query(username=username, hashed_password=password)
            query.join("channels")
            try:
                req.user = query.get(req.connection)
            except LookupError:
                req.user = AnonymousUser()
            else:
                req.connection.commit()
        else:
            req.user = AnonymousUser()

    def process_exception(self, request, exception):
        if isinstance(exception, AuthError):
            return util.send_to_login_page(request)

class ChannelCountMiddleware(object):
    def process_request(self, request):
        channel_count = Channel.query_approved().count(request.connection)
        request.connection.commit()
        request.total_channels = locale.format('%d', channel_count, True)


@@ -69,17 +69,27 @@
 ort util
+, settings
 %0A
-
 from exc
@@ -213,17 +213,71 @@
 ION_KEY%0A
+import hotshot, hotshot.stats, tempfile, StringIO, sys
 %0A
-
 class Us
@@ -1525,32 +1525,32 @@
 ection.commit()%0A
-
         request.
@@ -1608,8 +1608,1519 @@
  True)%0A%0A
+class ProfileMiddleware(object):%0A%0A    %22%22%22%0A%0A    Displays hotshot profiling for any view.%0A%0A    http://yoursite.com/yourview/?prof%0A%0A%0A%0A    Add the %22prof%22 key to query string by appending ?prof (or &prof=)%0A%0A    and you'll see the profiling results in your browser.%0A%0A    It's set up to only be available in django's debug mode,%0A%0A    but you really shouldn't add this middleware to any production configuration.%0A%0A    * Only tested on Linux%0A%0A    %22%22%22%0A%0A    def process_request(self, request):%0A%0A        if request.has_key('prof'):%0A%0A            self.tmpfile = tempfile.NamedTemporaryFile()%0A%0A            self.prof = hotshot.Profile(self.tmpfile.name)%0A%0A%0A%0A    def process_view(self, request, callback, callback_args, callback_kwargs):%0A%0A        if request.has_key('prof'):%0A%0A            return self.prof.runcall(callback, request, *callback_args, **callback_kwargs)%0A%0A%0A%0A    def process_response(self, request, response):%0A%0A        if request.has_key('prof'):%0A%0A            self.prof.close()%0A%0A%0A%0A            out = StringIO.StringIO()%0A%0A            old_stdout = sys.stdout%0A%0A            sys.stdout = out%0A%0A%0A%0A            stats = hotshot.stats.load(self.tmpfile.name)%0A%0A            #stats.strip_dirs()%0A%0A            stats.sort_stats('cumulative', 'calls')%0A%0A            stats.print_stats('channelguide/')%0A%0A%0A%0A            sys.stdout = old_stdout%0A%0A            stats_str = out.getvalue()%0A%0A%0A%0A            if response and response.content and stats_str:%0A%0A                response.content = %22%3Cpre%3E%22 + stats_str + %22%3C/pre%3E%22%0A%0A%0A%0A        return response%0A%0A

add profiling middleware