Пример #1
0
Файл: db.py Проект: boto/botoweb
	def _get(self, request, response, id=None ):
		"""Get an object, or search for a list of objects"""
		response.content_type = "text/xml"
		if id:
			vals = id.split("/",1)
			property = None
			if len(vals) > 1:
				(id, property) = vals
			obj = self.read(id=id, user=request.user)
			if property:
				return self.get_property(request, response, obj, property)
			else:
				if request.file_extension == "json" or request.accept.best_match(['application/xml', 'application/json']) == "application/json":
					response.content_type = "application/json"
					response.app_iter = JSONWrapper(iter([obj]), request.user)
				else:
					response.write(xmlize.dumps(obj))
					
		else:
			params = request.GET.mixed()
			objs = self.search(params=params, user=request.user)
			# Add the count to the header
			try:
				response.headers['X-Result-Count'] = str(objs.count())
			except:
				raise BadRequest('Invalid Query')
			if params.has_key("next_token"):
				del(params['next_token'])
			base_url = '%s%s%s' % (request.real_host_url, request.base_url, request.script_name)
			#objs.limit = self.page_size
			if request.file_extension == "json" or request.accept.best_match(['application/xml', 'application/json']) == "application/json":
				response.content_type = "application/json"
				response.app_iter = JSONWrapper(objs, request.user, "%s.json" % base_url, params)
			elif request.file_extension == "csv":
				response.content_type = "text/csv"
				response.headers['Content-Disposition'] = 'attachment;filename=%s.csv' % self.db_class.__name__
				response.app_iter = CSVWrapper(objs, request.user, self.db_class)
			else:
				page = False
				if(objs.limit == None):
					objs.limit = self.page_size
					page = True
				response.write("<%sList>" % self.db_class.__name__)
				for obj in objs:
					dataStr = xmlize.dumps(obj)
					if '\x80' in dataStr or '\x1d' in dataStr:
						dataStr.replace('\x80','').replace('\x1d','')
					response.write(dataStr)
				if page and objs.next_token:
					if params.has_key("next_token"):
						del(params['next_token'])
					self_link = '%s?%s' % (base_url, urllib.urlencode(params).replace("&", "&amp;"))
					params['next_token'] = objs.next_token
					next_link = '%s?%s' % (base_url, urllib.urlencode(params).replace("&", "&amp;"))
					response.write('<link type="text/xml" rel="next" href="%s"/>' % (next_link))
					response.write('<link type="text/xml" rel="self" href="%s"/>' % (self_link))
				response.write("</%sList>" % self.db_class.__name__)
		return response
Пример #2
0
Файл: db.py Проект: boto/botoweb
	def _post(self, request, response, id=None):
		"""Create a new resource, or update a single property on an object"""
		if id:
			vals = id.split("/",1)
			if len(vals) > 1:
				obj = self.db_class.lookup(vals[0])
				return self.update_property(request, response, obj, vals[1])
			else:
				obj = self.db_class.lookup(id)
				if obj:
					raise Conflict("Object %s already exists" % id)

		if request.file_extension == "json" or request.accept.best_match(['application/xml', 'application/json']) == "application/json":
			new_obj = json.loads(request.body)
			new_obj['__id__'] = id
		else:
			new_obj = xmlize.loads(request.body)
			new_obj.__id__ = id
		obj = self.create(new_obj, request.user, request)
		response.set_status(201)
		if request.file_extension == "json" or request.accept.best_match(['application/xml', 'application/json']) == "application/json":
			response.content_type = "application/json"
			response.app_iter = JSONWrapper(iter([obj]), request.user)
		else:
			response.content_type = "text/xml"
			response.write(xmlize.dumps(obj))
		return response
