Skip to content
This repository
  • 4 commits
  • 17 files changed
  • 1 comment
  • 1 contributor
Jan 10, 2013
Neil Williams Middleware: Replace pylons.Response with raw WSGI.
pylons.Response is deprecated and we're not really using its
capabilities here anyway.
44f42ef
Neil Williams Toolbar: replace pylons.Response usage with simple abort. 6518852
Neil Williams Remove remaining (unused) imports of pylons.Response. 029f5c9
Neil Williams Replace c.response with pylons.response.
pylons.response is its own StackedObjectProxy and returning response
objects from controllers is deprecated so returning c.response is bad.

In many cases, this transition just involves returning content from the
controller directly rather than doing c.response.content = ___. This
will make the transition to Pylons 0.9.7 easier because WebOb's response
object doesn't have a content property and works differently.
14f3188
54  r2/r2/config/middleware.py
@@ -31,7 +31,7 @@
31 31
 from paste.registry import RegistryManager
32 32
 from paste.urlparser import StaticURLParser
33 33
 from paste.deploy.converters import asbool
34  
-from pylons import config, Response
  34
+from pylons import config, response
35 35
 from pylons.error import error_template
36 36
 from pylons.middleware import ErrorDocuments, ErrorHandler, StaticJavascripts
37 37
 from pylons.wsgiapp import PylonsApp, PylonsBaseWSGIApp
@@ -86,14 +86,8 @@ def error_mapper(code, message, environ, global_conf=None, **kw):
86 86
 
87 87
         #preserve x-sup-id when 304ing
88 88
         if code == 304:
89  
-            #check to see if c is useable
90  
-            try:
91  
-                c.test
92  
-            except TypeError:
93  
-                pass
94  
-            else:
95  
-                if c.response.headers.has_key('x-sup-id'):
96  
-                    d['x-sup-id'] = c.response.headers['x-sup-id']
  89
+            if response.headers.has_key('x-sup-id'):
  90
+                d['x-sup-id'] = response.headers['x-sup-id']
97 91
 
98 92
         extension = environ.get("extension")
99 93
         if extension:
@@ -179,17 +173,15 @@ def __call__(self, environ, start_response):
179 173
 
180 174
         # if there was a subreddit subdomain, redirect
181 175
         if sr_redirect and environ.get("FULLPATH"):
182  
-            r = Response()
183 176
             if not subdomains and g.domain_prefix:
184 177
                 subdomains.append(g.domain_prefix)
185 178
             subdomains.append(g.domain)
186 179
             redir = "%s/r/%s/%s" % ('.'.join(subdomains),
187 180
                                     sr_redirect, environ['FULLPATH'])
188 181
             redir = "http://" + redir.replace('//', '/')
189  
-            r.status_code = 301
190  
-            r.headers['location'] = redir
191  
-            r.content = ""
192  
-            return r(environ, start_response)
  182
+
  183
+            start_response("301 Moved Permanently", [("Location", redir)])
  184
+            return [""]
193 185
 
194 186
         return self.app(environ, start_response)
195 187
 
@@ -304,34 +296,28 @@ def __call__(self, environ, start_response):
304 296
         cl_key = 'CONTENT_LENGTH'
305 297
         if environ['REQUEST_METHOD'] == 'POST':
306 298
             if cl_key not in environ:
307  
-                r = Response()
308  
-                r.status_code = 411
309  
-                r.content = '<html><head></head><body>length required</body></html>'
310  
-                return r(environ, start_response)
  299
+                start_response("411 Length Required", [])
  300
+                return ['<html><body>length required</body></html>']
311 301
 
312 302
             try:
313 303
                 cl_int = int(environ[cl_key])
314 304
             except ValueError:
315  
-                r = Response()
316  
-                r.status_code = 400
317  
-                r.content = '<html><head></head><body>bad request</body></html>'
318  
-                return r(environ, start_response)
  305
