def publish(self, message): if not self.backlog_length: raise Exception("Cannot publish to a RealtimeChannel without a backlog_length set.") id = self.msg_id.incr() self.msg_backlog.zadd(util.client_dumps(message), id) self.pubsub.publish(util.client_dumps({'id': id, 'payload': message})) self.msg_backlog.zremrangebyscore('-inf', id - self.backlog_length) if self.ttl: self.msg_id.expire(self.ttl) self.msg_backlog.expire(self.ttl)
def publish(self, message): if not self.backlog_length: raise Exception( "Cannot publish to a RealtimeChannel without a backlog_length set." ) id = self.msg_id.incr() self.msg_backlog.zadd(util.client_dumps(message), id) self.pubsub.publish(util.client_dumps({'id': id, 'payload': message})) self.msg_backlog.zremrangebyscore('-inf', id - self.backlog_length) if self.ttl: self.msg_id.expire(self.ttl) self.msg_backlog.expire(self.ttl)
def to_json(things): """ If the model/object defines a "to_client" then call it first. This way objects can implement the "to_client" interface to return a dictionary representation of themselves to be serialized as json. """ return util.js_safety(util.client_dumps(things))
def JSONPResponse(request, response, **kwargs): callback = request.GET.get('callback', 'callback') if not callback.replace('_', '').isalnum(): raise ServiceError() return HttpResponse( '%s(%s);' % (callback, client_dumps(response, viewer=request.user)), mimetype='application/javascript', **kwargs)
def daily_sticker_activity_json(user): activity = None if user.kv.has_unseen_daily_free_stickers.get(): user.kv.has_unseen_daily_free_stickers.delete() activity = DailyFreeStickersActivity({ 'reward_stickers': knobs.DAILY_FREE_STICKERS, }, actor=user) activity = activity_stream_item(activity, user) return util.js_safety(util.client_dumps(activity))
def process_response(self, request, response): if response.status_code == 403 and request.META.get('HTTP_X_SESSIONID'): import traceback import sys stack = str(request.path_info) + '\n' #stack += request.body + '\n' if request.user.is_authenticated(): stack += request.user.username + '\n' import time stack += str(time.time()) + '\n' import re regex_http_ = re.compile(r'^HTTP_.+$') regex_content_type = re.compile(r'^CONTENT_TYPE$') regex_content_length = re.compile(r'^CONTENT_LENGTH$') request_headers = {} for header in request.META: if regex_http_.match(header) or regex_content_type.match(header) or regex_content_length.match(header): request_headers[header] = request.META[header] stack += '\n'.join('{}: {}'.format(k,v) for k,v in request_headers.items()) + '\n' import traceback tb = traceback.format_exc() stack += unicode(tb) stack += '\n'.join('{}: {}'.format(k,v) for k,v in request.COOKIES.items()) + '\n' stack += '\n' + unicode(response.content) stack += '\n'.join(traceback.format_exception(*sys.exc_info())) stk = traceback.extract_stack() for mod, lineno, fun_name, call_code_text in stk: stack += "[%s:%i] in %s" % (mod, lineno, fun_name) from django.core.mail import send_mail send_mail('403 stack trace', stack, '*****@*****.**', ['*****@*****.**'], fail_silently=False) user_agent = request.META.get('HTTP_USER_AGENT') version = AppVersionMiddleware.get_version_from_user_agent(user_agent) if version is None or version in ['1.0.1', '1.0.2']: return response response = {'success': False, 'error_type': 'ServiceError', 'reason': 'Sorry! To fix your app, please sign-out and sign-in again: tap Profile, tap the gear icon in the top right, then tap Sign Out. Please contact us if you need more help: [email protected]'} #if 'activities' in request.META['PATH_INFO']: # response = {'success': True, 'activities': []} #else: # response = {'success': False, 'error_type': 'ServiceError', 'reason': 'Error code 403, please try again.'} return HttpResponse(util.client_dumps(response), mimetype='application/json') return response
def ServiceResponse(request, response, **kwargs): """ Serializes the response to primarily JSON, but you can force it to produce YAML by sending a format=yaml request variable. """ formatted_response = client_dumps(response) if request.POST.get("format") == "yaml": formatted_response = yaml.safe_dump(loads(formatted_response), default_flow_style=False) # Allows us to force a mimetype in a request arg. mimetype = request.POST.get("force_mimetype", 'application/json') return HttpResponse(formatted_response, mimetype, **kwargs)
def ServiceResponse(request, response, **kwargs): """ Serializes the response to primarily JSON, but you can force it to produce YAML by sending a format=yaml request variable. """ formatted_response = client_dumps(response, viewer=request.user) def get_yaml(): return yaml.safe_dump(loads(formatted_response), default_flow_style=False) if request.POST.get('format') == 'yaml': formatted_response = get_yaml() elif request.POST.get('format') == 'html': return r2r_jinja('api_response.html', {'yaml': get_yaml()}) # Allows us to force a mimetype in a request arg. mimetype = request.POST.get('force_mimetype', 'application/json') return HttpResponse(formatted_response, mimetype, **kwargs)
def process_request(self, request): if request.user.is_authenticated(): if 'sandbox' in request.user_kv: if request.META['PATH_INFO'].startswith('/api'): # Deactivated users cannot access anything outside of the sandbox. 403 Forbidden any other # request. if not request.user.is_active: return HttpResponseForbidden(util.client_dumps({'reason': 'deactivated'})) # Otherwise fall though and serve API requests, user is just warned. elif not request.META['PATH_INFO'].startswith(request.user_kv['sandbox']): # Request for a page outside of the sandbox, redirect to the sandbox. return HttpResponseRedirect(request.user_kv['sandbox']) elif not request.user.is_active: # Deactivated user with no sandbox, log them out, boot them to / logout(request) return HttpResponseRedirect('/')
def process_request(self, request): if request.user.is_authenticated(): if 'sandbox' in request.user_kv: if request.META['PATH_INFO'].startswith('/api'): # Deactivated users cannot access anything outside of the sandbox. 403 Forbidden any other # request. if not request.user.is_active: return HttpResponseForbidden( util.client_dumps({'reason': 'deactivated'})) # Otherwise fall though and serve API requests, user is just warned. elif not request.META['PATH_INFO'].startswith( request.user_kv['sandbox']): # Request for a page outside of the sandbox, redirect to the sandbox. return HttpResponseRedirect(request.user_kv['sandbox']) elif not request.user.is_active: # Deactivated user with no sandbox, log them out, boot them to / logout(request) return HttpResponseRedirect('/')
def response_wrapper(ret): ret = loads(ret) ret['success'] = True ret = client_dumps(ret) return HttpResponse(ret, 'application/json')
def test_client_dumps(self): self.assertEqual('{}', util.client_dumps({}))
def test_sticker_details(self): util.client_dumps(stickers.all_details())
def process_request(self, request): if (request.META['PATH_INFO'].startswith('/staff') and not (request.user.is_authenticated() and request.user.is_staff)): return HttpResponseForbidden(util.client_dumps({'reason': 'staff_only'}))
def JSONPResponse(request, response, **kwargs): callback = request.GET.get('callback', 'callback') if not callback.replace('_', '').isalnum(): raise ServiceError() return HttpResponse('%s(%s);' % (callback, client_dumps(response, viewer=request.user)), mimetype='application/javascript', **kwargs)
def process_request(self, request): if request.META["PATH_INFO"].startswith("/staff") and not ( request.user.is_authenticated() and request.user.is_staff ): return HttpResponseForbidden(util.client_dumps({"reason": "staff_only"}))
def to_escaped_json(things): return util.js_safety(util.client_dumps(things), django=False, escape_html=True)
def process_request(self, request): if (request.META['PATH_INFO'].startswith('/staff') and not (request.user.is_authenticated() and request.user.is_staff)): return HttpResponseForbidden( util.client_dumps({'reason': 'staff_only'}))
def process_response(self, request, response): if response.status_code == 403 and request.META.get( 'HTTP_X_SESSIONID'): import traceback import sys stack = str(request.path_info) + '\n' #stack += request.body + '\n' if request.user.is_authenticated(): stack += request.user.username + '\n' import time stack += str(time.time()) + '\n' import re regex_http_ = re.compile(r'^HTTP_.+$') regex_content_type = re.compile(r'^CONTENT_TYPE$') regex_content_length = re.compile(r'^CONTENT_LENGTH$') request_headers = {} for header in request.META: if regex_http_.match(header) or regex_content_type.match( header) or regex_content_length.match(header): request_headers[header] = request.META[header] stack += '\n'.join('{}: {}'.format(k, v) for k, v in request_headers.items()) + '\n' import traceback tb = traceback.format_exc() stack += unicode(tb) stack += '\n'.join('{}: {}'.format(k, v) for k, v in request.COOKIES.items()) + '\n' stack += '\n' + unicode(response.content) stack += '\n'.join(traceback.format_exception(*sys.exc_info())) stk = traceback.extract_stack() for mod, lineno, fun_name, call_code_text in stk: stack += "[%s:%i] in %s" % (mod, lineno, fun_name) from django.core.mail import send_mail send_mail('403 stack trace', stack, '*****@*****.**', ['*****@*****.**'], fail_silently=False) user_agent = request.META.get('HTTP_USER_AGENT') version = AppVersionMiddleware.get_version_from_user_agent( user_agent) if version is None or version in ['1.0.1', '1.0.2']: return response response = { 'success': False, 'error_type': 'ServiceError', 'reason': 'Sorry! To fix your app, please sign-out and sign-in again: tap Profile, tap the gear icon in the top right, then tap Sign Out. Please contact us if you need more help: [email protected]' } #if 'activities' in request.META['PATH_INFO']: # response = {'success': True, 'activities': []} #else: # response = {'success': False, 'error_type': 'ServiceError', 'reason': 'Error code 403, please try again.'} return HttpResponse(util.client_dumps(response), mimetype='application/json') return response