Пример #3
0
Файл: db.py Проект: boto/botoweb
	def _put(self, request, response, id=None):
		"""Update an existing resource"""
		obj = None
		if id:
			obj = self.db_class.lookup(id)

		if not obj:
			raise NotFound()

		props = {}
		if "json" in request.content_type:
			props = json.loads(request.body)
		elif request.content_type == "application/x-www-form-urlencoded" and not request.body.startswith("<"):
			props = request.POST.mixed()
		else:
			request.content_type = "text/xml"
			# By default we assume it's XML
			new_obj = xmlize.loads(request.body)
			for prop in new_obj.__dict__:
				prop_value = getattr(new_obj, prop)
				if not prop.startswith("_"):
					props[prop] = prop_value
		obj =  self.update(obj, props, request.user, request)

		if request.file_extension == "json" or request.accept.best_match(['application/xml', 'application/json']) == "application/json":
			response.content_type = "application/json"
			response.app_iter = JSONWrapper(iter([obj]), request.user)
		else:
			response.content_type = "text/xml"
			response.write(xmlize.dumps(obj))
		return response
Пример #4
0
	def test_map(self):
		"""Test dumping and loading a map (dict/complexType)"""
		d = {"bar":"biz", "foo":"fiz"}
		xml = xmlize.dumps(d, "map")
		d2  = xmlize.loads("<result>%s</result>" % xml)
		print xml
		assert d2.map == d
Пример #5
0
Файл: db.py Проект: boto/botoweb
	def _delete(self, request, response, id=None):
		"""
		Delete a given object
		"""
		obj = self.read(id=id, user=request.user);
		content = self.delete(obj,user=request.user)
		response.content_type = "text/xml"
		response.write(xmlize.dumps(content))
		return response
Пример #6
0
	def test_datetime(self):
		"""Try encoding and decoding a datetime"""
		xmlize.register(ObjectTest)
		obj = ObjectTest()
		obj.d = datetime.datetime(year=2009, month=9, day=9, hour=9, minute=9, second=9, tzinfo=pytz.utc)
		sr = xmlize.dumps(obj)
		obj2 = xmlize.loads(sr)

		print obj2.d.tzinfo
		assert obj2.d == obj.d
Пример #7
0
	def save(self, obj):
		"""Save this object"""
		assert obj.__class__.__name__ in self.routes
		url = self.routes[obj.__class__.__name__]
		body = xmlize.dumps(obj)
		if obj.id:
			# PUT to update
			self.request(method="PUT", path="/%s/%s" % (url, obj.id), body=body)
		else:
			# POST to create
			self.request(method="POST", path="/%s"%url, body=body)
Пример #8
0
	def test_str(self):
		"""Test encoding a string"""
		xmlize.register(ObjectTest)
		obj = ObjectTest()
		obj.foo = "bar"
		obj.name = "Bizzle"
		obj.id = "12345"
		sr = xmlize.dumps(obj)
		obj2 = xmlize.loads(sr)


		assert obj2.foo == obj.foo
		assert obj2.name == obj.name
		assert obj2.__id__ == obj.id
Пример #9
0
	def test_reference(self):
		"""Test dumping a reference"""
		xmlize.register(ObjectTestReference)
		xmlize.register(ObjectTestReferenceSub)
		obj = ObjectTestReference()
		obj.name = "Parent Object"
		obj.id = "1234567890"
		obj_sub = ObjectTestReferenceSub()
		obj_sub.parent = obj
		obj_sub.id = "9378509283"

		obj_xml = xmlize.dumps(obj_sub)
		obj_loaded = xmlize.loads(obj_xml)
		print obj_xml
		assert obj_loaded.parent.__id__ == obj.id
Пример #10
0
Файл: db.py Проект: boto/botoweb
			except:
				response.write(val.read())
		elif isinstance(val, Key):
			response.content_type = val.content_type
			response.write(val.get_contents_as_string())
		elif isinstance(val, Query) or isinstance(val, BatchItemFetcher):
			objs = self.build_query(request.GET.mixed(), query=val, user=request.user)
			response.headers['X-Result-Count'] = str(objs.count())
			response.write("<%s>" % property)

			page = False
			if(objs.limit == None):
				objs.limit = self.page_size
				page = True
			for o in objs:
				response.write(xmlize.dumps(o))
			params = request.GET.mixed()
			if page and objs.next_token:
				if params.has_key("next_token"):
					del(params['next_token'])
				self_link = '%s%s%s/%s/%s?%s' % (request.real_host_url, request.base_url, request.script_name, obj.id, property, urllib.urlencode(params).replace("&", "&amp;"))
				params['next_token'] = objs.next_token
				next_link = '%s%s%s/%s/%s?%s' % (request.real_host_url, request.base_url, request.script_name, obj.id, property, urllib.urlencode(params).replace("&", "&amp;"))
				response.write('<link type="text/xml" rel="next" href="%s"/>' % (next_link))
				response.write('<link type="text/xml" rel="self" href="%s"/>' % (self_link))
			response.write("</%s>" % property)
		elif val:
			if format in [None, "xml"]:
				response.content_type = "text/xml"
				if hasattr(val, "to_xml"):
					response.write(val.to_xml())