+                start_response("400 Bad Request", [])
  306
+                return ['<html><body>bad request</body></html>']
319 307
 
320 308
             if cl_int > self.max_size:
321 309
                 from r2.lib.strings import string_dict
322 310
                 error_msg = string_dict['css_validator_messages']['max_size'] % dict(max_size = self.max_size/1024)
323  
-                r = Response()
324  
-                r.status_code = 413
325  
-                r.content = ("<html>"
326  
-                             "<head>"
327  
-                             "<script type='text/javascript'>"
328  
-                             "parent.completedUploadImage('failed',"
329  
-                             "''," 
330  
-                             "''," 
331  
-                             "[['BAD_CSS_NAME', ''], ['IMAGE_ERROR', '", error_msg,"']],"
332  
-                             "'image-upload');"
333  
-                             "</script></head><body>you shouldn\'t be here</body></html>")
334  
-                return r(environ, start_response)
  311
+                start_response("413 Too Big", [])
  312
+                return ["<html>"
  313
+                        "<head>"
  314
+                        "<script type='text/javascript'>"
  315
+                        "parent.completedUploadImage('failed',"
  316
+                        "'',"
  317
+                        "'',"
  318
+                        "[['BAD_CSS_NAME', ''], ['IMAGE_ERROR', '", error_msg,"']],"
  319
+                        "'image-upload');"
  320
+                        "</script></head><body>you shouldn\'t be here</body></html>"]
335 321
 
336 322
         return self.app(environ, start_response)
337 323
 
8  r2/r2/controllers/buttons.py
@@ -25,9 +25,9 @@
25 25
                           Bookmarklets, BoringPage)
26 26
 from r2.lib.pages.things import wrap_links
27 27
 from r2.models import *
28  
-from r2.lib.utils import tup
  28
+from r2.lib.utils import tup, to_js
29 29
 from r2.lib.validator import *
30  
-from pylons import c, request
  30
+from pylons import c, request, response
31 31
 from pylons.i18n import _
32 32
 
33 33
 class ButtonsController(RedditController):
@@ -81,7 +81,6 @@ def GET_button_embed(self, buttontype):
81 81
               styled = VBoolean('styled', default=True))
82 82
     def GET_button_lite(self, buttonimage, title, url, styled, newwindow):
83 83
         c.render_style = 'js'
84  
-        c.response_content_type = 'text/javascript; charset=UTF-8'
85 84
 
86 85
         if not url:
87 86
             url = request.referer
@@ -99,7 +98,8 @@ def builder_wrapper(thing = None):
99 98
                               styled = styled, **kw)
100 99
 
101 100
         bjs = self.get_wrapped_link(url, wrapper = builder_wrapper)
102  
-        return self.sendjs(bjs.render(), callback='', escape=False)
  101
+        response.content_type = "text/javascript"
  102
+        return to_js(bjs.render(), callback='', escape=False)
103 103
 
104 104
     def GET_button_demo_page(self):
105 105
         # no buttons for domain listings -> redirect to top level
5  r2/r2/controllers/captcha.py
@@ -23,12 +23,13 @@
23 23
 from reddit_base import RedditController
24 24
 import StringIO
25 25
 import r2.lib.captcha as captcha
26  
-from pylons import c
  26
+from pylons import c, response
27 27
 
28 28
 class CaptchaController(RedditController):
29 29
     def GET_captchaimg(self, iden):
30 30
         image = captcha.get_image(iden)
31 31
         f = StringIO.StringIO()
32 32
         image.save(f, "PNG")
33  
-        return self.sendpng(f.getvalue())
  33
+        response.content_type = "image/png;"
  34
+        return f.getvalue()
34 35
     
20  r2/r2/controllers/error.py
@@ -112,7 +112,6 @@ def __call__(self, environ, start_response):
112 112
 
113 113
 
114 114
     def send403(self):
