Remove unused imports in Melange modules.
[Melange.git] / app / soc / views / helper / responses.py
blobef6785a01bb9a1c2286a9436024f3d41703be0c4
1 #!/usr/bin/python2.5
3 # Copyright 2008 the Melange authors.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 """Helpers used to render response.
18 """
20 __authors__ = [
21 '"Todd Larsen" <tlarsen@google.com>',
22 '"Pawel Solyga" <pawel.solyga@gmail.com>',
23 '"Sverre Rabbelier" <sverre@rabbelier.nl>',
27 from google.appengine.api import users
29 from django import http
30 from django.template import loader
32 from soc.logic import accounts
33 from soc.logic import system
34 from soc.logic.models import site
35 from soc.logic.models.user import logic as user_logic
36 from soc.modules import callback
37 from soc.views import helper
38 from soc.views.helper import redirects
39 from soc.views.helper import templates
42 def respond(request, template, context=None, response_args=None,
43 response_headers=None):
44 """Helper to render a response, passing standard stuff to the response.
46 Args:
47 request: the Django HTTP request object
48 template: the template (or search list of templates) to render
49 context: the context supplied to the template (implements dict)
50 response_args: keyword arguments passed to http.HttpResponse()
51 (response_args['content'] is created with
52 render_to_string(template, dictionary=context) if it is not present)
53 response_headers: optional dict containing HTTP response header names
54 and corresponding values to set in the HttpResponse object before it
55 is returned; default is None
57 Returns:
58 django.shortcuts.render_to_response(template, context) results
60 Raises:
61 Any exceptions that django.template.loader.render_to_string() or
62 django.http.HttpResponse() might raise.
63 """
65 if not context:
66 from soc.views.helper import params
67 context = getUniversalContext(request)
68 useJavaScript(context, params.DEF_JS_USES_LIST)
70 if response_args is None:
71 response_args = {}
73 if 'content' not in response_args:
74 content = loader.render_to_string(template, dictionary=context)
75 response_args['content'] = content.strip('\n')
77 http_response = http.HttpResponse(**response_args)
79 if response_headers:
80 for key, value in response_headers.iteritems():
81 http_response[key] = value
83 return http_response
86 def getUniversalContext(request):
87 """Constructs a template context dict will many common variables defined.
89 Args:
90 request: the Django HTTP request object
92 Returns:
93 a new context dict containing:
96 'request': the Django HTTP request object passed in by the caller
97 'account': the logged-in Google Account if there is one
98 'user': the User entity corresponding to the Google Account in
99 context['account']
100 'is_admin': True if users.is_current_user_admin() is True
101 'is_debug': True if system.isDebug() is True
102 'sign_in': a Google Account login URL
103 'sign_out': a Google Account logout URL
104 'sidebar_menu_html': an HTML string that renders the sidebar menu
108 account = accounts.getCurrentAccount()
109 user = None
110 is_admin = False
112 context = {}
113 context['request'] = request
115 if account:
116 user = user_logic.getForAccount(account)
117 is_admin = user_logic.isDeveloper(account=account, user=user)
119 context['account'] = account
120 context['user'] = user
121 context['is_admin'] = is_admin
123 context['is_local'] = system.isLocal()
124 context['is_debug'] = system.isDebug()
125 context['sign_in'] = users.create_login_url(request.path)
126 context['sign_out'] = users.create_logout_url(request.path)
128 context['sidebar_menu_items'] = callback.getCore().getSidebar(account, user)
130 context['gae_version'] = system.getAppVersion()
131 context['soc_release'] = system.getMelangeVersion()
133 settings = site.logic.getSingleton()
135 context['ga_tracking_num'] = settings.ga_tracking_num
136 context['gmaps_api_key'] = settings.gmaps_api_key
137 context['site_name'] = settings.site_name
138 context['site_notice'] = settings.site_notice
139 context['tos_link'] = redirects.getToSRedirect(settings)
141 return context
143 def useJavaScript(context, uses):
144 """Updates the context for JavaScript usage.
147 for use in uses:
148 context['uses_%s' % use] = True
150 def redirectToChangedSuffix(
151 request, old_suffix, new_suffix=None, params=None):
152 """Changes suffix of URL path and returns an HTTP redirect response.
154 Args:
155 request: the Django HTTP request object; redirect path is derived from
156 request.path
157 old_suffix, new_suffix, params: see helper.requests.replaceSuffix()
159 Returns:
160 a Django HTTP redirect response pointing to the altered path.
162 path = helper.requests.replaceSuffix(request.path, old_suffix, new_suffix,
163 params=params)
164 return http.HttpResponseRedirect(path)
167 def errorResponse(error, request, template=None, context=None):
168 """Creates an HTTP response from the soc.views.out_of_band.Error exception.
170 Args:
171 errror: a out_of_band.Error object
172 request: a Django HTTP request
173 template: the "sibling" template (or a search list of such templates)
174 from which to construct the actual template name (or names)
175 context: optional context dict supplied to the template, which is
176 modified (so supply a copy if such modification is not acceptable)
178 if not context:
179 context = error.context
181 if not context:
182 from soc.views.helper import params
183 context = getUniversalContext(request)
184 useJavaScript(context, params.DEF_JS_USES_LIST)
186 if not template:
187 template = []
189 # make a list of possible "sibling" templates, then append a default
190 sibling_templates = templates.makeSiblingTemplatesList(template,
191 error.TEMPLATE_NAME, default_template=error.DEF_TEMPLATE)
193 context['status'] = error.response_args.get('status')
195 if not context.get('message'):
196 # supplied context did not explicitly override the message
197 context['message'] = error.message_fmt % context
199 return respond(request, sibling_templates, context=context,
200 response_args=error.response_args)