]> git.openstreetmap.org Git - osqa.git/blob - forum/views/decorators.py
Correct text
[osqa.git] / forum / views / decorators.py
1 # -*- coding: utf-8 -*-
2 import json
3 import logging
4
5 from datetime import datetime
6
7 from django.http import HttpResponse, HttpResponseRedirect
8 from django.shortcuts import render_to_response
9 from django.core.urlresolvers import reverse
10 from django.template import RequestContext
11 from django.utils.translation import ugettext as _
12
13 from forum.modules import ui, decorate
14 from forum.settings import ONLINE_USERS
15
16 def login_required(func, request, *args, **kwargs):
17     if not request.user.is_authenticated():
18         return HttpResponseRedirect(reverse('auth_signin'))
19     else:
20         return func(request, *args, **kwargs)
21
22 def render(template=None, tab=None, tab_title='', weight=500, tabbed=True):
23     def decorator(func):        
24         def decorated(context, request, *args, **kwargs):
25             if request.user.is_authenticated():
26                 ONLINE_USERS[request.user] = datetime.now()
27
28             if isinstance(context, HttpResponse):
29                 return context
30
31             if tab is not None:
32                 context['tab'] = tab
33
34             return render_to_response(context.pop('template', template), context,
35                                       context_instance=RequestContext(request))
36
37         if tabbed and tab and tab_title:
38             ui.register(ui.PAGE_TOP_TABS,
39                         ui.PageTab(tab, tab_title, lambda: reverse(func.__name__), weight=weight))
40             
41         return decorate.result.withfn(decorated, needs_params=True)(func)
42
43     return decorator
44
45 class CommandException(Exception):
46     pass
47
48 class RefreshPageCommand(HttpResponse):
49     def __init__(self):
50         super(RefreshPageCommand, self).__init__(
51                 content=json.dumps({'commands': {'refresh_page': []}, 'success': True}),
52                 mimetype="application/json")
53
54 def command(func, request, *args, **kwargs):
55     try:
56         response = func(request, *args, **kwargs)
57
58         if isinstance(response, HttpResponse):
59             return response
60
61         response['success'] = True
62     except Exception, e:
63         import traceback
64         #traceback.print_exc()
65
66         if isinstance(e, CommandException):
67             response = {
68             'success': False,
69             'error_message': e.message
70             }
71         else:
72             logging.error("%s: %s" % (func.__name__, str(e)))
73             logging.error(traceback.format_exc())
74             response = {
75             'success': False,
76             'error_message': _("We're sorry, but an unknown error ocurred.<br />Please try again in a while.")
77             }
78
79     if request.is_ajax():
80         return HttpResponse(json.dumps(response), mimetype="application/json")
81     else:
82         return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
83