Пример #11
0
	def test_dump_list(self):
		"""Test dumping a simple list"""
		l = ['admin', 'test', 'developer']
		xml = xmlize.dumps(l, 'auth_groups')
		l2 = xmlize.loads("<result>%s</result>" % xml)
		assert l2.auth_groups == l
Пример #12
0
    def _get(self, request, response, id=None):
        """Get an object, or search for a list of objects"""
        response.content_type = "text/xml"
        if id:
            vals = id.split("/", 1)
            property = None
            if len(vals) > 1:
                (id, property) = vals
            obj = self.read(id=id, user=request.user)
            if property:
                return self.get_property(request, response, obj, property)
            else:
                if request.file_extension == "json":
                    response.content_type = "application/json"
                    response.app_iter = JSONWrapper(iter([obj]), request.user)
                else:
                    response.write(xmlize.dumps(obj))

        else:
            # Add the count to the header
            response = self._head(request, response)
            params = request.GET.mixed()
            objs = self.search(params=params, user=request.user)
            if params.has_key("next_token"):
                del (params['next_token'])
            base_url = '%s%s%s' % (request.real_host_url, request.base_url,
                                   request.script_name)
            #objs.limit = self.page_size
            if request.file_extension == "json":
                response.content_type = "application/json"
                response.app_iter = JSONWrapper(objs, request.user,
                                                "%s.json" % base_url, params)
            elif request.file_extension == "csv":
                response.content_type = "text/csv"
                response.headers[
                    'Content-Disposition'] = 'attachment;filename=%s.csv' % self.db_class.__name__
                response.app_iter = CSVWrapper(objs, request.user,
                                               self.db_class)
            else:
                page = False
                if (objs.limit == None):
                    objs.limit = self.page_size
                    page = True
                response.write("<%sList>" % self.db_class.__name__)
                for obj in objs:
                    response.write(xmlize.dumps(obj))
                if page and objs.next_token:
                    if params.has_key("next_token"):
                        del (params['next_token'])
                    self_link = '%s?%s' % (base_url,
                                           urllib.urlencode(params).replace(
                                               "&", "&amp;"))
                    params['next_token'] = objs.next_token
                    next_link = '%s?%s' % (base_url,
                                           urllib.urlencode(params).replace(
                                               "&", "&amp;"))
                    response.write(
                        '<link type="text/xml" rel="next" href="%s"/>' %
                        (next_link))
                    response.write(
                        '<link type="text/xml" rel="self" href="%s"/>' %
                        (self_link))
                response.write("</%sList>" % self.db_class.__name__)
        return response
Пример #13
0
        elif isinstance(val, Key):
            response.content_type = val.content_type
            response.write(val.get_contents_as_string())
        elif isinstance(val, Query):
            objs = self.build_query(request.GET.mixed(),
                                    query=val,
                                    user=request.user)
            response.headers['X-Result-Count'] = str(objs.count())
            response.write("<%s>" % property)

            page = False
            if (objs.limit == None):
                objs.limit = self.page_size
                page = True
            for o in objs:
                response.write(xmlize.dumps(o))
            params = request.GET.mixed()
            if page and objs.next_token:
                if params.has_key("next_token"):
                    del (params['next_token'])
                self_link = '%s%s%s/%s/%s?%s' % (
                    request.real_host_url, request.base_url,
                    request.script_name, obj.id, property,
                    urllib.urlencode(params).replace("&", "&amp;"))
                params['next_token'] = objs.next_token
                next_link = '%s%s%s/%s/%s?%s' % (
                    request.real_host_url, request.base_url,
                    request.script_name, obj.id, property,
                    urllib.urlencode(params).replace("&", "&amp;"))
                response.write('<link type="text/xml" rel="next" href="%s"/>' %
                               (next_link))