Example #1
0
    def __init__(self):
        '''
        set up the test data from an external csv file
        '''
        self._testData = []

        for newRec in csv.DictReader(open("TestData.csv", 'rb'), delimiter=','):
            newRec['pk'] = Item.genPK(newRec['name'], newRec['category'])
            newRec['review'] = listify(newRec['review'])
            # convert lat / lon to floats : float('str')
            # If already have the PK, append to the existing review entry
            if not self._testData:
                self._testData.append(newRec)
            else:
                existingUpdated = False
                for existingRec in self._testData:
                    if (existingRec['pk'] == newRec['pk']) and newRec['review']:
                        existingRec['review'].append(newRec['review'][0])
                        existingUpdated = True
                if not existingUpdated:
                    self._testData.append(newRec)
Example #2
0
 def testValidPK(self):
     name = "WhatAGreatPlaceToRockAndRoll"
     category = "Recreational"
     myuuid = str(uuid.UUID(binascii.hexlify("%d%s" % (0, name[0:15]))))
     self.assertEqual(Item.genPK(name, category), myuuid)
Example #3
0
    def PUT(self, ignoreMe):
        """
        PUT == Create
        """
        jsonData = web.data()
        item = Item.ThingToDo()
        try:
            itemData = json.JSONDecoder().decode(jsonData)
        except:
            logging.error("Item-PUT: unable to decode json %s" % jsonData)
            web.badrequest()
            return

        if isTestMode():  # check env. if in test mode, import dbconn mock
            import Shared

            dbConn = Shared.dbMock
        else:
            dbConn = DataAccessLayer.DataAccessLayer()

        #        if 'lat' in itemData and 'lon' in itemData:
        #            itemData['latlon'] = Item.LatLon(itemData['lat'], itemData['lon'])
        #
        # name, category and createdBy are required
        if not ("name" in itemData and "category" in itemData and "createdBy" in itemData):
            logging.info("Item-PUT: missing required args")
            web.badrequest()
            return

        # One of address or lat/lon pair required
        if "address" not in itemData and not ("lat" in itemData and "lon" in itemData):
            logging.info("Item-PUT: missing address and lat/lon")
            web.badrequest()
            return

        otherArgs = {}
        for attr, val in itemData.iteritems():
            if attr == "name" or attr == "category" or attr == "createdBy":
                # remove from the dict so that what remains is what setAttrs expects for keyword args
                continue
            # special handling of lat/lon so we get a textual represenation, rather than a numeric
            if attr == "lat":
                ll = Item.LatLon(val, 0.0)
                otherArgs[attr] = ll._lat
                continue
            if attr == "lon":
                ll = Item.LatLon(0.0, val)
                otherArgs[attr] = ll._lon
                continue
            # everything else just gets added to the keyword args
            otherArgs[attr] = val

        try:
            item.setAttrs(itemData["name"], itemData["category"], itemData["createdBy"], **otherArgs)
        except:
            logging.error("Item-PUT: unable to set attributes")
            web.badrequest()
            return

        # If the item already exists, that's an error - caller should be using POST, not PUT
        # Make the PK and see if it exists. AttributeError if it does
        PK = Item.genPK(itemData["name"], itemData["category"])
        searchFor = Item.SearchFor()
        searchFor.setAttr("pk", PK)
        where = searchFor.makeWhereClause()

        try:
            rtn = dbConn.read(where)
        except Exception as ex:
            logging.error("Item-PUT: Unexpected exception checking for existing record - %s", ex)
            web.badrequest()
            return
        if rtn != None:
            logging.info("Item-PUT: item already exists (%s)", PK)
            web.conflict()
            return

        # now that we have an item that doesn't exist, write it to the dbconn
        try:
            dbConn.write(item._serialized)
        except Exception as ex:
            logging.error("Item-PUT: unexpected exception writing item - %s", ex)
            web.badrequest()
            return

        return json.JSONEncoder().encode(item._serialized)