115  
-        c.response.status_code = 403
116 115
         c.site = DefaultSR()
117 116
         if 'usable_error_content' in request.environ:
118 117
             return request.environ['usable_error_content']
@@ -124,15 +123,12 @@ def send403(self):
124 123
             return res.render()
125 124
 
126 125
     def send404(self):
127  
-        c.response.status_code = 404
128 126
         if 'usable_error_content' in request.environ:
129 127
             return request.environ['usable_error_content']
130 128
         return pages.RedditError(_("page not found"),
131 129
                                  _("the page you requested does not exist")).render()
132 130
 
133 131
     def send429(self):
134  
-        c.response.status_code = 429
135  
-
136 132
         retry_after = request.environ.get("retry_after")
137 133
         if retry_after:
138 134
             response.headers["Retry-After"] = str(retry_after)
@@ -145,8 +141,7 @@ def send429(self):
145 141
         return template.render(logo_url=static(g.default_header_url))
146 142
 
147 143
     def send503(self):
148  
-        c.response.status_code = 503
149  
-        c.response.headers['Retry-After'] = request.environ['retry_after']
  144
+        response.headers["Retry-After"] = str(request.environ["retry_after"])
150 145
         return request.environ['usable_error_content']
151 146
 
152 147
     def GET_document(self):
@@ -167,13 +162,12 @@ def GET_document(self):
167 162
                 c.site = Subreddit._by_name(srname)
168 163
             if c.render_style not in self.allowed_render_styles:
169 164
                 if code not in (204, 304):
170  
-                     c.response.content = str(code)
171  
-                c.response.status_code = code
172  
-                return c.response
  165
+                    return str(code)
  166
+                else:
  167
+                    return ""
173 168
             elif c.render_style in extensions.API_TYPES:
174 169
                 data = request.environ.get('extra_error_data', {'error': code})
175  
-                c.response.content = websafe_json(json.dumps(data))
176  
-                return c.response
  170
+                return websafe_json(json.dumps(data))
177 171
             elif takedown and code == 404:
178 172
                 link = Link._by_fullname(takedown)
179 173
                 return pages.TakedownPage(link).render()
@@ -192,8 +186,8 @@ def GET_document(self):
192 186
                 if request.GET.has_key('x-sup-id'):
193 187
                     x_sup_id = request.GET.get('x-sup-id')
194 188
                     if '\r\n' not in x_sup_id:
195  
-                        c.response.headers['x-sup-id'] = x_sup_id
196  
-                return c.response
  189
+                        response.headers['x-sup-id'] = x_sup_id
  190
+                return ""
197 191
             elif c.site:
198 192
                 return self.send404()
199 193
             else:
25  r2/r2/controllers/front.py
@@ -49,7 +49,7 @@
49 49
 from listingcontroller import ListingController
50 50
 from oauth2 import OAuth2ResourceController, require_oauth2_scope
51 51
 from api_docs import api_doc, api_section
52  
-from pylons import c, request, request, Response
  52
+from pylons import c, request, response
53 53
 from r2.models.token import EmailVerificationToken
54 54
 from r2.controllers.ipn import generate_blob
55 55
 
@@ -410,11 +410,10 @@ def GET_stylesheet(self):
410 410
                     must_revalidate=False,
411 411
                 )
412 412
 
413  
-            c.response_content_type = 'text/css'
414  
-            c.response.content =  stylesheet_contents
  413
+            response.content_type = 'text/css'
415 414
             if c.site.type == 'private':
416  
-                c.response.headers['X-Private-Subreddit'] = 'private'
417  
-            return c.response
  415
+                response.headers['X-Private-Subreddit'] = 'private'
  416
+            return stylesheet_contents
418 417
         else:
419 418
             return self.abort404()
420 419
 
@@ -979,8 +978,7 @@ def GET_sup(self, period):
979 978
         sup.set_expires_header()
980 979
 
