def get(self, user_id=None): """Args: contacts: list of PoCo contact dicts """ paging_params = self.get_paging_params() total_results, contacts = self.source.get_contacts(user_id, **paging_params) response = { "startIndex": paging_params["start_index"], "itemsPerPage": len(contacts), "totalResults": total_results, "entry": contacts, "filtered": False, "sorted": False, "updatedSince": False, } self.response.headers["Access-Control-Allow-Origin"] = "*" format = self.request.get("format", "json") if format == "json": self.response.headers["Content-Type"] = "application/json" self.response.out.write(json.dumps(response, indent=2)) elif format == "xml": self.response.headers["Content-Type"] = "text/xml" self.response.out.write(XML_TEMPLATE % util.to_xml(response)) else: raise exc.HTTPBadRequest("Invalid format: %s (should be json or xml)" % format)
def get(self, user_id=None): """Args: contacts: list of PoCo contact dicts """ kwargs = {} for param in "startIndex", "count": val = self.request.get(param, 0) try: val = int(val) assert val >= 0 kwargs[param] = val except (ValueError, AssertionError): raise exc.HTTPBadRequest("Invalid %s: %s (should be positive int)" % (param, val)) contacts = self.source.get_contacts(user_id, **kwargs) response = { "startIndex": kwargs["startIndex"], "itemsPerPage": self.source.ITEMS_PER_PAGE, "totalResults": len(contacts), "entry": contacts, "filtered": False, "sorted": False, "updatedSince": False, } format = self.request.get("format", "json") if format == "json": self.response.headers["Content-Type"] = "application/json" self.response.out.write(json.dumps(response, indent=2)) elif format == "xml": self.response.headers["Content-Type"] = "text/xml" self.response.out.write(XML_TEMPLATE % util.to_xml(response)) else: raise exc.HTTPBadRequest("Invalid format: %s (should be json or xml)" % format)
def test_nested(self): self.assertEqual(""" <a> <b> <c>x</c> <d>y</d> </b> <e>2</e> <e>3</e> </a> """, util.to_xml({'a': {'b': {'c': 'x', 'd': 'y'}, 'e': (2, 3), }}))
def to_xml(self, root=None, header=True, pretty=False, dasherize=True): """Convert the object to an xml string. Args: root: The name of the root element for xml output. header: Whether to include the xml header. pretty: Whether to "pretty-print" format the output. dasherize: Whether to dasherize the xml attribute names. Returns: An xml string. """ if not root: root = self._singular return util.to_xml(self.to_dict(), root=root, header=header, pretty=pretty, dasherize=dasherize)
def get(self): """Handles an API GET. Request path is of the form /user_id/group_id/app_id/activity_id , where each element is an optional string object id. """ # parse path args = urllib.unquote(self.request.path).strip('/').split('/') if len(args) > MAX_PATH_LEN: raise exc.HTTPNotFound() elif args == ['']: args = [] # handle default path elements args = [None if a in defaults else a for a, defaults in zip(args, PATH_DEFAULTS)] paging_params = self.get_paging_params() # extract format format = self.request.get('format', 'json') if format not in ('json', 'atom', 'xml'): raise exc.HTTPBadRequest('Invalid format: %s, expected json, atom, xml' % format) # get activities and build response total_results, activities = self.source.get_activities(*args, **paging_params) response = {'startIndex': paging_params['start_index'], 'itemsPerPage': len(activities), 'totalResults': total_results, # TODO: this is just for compatibility with # http://activitystreamstester.appspot.com/ # the OpenSocial spec says to use entry instead, so switch back # to that eventually 'items': activities, 'filtered': False, 'sorted': False, 'updatedSince': False, } # encode and write response if format == 'json': self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(response, indent=2)) else: self.response.headers['Content-Type'] = 'text/xml' self.response.out.write(XML_TEMPLATE % util.to_xml(response))
def test_to_xml(self): self.assert_equals('', util.to_xml({})) self.assert_equals('\n<a>3.14</a>\n<b>xyz</b>\n', util.to_xml({'a': 3.14, 'b': 'xyz'})) self.assert_equals('\n<a></a>\n', util.to_xml({'a': None})) self.assert_equals('\n<a></a>\n', util.to_xml({'a': ''})) self.assert_equals('\n<a></a>\n', util.to_xml({'a': {}})) self.assert_equals('\n<a>0</a>\n', util.to_xml({'a': 0})) self.assert_equals('\n<a>1</a>\n<a>2</a>\n', util.to_xml({'a': [1, 2]})) self.assert_equals(""" <a> <b> <c>x</c> <d>y</d> </b> <e>2</e> <e>3</e> </a> """, util.to_xml({'a': {'b': {'c': 'x', 'd': 'y'}, 'e': (2, 3), }}))
def test_list(self): self.assertEqual(""" <a>1</a> <a>2</a> """, util.to_xml({'a': [1, 2]}))
def test_zero(self): self.assertEqual(""" <a>0</a> """ , util.to_xml({'a': 0}))
def test_empty_dict(self): self.assertEqual(""" <a></a> """ , util.to_xml({'a': {}}))
def test_empty_string(self): self.assertEqual(""" <a></a> """ , util.to_xml({'a': ''}))
def test_none(self): self.assertEqual(""" <a></a> """, util.to_xml({'a': None}))
def test_flat(self): self.assertEqual(""" <a>3.14</a>\n<b>xyz</b> """, util.to_xml({'a': 3.14, 'b': 'xyz'}))
def test_no_values(self): self.assertEqual('', util.to_xml({}))
def test_empty(self): self.assertEqual(""" """, util.to_xml({}))