def post(self, request): odlc_proto = interop_api_pb2.Odlc() try: json_format.Parse(request.body, odlc_proto) except Exception as e: return HttpResponseBadRequest( 'Failed to parse request. Error: %s' % str(e)) # Validate ODLC proto fields. try: validate_odlc_proto(odlc_proto) except ValueError as e: return HttpResponseBadRequest(str(e)) # Cannot set ODLC ID on a post. if odlc_proto.HasField('id'): return HttpResponseBadRequest( 'Cannot specify ID for POST request.') # Check that there aren't too many ODLCs uploaded already. odlc_count = Odlc.objects.filter(user=request.user).filter( mission=odlc_proto.mission).count() if odlc_count >= ODLC_UPLOAD_LIMIT: return HttpResponseBadRequest( 'Reached upload limit for ODLCs for mission.') # Build the ODLC object from the request. odlc = Odlc() odlc.user = request.user update_odlc_from_proto(odlc, odlc_proto) odlc.save() return HttpResponse(json_format.MessageToJson(odlc_to_proto(odlc)), content_type="application/json")
def put(self, request, pk): try: odlc = find_odlc(request, int(pk)) except Odlc.DoesNotExist: return HttpResponseNotFound('Odlc %s not found' % pk) except ValueError as e: return HttpResponseForbidden(str(e)) odlc_proto = interop_api_pb2.Odlc() try: json_format.Parse(request.body, odlc_proto) except Exception as e: return HttpResponseBadRequest( 'Failed to parse request. Error: %s' % str(e)) # Validate ODLC proto fields. try: validate_odlc_proto(odlc_proto) except ValueError as e: return HttpResponseBadRequest(str(e)) # ID provided in proto must match object. if odlc_proto.HasField('id') and odlc_proto.id != odlc.pk: return HttpResponseBadRequest('ID in request does not match URL.') # Update the ODLC object from the request. update_odlc_from_proto(odlc, odlc_proto) odlc.update_last_modified() odlc.save() return HttpResponse(json_format.MessageToJson(odlc_to_proto(odlc)), content_type="application/json")
def submit_form(): result = request.form letter_colour = request.form['letter_colour'] alphanumericval = request.form['alphanumeric'] bg_colour = request.form['bg_colour'] shapeval = request.form['shape'] orientationval = request.form['orientation'] send_image = im.image_src(im.imageArray, im.imageIndex) latlon = im.metadata(im.imageArray, im.imageIndex) odlc = interop_api_pb2.Odlc() odlc.type = interop_api_pb2.Odlc.STANDARD odlc.latitude = latlon.get('lat') / div_factor odlc.longitude = latlon.get('lon') / div_factor odlc.orientation = dict_orient[orientationval] odlc.shape = dict_shape[shapeval] odlc.shape_color = dict_colour[bg_colour] odlc.alphanumeric = alphanumericval odlc.alphanumeric_color = dict_colour[letter_colour] odlc = client.post_odlc(odlc) with open(send_image, 'rb') as f: image_data = f.read() client.put_odlc_image(odlc.id, image_data) im.moveimg(im.imageArray, im.imageIndex) return redirect("/")
def simulate_odlc(test, client, mission, actual): """Simulates sending ODLC.""" o = interop_api_pb2.Odlc() o.mission = mission.pk if actual: odlc = random.choice(mission.odlcs.all()) o.type = odlc.odlc_type o.latitude = odlc.location.latitude o.longitude = odlc.location.longitude if odlc.shape: o.orientation = odlc.orientation o.shape = odlc.shape o.shape_color = odlc.shape_color o.alphanumeric = odlc.alphanumeric o.alphanumeric_color = odlc.alphanumeric_color o.autonomous = random.random() < 0.1 else: o.description = odlc.description else: o.type = random.choice(interop_api_pb2.Odlc.Type.values()) o.latitude = random.uniform(0, 90) o.longitude = random.uniform(0, 180) o.orientation = random.choice( interop_api_pb2.Odlc.Orientation.values()) o.shape = random.choice(interop_api_pb2.Odlc.Shape.values()) o.shape_color = random.choice(interop_api_pb2.Odlc.Color.values()) o.alphanumeric = random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') o.alphanumeric_color = random.choice( interop_api_pb2.Odlc.Color.values()) o.autonomous = random.random() < 0.1 o.description = str(random.random()) r = client.post(odlcs_url, data=json_format.MessageToJson(o), content_type='application/json') test.assertEqual(r.status_code, 200, r.content)
def post(self, request): odlc_proto = interop_api_pb2.Odlc() try: json_format.Parse(request.body, odlc_proto) except Exception as e: return HttpResponseBadRequest( 'Failed to parse request. Error: %s' % str(e)) # Validate ODLC proto fields. try: validate_odlc_proto(odlc_proto) except ValueError as e: return HttpResponseBadRequest(str(e)) # Cannot set ODLC ID on a post. if odlc_proto.HasField('id'): return HttpResponseBadRequest( 'Cannot specify ID for POST request.') # Build the ODLC object from the request. odlc = Odlc() odlc.user = request.user update_odlc_from_proto(odlc, odlc_proto) odlc.save() return HttpResponse(json_format.MessageToJson(odlc_to_proto(odlc)), content_type="application/json")
def get_odlcs(self, mission_id): headers = {'Cookie': self.cookie} url = '/api/odlcs' if mission_id: url += '?mission=%d' % mission_id response = self.session.get(self.url + url + '?mission=%d', headers=headers) odlcs = [] for odlc_dict in r.json(): odlc_proto = interop_api_pb2.Odlc() json_format.Parse(json.dumps(odlc_dict), odlc_proto) odlcs.append(odlc_proto) self.status_codes(response.status_code) return odlcs
def post_odlc(self, odlc): """POST odlc. Args: odlc: The odlc to upload. Returns: The odlc after upload, which will include the odlc ID and user. Raises: InteropError: Error from server. requests.Timeout: Request timeout. ValueError or AttributeError: Malformed response from server. """ r = self.post('/api/odlcs', data=json_format.MessageToJson(odlc)) odlc = interop_api_pb2.Odlc() json_format.Parse(r.text, odlc) return odlc
def get_odlc(self, odlc_id): """GET odlc. Args: odlc_id: The ID of the odlc to get. Returns: Odlc object with corresponding ID. Raises: InteropError: Error from server. requests.Timeout: Request timeout. ValueError or AttributeError: Malformed response from server. """ r = self.get('/api/odlcs/%d' % odlc_id) odlc = interop_api_pb2.Odlc() json_format.Parse(r.text, odlc) return odlc
def get_odlcs(self): """GET odlcs. Returns: List of Odlc objects which are viewable by user. Raises: InteropError: Error from server. requests.Timeout: Request timeout. ValueError or AttributeError: Malformed response from server. """ r = self.get('/api/odlcs') odlcs = [] for odlc_dict in r.json(): odlc_proto = interop_api_pb2.Odlc() json_format.Parse(json.dumps(odlc_dict), odlc_proto) odlcs.append(odlc_proto) return odlcs
def put_odlc(self, odlc_id, odlc): """PUT odlc. Args: odlc_id: The ID of the odlc to update. odlc: The odlc details to update. Returns: The odlc after being updated. Raises: InteropError: Error from server. requests.Timeout: Request timeout. ValueError or AttributeError: Malformed response from server. """ r = self.put( '/api/odlcs/%d' % odlc_id, data=json_format.MessageToJson(odlc)) odlc = interop_api_pb2.Odlc() json_format.Parse(r.text, odlc) return odlc
def get_odlcs(self, mission=None): """GET odlcs. Args: mission: Optional. ID of a mission to restrict by. Returns: List of Odlc objects which are viewable by user. Raises: InteropError: Error from server. requests.Timeout: Request timeout. ValueError or AttributeError: Malformed response from server. """ url = '/api/odlcs' if mission: url += '?mission=%d' % mission r = self.get(url) odlcs = [] for odlc_dict in r.json(): odlc_proto = interop_api_pb2.Odlc() json_format.Parse(json.dumps(odlc_dict), odlc_proto) odlcs.append(odlc_proto) return odlcs
def upload_odlc(client, odlc_file, image_file): """Upload a single odlc to the server Args: client: interop.Client connected to the server odlc_file: Path to file containing odlc details in the Object File Format. image_file: Path to odlc thumbnail. May be None. """ odlc = interop_api_pb2.Odlc() with open(odlc_file) as f: json_format.Parse(f.read(), odlc) # logger.info('Uploading odlc %s: %r' % (odlc_file, odlc)) odlc = client.post_odlc(odlc).result() if image_file: # logger.info('Uploading odlc thumbnail %s' % image_file) with open(image_file, 'rb') as img: client.post_odlc_image(odlc.id, img.read()).result() else: print('No thumbnail for odlc %s' % odlc_file)
def odlc_to_proto(odlc): """Converts an ODLC into protobuf format.""" odlc_proto = interop_api_pb2.Odlc() odlc_proto.id = odlc.pk odlc_proto.type = odlc.odlc_type if odlc.location is not None: odlc_proto.latitude = odlc.location.latitude odlc_proto.longitude = odlc.location.longitude if odlc.orientation is not None: odlc_proto.orientation = odlc.orientation if odlc.shape is not None: odlc_proto.shape = odlc.shape if odlc.alphanumeric: odlc_proto.alphanumeric = odlc.alphanumeric if odlc.background_color is not None: odlc_proto.shape_color = odlc.background_color if odlc.alphanumeric_color is not None: odlc_proto.alphanumeric_color = odlc.alphanumeric_color if odlc.description: odlc_proto.description = odlc.description odlc_proto.autonomous = odlc.autonomous return odlc_proto
def upload2Interop(self): s1 = s2 = s3 = s4 = s5 = s6 = s7 = s8 = s9 = None s1 = self.text1.get() s2 = self.entry2.get() s3 = self.entry3.get() s4 = self.text4.get() s5 = self.text5.get() s6 = self.text6.get() s7 = self.entry7.get() s8 = self.text8.get() s9 = self.entry9.get() if s9 == "": s9 = None target_response = OrderedDict([("id", 1), ( "mission", 1, ), ("type", s1), ("latitude", s2), ("longitude", s3), ("orientation", s4), ("shape", s5), ("background_color", s6), ("alphanumeric", s7), ("alphanumeric_color", s8), ("description", s9), ("autonomous", False)]) # print target_response json_str = json.dumps(target_response) print(json_str) x = self.gps() print("Latitude and Longitude : ") with open(str(self.index2) + ".json", 'w') as outfile: json.dump(target_response, outfile) a = str(self.index2) + ".json" b = "cp " + a + " mydata/" + a os.system(b) myclient = client.Client(url='http://localhost:8000', username='******', password='******') """target=interop.Odlc(id=None, user='******', type=s1, latitude=s2, longitude=s3, orientation=s4, shape=s5, background_color=s6, alphanumeric=s7, alphanumeric_color=s8, description=None, autonomous=False) target = client.post_odlc(target)""" odlc = interop_api_pb2.Odlc() odlc.mission = 1 odlc.type = interop_api_pb2.Odlc.STANDARD #odlc.latitude = s2 #odlc.longitude = s3 odlc.orientation = 4 odlc.shape = 5 odlc.shape_color = 6 odlc.alphanumeric = s7 odlc.alphanumeric_color = 8 odlc = myclient.post_odlc(odlc) print(str(self.index2) + ".jpg") with open(str(self.index2) + ".jpg", 'rb') as f: image_data = f.read() myclient.put_odlc_image(odlc.id, image_data) self.index2 += 1
def test_odlcs(self): """Test odlc workflow.""" # Post a odlc gets an updated odlc. odlc = interop_api_pb2.Odlc() odlc.type = interop_api_pb2.Odlc.STANDARD post_odlc = self.client.post_odlc(odlc) async_post_odlc = self.client.post_odlc(odlc) self.assertIsNotNone(post_odlc.id) self.assertIsNotNone(async_post_odlc.id) self.assertEqual(interop_api_pb2.Odlc.STANDARD, post_odlc.type) self.assertEqual(interop_api_pb2.Odlc.STANDARD, async_post_odlc.type) self.assertNotEqual(post_odlc.id, async_post_odlc.id) # Get odlcs. get_odlc = self.client.get_odlc(post_odlc.id) async_get_odlc = self.async_client.get_odlc( async_post_odlc.id).result() get_odlcs = self.client.get_odlcs() async_get_odlcs = self.async_client.get_odlcs().result() self.assertEquals(post_odlc, get_odlc) self.assertEquals(async_post_odlc, async_get_odlc) self.assertIn(post_odlc, get_odlcs) self.assertIn(async_post_odlc, async_get_odlcs) # Update odlc. post_odlc.shape = interop_api_pb2.Odlc.CIRCLE async_post_odlc.shape = interop_api_pb2.Odlc.CIRCLE put_odlc = self.client.put_odlc(post_odlc.id, post_odlc) async_put_odlc = self.async_client.put_odlc(async_post_odlc.id, async_post_odlc).result() self.assertEquals(post_odlc, put_odlc) self.assertEquals(async_post_odlc, async_put_odlc) # Upload odlc image. test_image_filepath = os.path.join(os.path.dirname(__file__), "testdata/A.jpg") with open(test_image_filepath, 'rb') as f: image_data = f.read() self.client.put_odlc_image(post_odlc.id, image_data) self.async_client.put_odlc_image(async_post_odlc.id, image_data).result() # Get the odlc image. get_image = self.client.get_odlc_image(post_odlc.id) async_get_image = self.async_client.get_odlc_image( async_post_odlc.id).result() self.assertEquals(image_data, get_image) self.assertEquals(image_data, async_get_image) # Delete the odlc image. self.client.delete_odlc_image(post_odlc.id) self.async_client.delete_odlc_image(async_post_odlc.id).result() with self.assertRaises(InteropError): self.client.get_odlc_image(post_odlc.id) with self.assertRaises(InteropError): self.async_client.get_odlc_image(async_post_odlc.id).result() # Delete odlc. self.client.delete_odlc(post_odlc.id) self.async_client.delete_odlc(async_post_odlc.id).result() self.assertNotIn(post_odlc, self.client.get_odlcs()) self.assertNotIn(async_post_odlc, self.async_client.get_odlcs().result())
def upload2Interop(self): s0 = self.mission.get() s1 = self.text1.get() s4 = self.text4.get() s5 = self.text5.get() s6 = self.text6.get() s7 = self.entry7.get() s8 = self.text8.get() s9 = self.entry9.get() typeDict = { "standard": interop_api_pb2.Odlc.STANDARD, "emergent": interop_api_pb2.Odlc.EMERGENT, "off_axis": interop_api_pb2.Odlc.OFF_AXIS } orientationDict = { "n": 1, "ne": 2, "e": 3, "se": 4, "s": 5, "sw": 6, "w": 7, "nw": 8 } shapeDict = { "circle": 1, "semicircle": 2, "quarter_circle": 3, "triangle": 4, "square": 5, "rectangle": 6, "trapezoid": 7, "pentagon": 8, "hexagon": 9, "heptagon": 10, "octagon": 11, "star": 12, "cross": 13 } colourDict = { "white": 1, "black": 2, "gray": 3, "red": 4, "blue": 5, "green": 6, "yellow": 7, "purple": 8, "brown": 9, "orange": 10 } myclient = client.Client(url='http://10.10.130.10:80', username='******', password='******') currPath = self._images[self._image_pos] odlc = interop_api_pb2.Odlc() odlc.mission = int(s0) odlc.type = typeDict[s1] try: odlc.latitude = float(gpcrop[currPath[10:]][0]) odlc.longitude = float(gpcrop[currPath[10:]][1]) except KeyError: print("OOPs") if s4 != "Orientation": odlc.orientation = orientationDict[s4] if s5 != "Shape": odlc.shape = shapeDict[s5] if s6 != "Background Colour": odlc.shape_color = colourDict[s6] if s7 != "": odlc.alphanumeric = s7 if s8 != "Alphanumeric Colour": odlc.alphanumeric_color = colourDict[s8] if s9 != "" and odlc.type == interop_api_pb2.Odlc.EMERGENT: odlc.description = s9 odlc = myclient.post_odlc(odlc) with open(currPath, 'rb') as f: image_data = f.read() myclient.put_odlc_image(odlc.id, image_data)