def test_json_body_alternate_charset(self): from pyramid.compat import json request = self._makeOne({"REQUEST_METHOD": "POST"}) inp = text_(b"/\xe6\xb5\x81\xe8\xa1\x8c\xe8\xb6\x8b\xe5\x8a\xbf", "utf-8") if PY3: # pragma: no cover body = bytes(json.dumps({"a": inp}), "utf-16") else: body = json.dumps({"a": inp}).decode("utf-8").encode("utf-16") request.body = body request.content_type = "application/json; charset=utf-16" self.assertEqual(request.json_body, {"a": inp})
def test_json_body_alternate_charset(self): from pyramid.compat import json request = self._makeOne({'REQUEST_METHOD':'POST'}) inp = text_( b'/\xe6\xb5\x81\xe8\xa1\x8c\xe8\xb6\x8b\xe5\x8a\xbf', 'utf-8' ) if PY3: # pragma: no cover body = bytes(json.dumps({'a':inp}), 'utf-16') else: body = json.dumps({'a':inp}).decode('utf-8').encode('utf-16') request.body = body request.content_type = 'application/json; charset=utf-16' self.assertEqual(request.json_body, {'a':inp})
def notify_observers(self, msg): out = json.dumps(msg) for obs in self.observers: obs.put(out) obs.put(StopIteration) # for now just kill observers once a message is sent instead # of playing with chunked encoding self.observers = []
def _render(value, system): request = system.get('request') if request is not None: response = request.response ct = response.content_type if ct == response.default_content_type: response.content_type = 'application/json' return json.dumps(value, default=default_encoder)
def _render(value, system): request = system.get('request') if request is not None: response = request.response ct = response.content_type if ct == response.default_content_type: response.content_type = 'application/json' return json.dumps(value)
def test_json_body_alternate_charset(self): from pyramid.compat import json request = self._makeOne({'REQUEST_METHOD':'POST'}) request.charset = 'latin-1' la = unicode('La Pe\xc3\xb1a', 'utf-8') body = json.dumps({'a':la}, encoding='latin-1') request.body = body self.assertEqual(request.json_body, {'a':la})
def test_json_body_alternate_charset(self): from pyramid.compat import json request = self._makeOne({'REQUEST_METHOD': 'POST'}) request.charset = 'latin-1' la = unicode('La Pe\xc3\xb1a', 'utf-8') body = json.dumps({'a': la}, encoding='latin-1') request.body = body self.assertEqual(request.json_body, {'a': la})
def _render(value, system): request = system.get("request") if request is not None: response = request.response ct = response.content_type if ct == response.default_content_type: response.content_type = "application/json" return json.dumps(value)
def add_observer(self, cursor=None): obs = self.Observer(game=self) if cursor == self.cursor or cursor is None: self.observers.append(obs) else: msg = json.dumps(self.updates[cursor+1]) obs.put(msg) obs.put(StopIteration) return obs
def _makeDummyRequest(self, request_data=None): from pyramid.testing import DummyRequest request = DummyRequest() request.matched_route = DummyRoute('JSON-RPC') if request_data is not None: request.body = json.dumps(request_data) request.content_length = len(request.body) return request
def add_observer(self, cursor=None): obs = self.Observer(game=self) if cursor == self.cursor or cursor is None: self.observers.append(obs) else: msg = json.dumps(self.updates[cursor + 1]) obs.put(msg) obs.put(StopIteration) return obs
def serialize(self): tracking = { 'events': self.events, 'alias': self.user_id if self.alias else None, 'identify': self.user_id if self.user_id else None } return { 'api_token': self.api_token, 'tracking': tracking, 'tracking_json': json.dumps(tracking) }
def jsonrpc_error_response(error, id=None): """ Marshal a Python Exception into a webob ``Response`` object with a body that is a JSON string suitable for use as a JSON-RPC response with a content-type of ``application/json`` and return the response.""" body = json.dumps({"jsonrpc": "2.0", "id": id, "error": error.as_dict()}) response = Response(body) response.content_type = "application/json" response.content_length = len(body) return response
def test_view_callable_cls_with_dict(self): target = self._makeOne() view_callable = target(DummyView) request = testing.DummyRequest() params = {'jsonrpc':'2.0', 'method':'dummy_rpc', 'params':dict(a=3, b=4), 'id':'test'} body = json.dumps(params) request.json_body = params request.rpc_args = dict(a=3, b=4) context = object() result = view_callable(context, request) self.assertEqual(result, 7)
def test_view_callable_cls_with_invalid_args(self): from pyramid_rpc.jsonrpc import JsonRpcParamsInvalid target = self._makeOne() view_callable = target(DummyView) request = testing.DummyRequest() params = {'jsonrpc':'2.0', 'method':'dummy_rpc', 'params':[], 'id':'test'} body = json.dumps(params) request.json_body = params request.rpc_args = [] context = object() self.assertRaises(JsonRpcParamsInvalid, view_callable, context, request)
def view_calendar(context, request): kotti_calendar_resources.need() locale_name = get_locale_name(request) if locale_name in fullcalendar_locales: fullcalendar_locales[locale_name].need() else: # pragma: no cover (safety belt only, should never happen) fullcalendar_locales["en"].need() session = DBSession() now = datetime.datetime.now() query = session.query(Event).filter(Event.parent_id == context.id) future = or_(Event.start > now, Event.end > now) upcoming = query.filter(future).order_by(Event.start).all() past = query.filter(Event.start < now).order_by(desc(Event.start)).all() upcoming = [event for event in upcoming if has_permission('view', event, request)] past = [event for event in past if has_permission('view', event, request)] fmt = '%Y-%m-%d %H:%M:%S' fullcalendar_events = [] for event in (upcoming + past): json_event = { 'title': event.title, 'url': resource_url(event, request), 'start': event.start.strftime(fmt), 'allDay': event.all_day, } if event.end: json_event['end'] = event.end.strftime(fmt) fullcalendar_events.append(json_event) fullcalendar_options = { 'header': { 'left': 'prev,next today', 'center': 'title', 'right': 'month,agendaWeek,agendaDay' }, 'eventSources': context.feeds, 'weekends': context.weekends, 'events': fullcalendar_events, } return { 'api': template_api(context, request), 'upcoming_events': upcoming, 'past_events': past, 'fullcalendar_options': json.dumps(fullcalendar_options), }
def _render(value, system): request = system['request'] val = json.dumps(value) callback = request.GET.get(self.param_name) if callback is None: ct = 'application/json' body = val else: ct = 'application/javascript' body = '%s(%s)' % (callback, val) response = request.response if response.content_type == response.default_content_type: response.content_type = ct return body
def test_it_with_no_id(self): def view(request): return request.rpc_args[0] config = self.config config.include('pyramid_rpc.jsonrpc') config.add_jsonrpc_endpoint('rpc', '/api/jsonrpc') config.add_jsonrpc_method(view, endpoint='rpc', method='dummy') app = config.make_wsgi_app() app = TestApp(app) params = {'jsonrpc': '2.0', 'method': 'dummy', 'params': [2, 3]} resp = app.post('/api/jsonrpc', content_type='application/json', params=json.dumps(params)) self.assertEqual(resp.status_int, 204) self.assertEqual(resp.body, '')
def _render(value, system): request = system["request"] val = json.dumps(value) callback = request.GET.get(self.param_name) if callback is None: ct = "application/json" body = val else: ct = "application/javascript" body = "%s(%s)" % (callback, val) response = request.response if response.content_type == response.default_content_type: response.content_type = ct return body
def search(context, request): sr = get_search_results(context, request) artists, albums, tracks, criteria = sr["artists"], sr["albums"], sr["tracks"], sr["criteria"] return dict(results=json.dumps({ "artists": render_artists(artists, request, context), "albums": render_albums(context, request, albums or [], show_artist=True)["items"], "tracks": render_tracks(tracks, request, show_artist=True), "criteria": criteria}), criteria=criteria)
def test_it_with_invalid_method(self): config = self.config config.include('pyramid_rpc.jsonrpc') config.add_jsonrpc_endpoint('rpc', '/api/jsonrpc') app = config.make_wsgi_app() app = TestApp(app) params = {'jsonrpc': '2.0', 'id': 5, 'method': 'foo', 'params': [2, 3]} resp = app.post('/api/jsonrpc', content_type='application/json', params=json.dumps(params)) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.content_type, 'application/json') result = json.loads(resp.body) self.assertEqual(result['id'], 5) self.assertEqual(result['jsonrpc'], '2.0') self.assertEqual(result['error']['code'], -32601)
def view(self): """ Default view for :class:`kotti_calendar.resources.Calendar` :result: Dictionary needed to render the template. :rtype: dict """ kotti_calendar_resources.need() lang_all_js.need() return { 'api': template_api(self.context, self.request), 'upcoming_events': self.upcoming_events, 'past_events': self.past_events, 'fullcalendar_options': json.dumps(self.fullcalendar_options), 'event_url': self.event_url, }
def _render(value, system): request = system.get("request") if request is not None: rpc_id = getattr(request, "rpc_id", None) response = request.response if rpc_id is None: response.status = 204 del response.content_type return "" ct = response.content_type if ct == response.default_content_type: response.content_type = "application/json" out = {"jsonrpc": "2.0", "id": rpc_id, "result": value} return json.dumps(out)
def test_it(self): try: # Pyramid 1.1 from pyramid.renderers import null_renderer renderer = null_renderer except ImportError: # Pyramid 1.0 renderer = None from pyramid.config import Configurator from pyramid_rpc.jsonrpc import jsonrpc_endpoint from pyramid_rpc.jsonrpc import JsonRpcViewMapper config = Configurator() config.add_route('JSON-RPC', 'apis/rpc') config.add_view(jsonrpc_endpoint, route_name='JSON-RPC') def dummy_rpc(request, a, b): return a + b config.add_view(route_name='JSON-RPC', name='dummy_rpc', view=dummy_rpc, mapper=JsonRpcViewMapper, renderer=renderer) config.add_route('JSON-RPC-CLS', 'apis/rpc/cls') config.add_view(jsonrpc_endpoint, route_name='JSON-RPC-CLS') config.add_view(route_name='JSON-RPC-CLS', name='dummy_rpc', view=DummyView, mapper=JsonRpcViewMapper, renderer=renderer) app = config.make_wsgi_app() import webtest app = webtest.TestApp(app) params = {'jsonrpc': '2.0', 'method': 'dummy_rpc', 'params': [2, 3], 'id': 'test'} body = json.dumps(params) res = app.post('/apis/rpc', params=body, content_type='application/json') data = json.loads(res.body) self.assertEqual(data['id'], 'test') self.assertEqual(data['jsonrpc'], '2.0') self.assertEqual(data['result'], 5) res = app.post('/apis/rpc/cls', params=body, content_type='application/json') data = json.loads(res.body) self.assertEqual(data['id'], 'test') self.assertEqual(data['jsonrpc'], '2.0') self.assertEqual(data['result'], 5)
def _render(value, system): request = system.get('request') if request is not None: rpc_id = getattr(request, 'rpc_id', None) if rpc_id is None: raise HTTPNoContent() response = request.response ct = response.content_type if ct == response.default_content_type: response.content_type = 'application/json' out = { 'jsonrpc' : JSONRPC_VERSION, 'id' : rpc_id, 'result' : value, } return json.dumps(out)
def view_calendar(context, request): kotti_calendar_resources.need() locale_name = get_locale_name(request) if locale_name in fullcalendar_locales: fullcalendar_locales[locale_name].need() else: # pragma: no cover (safety belt only, should never happen) fullcalendar_locales["en"].need() session = DBSession() now = datetime.datetime.now() query = session.query(Event).filter(Event.parent_id == context.id) future = or_(Event.start > now, Event.end > now) upcoming = query.filter(future).order_by(Event.start).all() past = query.filter(Event.start < now).order_by(desc(Event.start)).all() upcoming = [event for event in upcoming if has_permission("view", event, request)] past = [event for event in past if has_permission("view", event, request)] fmt = "%Y-%m-%d %H:%M:%S" fullcalendar_events = [] for event in upcoming + past: json_event = { "title": event.title, "url": resource_url(event, request), "start": event.start.strftime(fmt), "allDay": event.all_day, } if event.end: json_event["end"] = event.end.strftime(fmt) fullcalendar_events.append(json_event) fullcalendar_options = { "header": {"left": "prev,next today", "center": "title", "right": "month,agendaWeek,agendaDay"}, "eventSources": context.feeds, "weekends": context.weekends, "events": fullcalendar_events, } return { "api": template_api(context, request), "upcoming_events": upcoming, "past_events": past, "fullcalendar_options": json.dumps(fullcalendar_options), }
def test_it_with_no_params(self): def view(request): self.assertEqual(request.rpc_args, []) return 'no params' config = self.config config.include('pyramid_rpc.jsonrpc') config.add_jsonrpc_endpoint('rpc', '/api/jsonrpc') config.add_jsonrpc_method(view, endpoint='rpc', method='dummy') app = config.make_wsgi_app() app = TestApp(app) params = {'jsonrpc': '2.0', 'id': 5, 'method': 'dummy'} resp = app.post('/api/jsonrpc', content_type='application/json', params=json.dumps(params)) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.content_type, 'application/json') result = json.loads(resp.body) self.assertEqual(result['id'], 5) self.assertEqual(result['jsonrpc'], '2.0') self.assertEqual(result['result'], 'no params')
def test_it_with_general_exception(self): def view(request): raise Exception() config = self.config config.include('pyramid_rpc.jsonrpc') config.add_jsonrpc_endpoint('rpc', '/api/jsonrpc') config.add_jsonrpc_method(view, endpoint='rpc', method='dummy') app = config.make_wsgi_app() app = TestApp(app) params = {'jsonrpc': '2.0', 'method': 'dummy', 'id': 5, 'params': [2, 3]} resp = app.post('/api/jsonrpc', content_type='application/json', params=json.dumps(params)) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.content_type, 'application/json') result = json.loads(resp.body) self.assertEqual(result['id'], 5) self.assertEqual(result['jsonrpc'], '2.0') self.assertEqual(result['error']['code'], -32603)
def _callFUT(self, app, method, params, id=5, version='2.0', path='/api/jsonrpc', content_type='application/json'): body = {} if id is not None: body['id'] = id if version is not None: body['jsonrpc'] = version if method is not None: body['method'] = method if params is not None: body['params'] = params resp = app.post(path, content_type=content_type, params=json.dumps(body)) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.content_type, 'application/json') result = json.loads(resp.body) self.assertEqual(result['jsonrpc'], '2.0') self.assertEqual(result['id'], id) return result
def jsonrpc_error_response(error, id=None): """ Marshal a Python Exception into a webob ``Response`` object with a body that is a JSON string suitable for use as a JSON-RPC response with a content-type of ``application/json`` and return the response.""" if not isinstance(error, JsonRpcError): error = JsonRpcInternalError() body = json.dumps({ 'jsonrpc' : JSONRPC_VERSION, 'id' : id, 'error' : error.as_dict(), }) response = Response(body) response.content_type = 'application/json' response.content_length = len(body) return response
def content(self): if not self.queries: return 'No queries in executed in request.' data = [] for query in self.queries: is_select = query['statement'].strip().lower().startswith('select') params = '' try: params = json.dumps(query['parameters']) except TypeError: pass # object not JSON serializable hash = hashlib.sha1( bytes_(self.request.exc_history.token + query['statement'] + params)).hexdigest() data.append({ 'engine_id': query['engine_id'], 'duration': query['duration'], 'sql': format_sql(query['statement']), 'raw_sql': query['statement'], 'hash': hash, 'params': params, 'is_select': is_select, 'context': query['context'], }) vars = { 'static_path': self.request.static_url(STATIC_PATH), 'root_path': self.request.route_url(ROOT_ROUTE_NAME), 'queries': data, } delattr(self.request, 'pdtb_sqla_queries') return self.render( 'pyramid_debugtoolbar.panels:templates/sqlalchemy.jinja2', vars, self.request)
def content(self): if not self.queries: return 'No queries in executed in request.' data = [] for query in self.queries: is_select = query['statement'].strip().lower().startswith('select') params = '' try: params = json.dumps(query['parameters']) except TypeError: pass # object not JSON serializable hash = hashlib.sha1( self.request.exc_history.token + query['statement'] + params).hexdigest() data.append({ 'engine_id': query['engine_id'], 'duration': query['duration'], 'sql': format_sql(query['statement']), 'raw_sql': query['statement'], 'hash': hash, 'params': params, 'is_select': is_select, 'context': query['context'], }) vars = { 'static_path': self.request.static_url(STATIC_PATH), 'root_path': self.request.route_url(ROOT_ROUTE_NAME), 'queries':data, } delattr(self.request, 'pdtb_sqla_queries') return self.render( 'pyramid_debugtoolbar.panels:templates/sqlalchemy.jinja2', vars, self.request)
def jsonrpc_response(data, id=None): """ Marshal a Python data structure into a webob ``Response`` object with a body that is a JSON string suitable for use as a JSON-RPC response with a content-type of ``application/json`` and return the response.""" if id is None: return Response(content_type="application/json") out = { 'jsonrpc' : JSONRPC_VERSION, 'id' : id, 'result' : data, } try: body = json.dumps(out) except Exception: return jsonrpc_error_response(JsonRpcInternalError(), id) response = Response(body) response.content_type = 'application/json' response.content_length = len(body) return response
def content(self): if not self.queries: return "No queries in executed in request." data = [] for query in self.queries: is_select = query["statement"].strip().lower().startswith("select") params = "" try: params = json.dumps(query["parameters"]) except TypeError: pass # object not JSON serializable hash = hashlib.sha1(bytes_(self.request.exc_history.token + query["statement"] + params)).hexdigest() data.append( { "engine_id": query["engine_id"], "duration": query["duration"], "sql": format_sql(query["statement"]), "raw_sql": query["statement"], "hash": hash, "params": params, "is_select": is_select, "context": query["context"], } ) vars = { "static_path": self.request.static_url(STATIC_PATH), "root_path": self.request.route_url(ROOT_ROUTE_NAME), "queries": data, } delattr(self.request, "pdtb_sqla_queries") return self.render("pyramid_debugtoolbar.panels:templates/sqlalchemy.mako", vars, self.request)
def _render(value, system): request = system.get('request') if request is not None: if not hasattr(request, 'response_content_type'): request.response_content_type = 'application/json' return json.dumps(value)
def process_bind_param(self, value, dialect): if value is not None: value = json.dumps(value, default=dump_default) return value