981 980
         if c.extension == 'json':
982  
-            c.response.content = sup.sup_json(period)
983  
-            return c.response
  981
+            return sup.sup_json(period)
984 982
         else:
985 983
             return self.abort404()
986 984
 
@@ -991,8 +989,7 @@ def GET_sup(self, period):
991 989
     def GET_traffic(self, article):
992 990
         content = trafficpages.PromotedLinkTraffic(article)
993 991
         if c.render_style == 'csv':
994  
-            c.response.content = content.as_csv()
995  
-            return c.response
  992
+            return content.as_csv()
996 993
 
997 994
         return LinkInfoPage(link=article,
998 995
                             page_classes=["promoted-traffic"],
@@ -1005,8 +1002,7 @@ def GET_promo_traffic(self, link):
1005 1002
         if link:
1006 1003
             content = trafficpages.PromoTraffic(link)
1007 1004
             if c.render_style == 'csv':
1008  
-                c.response.content = content.as_csv()
1009  
-                return c.response
  1005
+                return content.as_csv()
1010 1006
             return LinkInfoPage(link=link,
1011 1007
                                 page_classes=["promo-traffic"],
1012 1008
                                 comment=None,
@@ -1237,14 +1233,13 @@ def GET_adminoff(self, dest):
1237 1233
     def GET_validuser(self):
1238 1234
         """checks login cookie to verify that a user is logged in and
1239 1235
         returns their user name"""
1240  
-        c.response_content_type = 'text/plain'
  1236
+        response.content_type = 'text/plain'
1241 1237
         if c.user_is_loggedin:
1242 1238
             # Change cookie based on can_wiki trac permissions
1243 1239
             perm = str(c.user.can_wiki(default=False))
1244  
-            c.response.content = c.user.name + "," + perm
  1240
+            return c.user.name + "," + perm
1245 1241
         else:
1246  
-            c.response.content = ''
1247  
-        return c.response
  1242
+            return ""
1248 1243
 
1249 1244
     def _render_opt_in_out(self, msg_hash, leave):
1250 1245
         """Generates the form for an optin/optout page"""
1  r2/r2/controllers/listingcontroller.py
@@ -47,7 +47,6 @@
47 47
 from api_docs import api_doc, api_section
48 48
 
49 49
 from pylons.i18n import _
50  
-from pylons import Response
51 50
 from pylons.controllers.util import redirect_to
52 51
 
53 52
 import random
2  r2/r2/controllers/mediaembed.py
@@ -56,7 +56,7 @@ def GET_mediaembed(self, link):
56 56
 
57 57
 class AdController(MinimalController):
58 58
     def request_key(self):
59  
-        return make_key('request_key',
  59
+        return make_key('request_',
60 60
                         c.lang,
61 61
                         c.content_langs,
62 62
                         request.host,
7  r2/r2/controllers/post.py
@@ -32,9 +32,6 @@
32 32
 import hashlib
33 33
 
34 34
 class PostController(ApiController):
35  
-    def api_wrapper(self, kw):
36  
-        return Storage(**kw)
37  
-
38 35
     def set_options(self, all_langs, pref_lang, **kw):
39 36
         if c.errors.errors:
40 37
             print "fucker"
@@ -180,7 +177,7 @@ def POST_optin(self, msg_hash):
180 177
     def POST_login(self, dest, *a, **kw):
181 178
         ApiController._handle_login(self, *a, **kw)
182 179
         c.render_style = "html"
183  
-        c.response_content_type = ""
  180
+        response.content_type = "text/html"
184 181
 
185 182
         if c.errors:
186 183
             return LoginPage(user_login = request.post.get('user'),
@@ -192,7 +189,7 @@ def POST_login(self, dest, *a, **kw):
192 189
     def POST_reg(self, dest, *a, **kw):
193 190
         ApiController._handle_register(self, *a, **kw)
194 191
         c.render_style = "html"
195  
-        c.response_content_type = ""
  192
+        response.content_type = "text/html"
196 193
 
197 194
         if c.errors:
198 195
             return LoginPage(user_reg = request.post.get('user'),
4  r2/r2/controllers/promotecontroller.py
@@ -184,11 +184,9 @@ def GET_graph(self):
184 184
     def GET_admingraph(self):
185 185
         content = Promote_Graph(admin_view=True)
186 186
         if c.render_style == 'csv':
187  
-            c.response.content = content.as_csv()
188  
-            return c.response
  187
+            return content.as_csv()
189 188
         return PromotePage("admingraph", content=content).render()
190 189
 
191  
-
192 190
     def GET_inventory(self, sr_name):
193 191
         '''
194 192
         Return available inventory data as json for use in ajax calls
69  r2/r2/controllers/reddit_base.py
@@ -53,6 +53,7 @@
53 53
     ForbiddenError,
54 54
     errors,
55 55
 )
  56
+from r2.lib.filters import _force_utf8
56 57
 from r2.lib.strings import strings
57 58
 from r2.lib.template_helpers import add_sr
58 59
 from r2.lib.tracking import encrypt, decrypt
@@ -63,6 +64,7 @@
63 64
     http_utils,
64 65
     is_subdomain,
65 66
     is_throttled,
  67
+    tup,
66 68
 )
67 69
 from r2.lib.validator import (
68 70
     build_arg_list,
@@ -368,7 +370,7 @@ def set_subreddit():
368 370
 def set_content_type():
369 371
     e = request.environ
370 372
     c.render_style = e['render_style']
371  
-    c.response_content_type = e['content_type']
  373
+    response.content_type = e['content_type']
372 374
 
373 375
     if e.has_key('extension'):
374 376
         c.extension = ext = e['extension']
@@ -376,7 +378,7 @@ def set_content_type():
376 378
             def to_js(content):
377 379
                 return utils.to_js(content, callback=request.params.get(
378 380
                     "callback", "document.write"))
379  
-            c.response_wrappers.append(to_js)
  381
+            c.response_wrapper = to_js
380 382
         if ext in ("rss", "api", "json") and request.method.upper() == "GET":
381 383
             user = valid_feed(request.GET.get("user"),
382 384
                               request.GET.get("feed"),
@@ -591,10 +593,9 @@ def cross_domain_handler(self, *args, **kwargs):
591 593
                 if cors_perms["origin_check"](g.origin):
592 594
                     name = request.environ["pylons.routes_dict"]["action_name"]
593 595
                     resp = fn(self, *args, **kwargs)
594  
-                    c.cookies.add('hoist_%s' % name, ''.join(resp.content))
595  
-                    c.response_content_type = 'text/html'
596  
-                    resp.content = ''
597  
-                    return resp
  596
+                    c.cookies.add('hoist_%s' % name, ''.join(tup(resp)))
  597
+                    response.content_type = 'text/html'
  598
+                    return ""
598 599
                 else:
599 600
                     abort(403)
600 601
             else:
@@ -638,7 +639,7 @@ def request_key(self):
638 639
         except CookieError:
639 640
             cookies_key = ''
640 641
 
641  
-        return make_key('request_key_',
  642
+        return make_key('request_',
642 643
                         c.lang,
643 644
                         c.content_langs,
644 645
                         request.host,
@@ -652,7 +653,7 @@ def request_key(self):
652 653
                         cookies_key)
653 654
 
654 655
     def cached_response(self):
655  
-        return c.response
  656
+        return response.content
656 657
 
657 658
     def pre(self):
658 659
         action = request.environ["pylons.routes_dict"].get("action")
@@ -661,7 +662,7 @@ def pre(self):
661 662
         else:
662 663
             c.request_timer = SimpleSillyStub()
663 664
 
664  
-        c.response_wrappers = []
  665
+        c.response_wrapper = None
665 666
         c.start_time = datetime.now(g.tz)
666 667
         c.request_timer.start()
667 668
         g.reset_caches()
@@ -692,7 +693,6 @@ def try_pagecache(self):
692 693
             r = g.pagecache.get(self.request_key())
693 694
             if r:
694 695
                 r, c.cookies = r
695  
-                response = c.response
696 696
                 response.headers = r.headers
697 697
                 response.content = r.content
698 698
 
@@ -712,24 +712,19 @@ def try_pagecache(self):
712 712
                 c.request_timer.name = request_timer_name("cached_response")
713 713
 
714 714
                 # make sure to carry over the content type
715  
-                c.response_content_type = r.headers['content-type']
  715
+                response.content_type = r.headers['content-type']
716 716
                 c.used_cache = True
717 717
                 # response wrappers have already been applied before cache write
718  
-                c.response_wrappers = []
719  
-
  718
+                c.response_wrapper = None
720 719
 
721 720
     def post(self):
722 721
         c.request_timer.intermediate("action")
723 722
 
724  
-        response = c.response
725  
-        content = filter(None, response.content)
726  
-        if isinstance(content, (list, tuple)):
727  
-            content = ''.join(content)
728  
-        for w in c.response_wrappers:
729  
-            content = w(content)
730  
-        response.content = content
731  
-        if c.response_content_type:
732  
-            response.headers['Content-Type'] = c.response_content_type
  723
+        if c.response_wrapper:
  724
+            content = "".join(_force_utf8(x)
  725
+                              for x in tup(response.content) if x)
  726
+            wrapped_content = c.response_wrapper(content)
  727
+            response.content = wrapped_content
733 728
 
734 729
         if c.user_is_loggedin and not c.allow_loggedin_cache:
735 730
             response.headers['Cache-Control'] = 'no-cache'
@@ -738,18 +733,16 @@ def post(self):
738 733
         if c.deny_frames:
739 734
             response.headers["X-Frame-Options"] = "DENY"
740 735
 
741  
-        #return
742 736
         #set content cache
743 737
         if (g.page_cache_time
744 738
             and request.method.upper() == 'GET'
745 739
             and (not c.user_is_loggedin or c.allow_loggedin_cache)
746 740
             and not c.used_cache
747  
-            and response.status_code not in (429, 503)
748  
-            and response.content and response.content[0]):
  741
+            and response.status_code not in (429, 503)):
749 742
             try:
750 743
                 g.pagecache.set(self.request_key(),
751  
-                                  (response, c.cookies),
752  
-                                  g.page_cache_time)
  744
+                                (response._current_obj(), c.cookies),
  745
+                                g.page_cache_time)
753 746
             except MemcachedError as e:
754 747
                 # this codepath will actually never be hit as long as
755 748
                 # the pagecache memcached client is in no_reply mode.
@@ -819,11 +812,6 @@ def OPTIONS(self):
819 812
         """Return empty responses for CORS preflight requests"""
820 813
         self.check_cors()
821 814
 
822  
-    def sendpng(self, string):
823  
-        c.response_content_type = 'image/png'
824  
-        c.response.content = string
825  
-        return c.response
826  
-
827 815
     def update_qstring(self, dict):
828 816
         merged = copy(request.get)
829 817
         merged.update(dict)
@@ -831,18 +819,7 @@ def update_qstring(self, dict):
831 819
 
832 820
     def api_wrapper(self, kw):
833 821
         data = simplejson.dumps(kw)
834  
-        c.response.content = filters.websafe_json(data)
835  
-        return c.response
836  
-
837  
-    def iframe_api_wrapper(self, kw):
838  
-        data = simplejson.dumps(kw)
839  
-        c.response_content_type = 'text/html'
840  
-        c.response.content = (
841  
-            '<html><head><script type="text/javascript">\n'
842  
-            'parent.$.handleResponse().call('
843  
-            'parent.$("#" + window.frameElement.id).parent(), %s)\n'
844  
-            '</script></head></html>') % filters.websafe_json(data)
845  
-        return c.response
  822
+        return filters.websafe_json(data)
846 823
 
847 824
 
848 825
 class RedditController(MinimalController):
@@ -1036,7 +1013,7 @@ def abort_if_not_modified(self, last_modified, private=True,
1036 1013
         last_modified = last_modified.replace(microsecond=0)
1037 1014
 
1038 1015
         date_str = http_utils.http_date_str(last_modified)
1039  
-        c.response.headers['last-modified'] = date_str
  1016
+        response.headers['last-modified'] = date_str
1040 1017
 
1041 1018
         cache_control = []
1042 1019
         if private:
@@ -1044,7 +1021,7 @@ def abort_if_not_modified(self, last_modified, private=True,
1044 1021
         cache_control.append('max-age=%d' % max_age.total_seconds())
1045 1022
         if must_revalidate:
1046 1023
             cache_control.append('must-revalidate')
1047  
-        c.response.headers['cache-control'] = ', '.join(cache_control)
  1024
+        response.headers['cache-control'] = ', '.join(cache_control)
1048 1025
 
1049 1026
         modified_since = request.if_modified_since
1050 1027
         if modified_since and modified_since >= last_modified:
7  r2/r2/controllers/toolbar.py
@@ -30,7 +30,7 @@
30 30
 from r2.lib.template_helpers import add_sr
31 31
 from r2.lib import utils
32 32
 from r2.lib.validator import *
33  
-from pylons import c, Response
  33
+from pylons import c
34 34
 from r2.models.admintools import is_shamed_domain
35 35
 
36 36
 import string
@@ -174,11 +174,8 @@ def GET_s(self, rest):
174 174
 
175 175
         # we don't want clients to think that this URL is actually a
176 176
         # valid URL for search-indexing or the like
177  
-        c.response = Response()
178  
-        c.response.status_code = 404
179 177
         request.environ['usable_error_content'] = spaceCompress(res.render())
180  
-
181  
-        return c.response
  178
+        abort(404)
182 179
 
183 180
     @validate(link = VLink('id'))
184 181
     def GET_comments(self, link):
2  r2/r2/controllers/wiki.py
@@ -20,7 +20,7 @@
20 20
 ## reddit Inc. All Rights Reserved.
21 21
 ###############################################################################
22 22
 
23  
-from pylons import request, g, c, Response
  23
+from pylons import request, g, c
24 24
 from pylons.controllers.util import redirect_to
25 25
 from reddit_base import RedditController
26 26
 from r2.lib.utils import url_links
13  r2/r2/lib/base.py
@@ -24,7 +24,7 @@
24 24
 import pycassa.pool
25 25
 import sqlalchemy.exc
26 26
 
27  
-from pylons import Response, c, g, request, session, config
  27
+from pylons import c, g, request, session, config, response
28 28
 from pylons.controllers import WSGIController, Controller
29 29
 from pylons.i18n import N_, _, ungettext, get_lang
30 30
 from paste import httpexceptions
@@ -141,7 +141,6 @@ def __call__(self, environ, start_response):
141 141
             request.environ['pylons.routes_dict']['action_name'] = action
142 142
             request.environ['pylons.routes_dict']['action'] = handler_name
143 143
                     
144  
-        c.response = Response()
145 144
         try:
146 145
             res = WSGIController.__call__(self, environ, start_response)
147 146
         except Exception as e:
@@ -221,14 +220,8 @@ def redirect(cls, dest, code = 302):
221 220
         sends the user to that location with the provided HTTP code.
222 221
         """
223 222
         dest = cls.format_output_url(dest or "/")
224  
-        c.response.headers['Location'] = dest
225  
-        c.response.status_code = code
226  
-        return c.response
227  
-
228  
-    def sendjs(self,js, callback="document.write", escape=True):
229  
-        c.response.headers['Content-Type'] = 'text/javascript'
230  
-        c.response.content = to_js(js, callback, escape)
231  
-        return c.response
  223
+        response.status_code = code
  224
+        response.headers['Location'] = dest
232 225
 
233 226
 class EmbedHandler(urllib2.BaseHandler, urllib2.HTTPHandler,
234 227
                    urllib2.HTTPErrorProcessor, urllib2.HTTPDefaultErrorHandler):
2  r2/r2/lib/jsonresponse.py
@@ -40,7 +40,7 @@ class JsonResponse(object):
40 40
     api func.
41 41
     """
42 42
 
43  
-    content_type = 'application/json; charset=UTF-8'
  43
+    content_type = 'application/json'
44 44
 
45 45
     def __init__(self):
46 46
         self._clear()
3  r2/r2/lib/pages/pages.py
@@ -93,8 +93,7 @@ def responsive(res, space_compress = False):
93 93
             res = "%s(%s)" % (websafe_json(c.allowed_callback), res)
94 94
     elif space_compress:
95 95
         res = spaceCompress(res)
96  
-    c.response.content = res
97  
-    return c.response
  96
+    return res
98 97
 
99 98
 class Reddit(Templated):
100 99
     '''Base class for rendering a page on reddit.  Handles toolbar creation,
6  r2/r2/lib/sup.py
@@ -30,7 +30,7 @@
30 30
 from r2.lib.utils import rfc3339_date_str, http_date_str, to36
31 31
 from r2.lib.memoize import memoize
32 32
 from r2.lib.template_helpers import get_domain
33  
-from pylons import g, c
  33
+from pylons import g, c, response
34 34
 
35 35
 PERIODS = [600, 300, 60]
36 36
 MIN_PERIOD = min(PERIODS)
@@ -104,10 +104,10 @@ def sup_json(period):
104 104
 
105 105
 def set_sup_header(user, action):
106 106
     sup_id = make_sup_id(user, action)
107  
-    c.response.headers['x-sup-id'] = sup_url() + '#' + sup_id
  107
+    response.headers['x-sup-id'] = sup_url() + '#' + sup_id
108 108
 
109 109
 def set_expires_header():
110 110
     seconds = make_cur_time(MIN_PERIOD) + MIN_PERIOD
111 111
     expire_time = datetime.fromtimestamp(seconds, g.tz)
112  
-    c.response.headers['expires'] = http_date_str(expire_time)
  112
+    response.headers['expires'] = http_date_str(expire_time)
113 113
 
9  r2/r2/lib/validator/validator.py
@@ -213,7 +213,7 @@ def newfn(self, *a, **env):
213 213
                     else:
214 214
                         responder = JsonResponse()
215 215
 
216  
-                    c.response_content_type = responder.content_type
  216
+                    response.content_type = responder.content_type
217 217
 
218 218
                     try:
219 219
                         kw = _make_validated_kw(fn, simple_vals, param_vals, env)
@@ -291,7 +291,12 @@ def wrapped_self_method(*a, **kw):
291 291
         if val:
292 292
             return val
293 293
         else:
294  
-            return self.iframe_api_wrapper(responder.make_response())
  294
+            data = simplejson.dumps(responder.make_response())
  295
+            response.content_type = "text/html"
  296
+            return ('<html><head><script type="text/javascript">\n'
  297
+                    'parent.$.handleResponse().call('
  298
+                    'parent.$("#" + window.frameElement.id).parent(), %s)\n'
  299
+                    '</script></head></html>') % filters.websafe_json(data)
295 300
     return _validatedForm(self, wrapped_self_method, responder, simple_vals,
296 301
                           param_vals, *a, **kw)
297 302
 

Showing you all comments on commits in this comparison.

Ben Carleton

frustrating code is frustrating

Something went wrong with that request. Please try again.