def post(self): db.session().final_flush() from flask import jsonify ret = jsonify(self.erased) ret.status_code = 201 db.session.commit() return ret
def delete(self, id: uuid.UUID): lot = self.get_lot(id) self._delete(lot, self.get_ids()) db.session().final_flush() response = self.schema.jsonify(lot) db.session.commit() return response
def post(self): """Add one document.""" try: data = request.get_json(validate=True) except ValueError as err: raise ValidationError(err) hash3 = data['file_hash'] db_hash = ReportHash(hash3=hash3) db.session.add(db_hash) doc = TradeDocument(**data) trade = doc.lot.trade if trade: trade.documents.add(doc) confirm = ConfirmDocument(action=trade, user=g.user, devices=set(), documents={doc}) db.session.add(confirm) db.session.add(doc) db.session().final_flush() ret = self.schema.jsonify(doc) ret.status_code = 201 db.session.commit() return ret
def build(self): device = self.snapshot_json.pop('device') # type: Computer components = None if self.snapshot_json['software'] == (SnapshotSoftware.Workbench or SnapshotSoftware.WorkbenchAndroid): components = self.snapshot_json.pop('components', None) # type: List[Component] if isinstance(device, Computer) and device.hid: device.add_mac_to_hid(components_snap=components) snapshot = Snapshot(**self.snapshot_json) # Remove new actions from devices so they don't interfere with sync actions_device = set(e for e in device.actions_one) device.actions_one.clear() if components: actions_components = tuple(set(e for e in c.actions_one) for c in components) for component in components: component.actions_one.clear() assert not device.actions_one assert all(not c.actions_one for c in components) if components else True db_device, remove_actions = self.resource_def.sync.run(device, components) del device # Do not use device anymore snapshot.device = db_device snapshot.actions |= remove_actions | actions_device # Set actions to snapshot # commit will change the order of the components by what # the DB wants. Let's get a copy of the list so we preserve order ordered_components = OrderedSet(x for x in snapshot.components) # Add the new actions to the db-existing devices and components db_device.actions_one |= actions_device if components: for component, actions in zip(ordered_components, actions_components): component.actions_one |= actions snapshot.actions |= actions if snapshot.software == SnapshotSoftware.Workbench: # Check ownership of (non-component) device to from current.user if db_device.owner_id != g.user.id: raise InsufficientPermission() # Compute ratings try: rate_computer, price = RateComputer.compute(db_device) except CannotRate: pass else: snapshot.actions.add(rate_computer) if price: snapshot.actions.add(price) elif snapshot.software == SnapshotSoftware.WorkbenchAndroid: pass # TODO try except to compute RateMobile # Check if HID is null and add Severity:Warning to Snapshot if snapshot.device.hid is None: snapshot.severity = Severity.Warning db.session.add(snapshot) db.session().final_flush() ret = self.schema.jsonify(snapshot) # transform it back ret.status_code = 201 db.session.commit() return ret
def post(self): l = request.get_json() lot = Lot(**l) db.session.add(lot) db.session().final_flush() ret = self.schema.jsonify(lot) ret.status_code = 201 db.session.commit() return ret
def _post_one(self): t = request.get_json() tag = Tag(**t) if tag.like_etag(): raise CannotCreateETag(tag.id) db.session.add(tag) db.session().final_flush() db.session.commit() return Response(status=201)
def post(self): """ Create one res_obj """ res_json = request.get_json() res_obj = self.model(**res_json) db.session.add(res_obj) db.session().final_flush() ret = self.schema.jsonify(res_obj) ret.status_code = 201 db.session.commit() return ret
def post(self, id: uuid.UUID): lot = self.get_lot(id) self._post(lot, self.get_ids()) db.session().final_flush() ret = self.schema.jsonify(lot) ret.status_code = 201 db.session.commit() return ret
def merge_devices(self, dev1_id: int, dev2_id: int) -> Device: """Merge the current device with `with_device` (dev2_id) by adding all `with_device` actions under the current device, (dev1_id). This operation is highly costly as it forces refreshing many models in session. """ # base_device = Device.query.filter_by(id=dev1_id, owner_id=g.user.id).one() self.base_device = Device.query.filter_by(id=dev1_id, owner_id=g.user.id).one() self.with_device = Device.query.filter_by(id=dev2_id, owner_id=g.user.id).one() if self.base_device.allocated or self.with_device.allocated: # Validation than any device is allocated msg = 'The device is allocated, please deallocated before merge.' raise ValidationError(msg) if not self.base_device.type == self.with_device.type: # Validation than we are speaking of the same kind of devices raise ValidationError('The devices is not the same type.') # Adding actions of self.with_device with_actions_one = [a for a in self.with_device.actions if isinstance(a, actions.ActionWithOneDevice)] with_actions_multiple = [a for a in self.with_device.actions if isinstance(a, actions.ActionWithMultipleDevices)] # Moving the tags from `with_device` to `base_device` # Union of tags the device had plus the (potentially) new ones self.base_device.tags.update([x for x in self.with_device.tags]) self.with_device.tags.clear() # We don't want to add the transient dummy tags db.session.add(self.with_device) # Moving the actions from `with_device` to `base_device` for action in with_actions_one: if action.parent: action.parent = self.base_device else: self.base_device.actions_one.add(action) for action in with_actions_multiple: if action.parent: action.parent = self.base_device else: self.base_device.actions_multiple.add(action) # Keeping the components of with_device components = OrderedSet(c for c in self.with_device.components) self.base_device.components = components # Properties from with_device self.merge() db.session().add(self.base_device) db.session().final_flush() return self.base_device
def _create_many_regular_tags(self, num: int): tags_id, _ = g.tag_provider.post('/', {}, query=[('num', num)]) tags = [ Tag(id=tag_id, provider=g.inventory.tag_provider) for tag_id in tags_id ] db.session.add_all(tags) db.session().final_flush() response = things_response(self.schema.dump(tags, many=True, nested=1), code=201) db.session.commit() return response
def put(self, tag_id: str, device_id: str): """Links an existing tag with a device.""" tag = Tag.from_an_id(tag_id).one() # type: Tag if tag.device_id: if tag.device_id == device_id: return Response(status=204) else: raise LinkedToAnotherDevice(tag.device_id) else: tag.device_id = device_id db.session().final_flush() db.session.commit() return Response(status=204)
def delete(self, tag_id: str, device_id: str): tag = Tag.from_an_id(tag_id).filter_by(owner=g.user).one() # type: Tag device = Device.query.filter_by(owner=g.user).filter_by( id=device_id).one() if tag.provider: # if is an unamed tag not do nothing return Response(status=204) if tag.device == device: tag.device_id = None db.session().final_flush() db.session.commit() return Response(status=204)
def snapshot(self, snapshot_json: dict, resource_def): """ Performs a Snapshot. See `Snapshot` section in docs for more info. """ # Note that if we set the device / components into the snapshot # model object, when we flush them to the db we will flush # snapshot, and we want to wait to flush snapshot at the end device = snapshot_json.pop('device') # type: Computer components = None if snapshot_json['software'] == SnapshotSoftware.Workbench: components = snapshot_json.pop('components') # type: List[Component] snapshot = Snapshot(**snapshot_json) # Remove new events from devices so they don't interfere with sync events_device = set(e for e in device.events_one) device.events_one.clear() if components: events_components = tuple(set(e for e in c.events_one) for c in components) for component in components: component.events_one.clear() assert not device.events_one assert all(not c.events_one for c in components) if components else True db_device, remove_events = resource_def.sync.run(device, components) snapshot.device = db_device snapshot.events |= remove_events | events_device # Set events to snapshot # commit will change the order of the components by what # the DB wants. Let's get a copy of the list so we preserve order ordered_components = OrderedSet(x for x in snapshot.components) # Add the new events to the db-existing devices and components db_device.events_one |= events_device if components: for component, events in zip(ordered_components, events_components): component.events_one |= events snapshot.events |= events # Compute ratings for rate in (e for e in events_device if isinstance(e, WorkbenchRate)): rates = rate.ratings() snapshot.events |= rates db.session.add(snapshot) db.session().final_flush() ret = self.schema.jsonify(snapshot) # transform it back ret.status_code = 201 db.session.commit() return ret
def post(self): # Create delivery note dn = request.get_json() dlvnote = Deliverynote(**dn) # Create a lot lot_name = dlvnote.document_id + "_" + datetime.datetime.utcnow( ).strftime("%Y-%m-%d") new_lot = Lot(name=lot_name) dlvnote.lot_id = new_lot.id db.session.add(new_lot) db.session.add(dlvnote) db.session().final_flush() ret = self.schema.jsonify(dlvnote) ret.status_code = 201 db.session.commit() return ret
def post(self): """Posts an action.""" res_json = request.get_json(validate=False) tmp_snapshots = app.config['TMP_LIVES'] path_live = save_json(res_json, tmp_snapshots, '', live=True) res_json.pop('debug', None) res_json.pop('elapsed', None) res_json.pop('os', None) res_json_valid = self.schema.load(res_json) live = self.live(res_json_valid) db.session.add(live) db.session().final_flush() ret = self.schema.jsonify(live) ret.status_code = 201 db.session.commit() move_json(tmp_snapshots, path_live, '', live=True) return ret
def put(self, tag_id: str, device_id: int): """Links an existing tag with a device.""" device_id = int(device_id) tag = Tag.from_an_id(tag_id).filter_by(owner=g.user).one() # type: Tag if tag.device_id: if tag.device_id == device_id: return Response(status=204) else: raise LinkedToAnotherDevice(tag.device_id) else: # Check if this device exist for this owner Device.query.filter_by(owner=g.user).filter_by(id=device_id).one() tag.device_id = device_id db.session().final_flush() db.session.commit() return Response(status=204)
def post(self): """Posts an event.""" json = request.get_json(validate=False) if not json or 'type' not in json: raise ValidationError('Resource needs a type.') # todo there should be a way to better get subclassess resource # defs resource_def = app.resources[json['type']] e = resource_def.schema.load(json) if json['type'] == Snapshot.t: return self.snapshot(e, resource_def) Model = db.Model._decl_class_registry.data[json['type']]() event = Model(**e) db.session.add(event) db.session().final_flush() ret = self.schema.jsonify(event) ret.status_code = 201 db.session.commit() return ret
def post(self): """Posts an action.""" json = request.get_json(validate=False) if not json or 'type' not in json: raise ValidationError('Post request needs a json.') # todo there should be a way to better get subclassess resource # defs resource_def = app.resources[json['type']] if json['type'] == Snapshot.t: if json.get('software') == 'Web' and json['device'] == 'Computer': txt = 'Invalid snapshot' raise ValidationError(txt) if json.get('software') == 'Web': snapshot = SnapshotView(json, resource_def, self.schema) return snapshot.post() # TODO @cayop uncomment at four weeks # if not 'data' in json: # txt = 'Invalid snapshot' # raise ValidationError(txt) # snapshot_data = decode_snapshot(json) snapshot_data = json if 'data' in json: snapshot_data = decode_snapshot(json) if not snapshot_data: txt = 'Invalid snapshot' raise ValidationError(txt) snapshot = SnapshotView(snapshot_data, resource_def, self.schema) return snapshot.post() if json['type'] == VisualTest.t: pass # TODO JN add compute rate with new visual test and old components device if json['type'] == InitTransfer.t: return self.transfer_ownership() if json['type'] == Trade.t: trade = trade_view.TradeView(json, resource_def, self.schema) return trade.post() if json['type'] == Confirm.t: confirm = trade_view.ConfirmView(json, resource_def, self.schema) return confirm.post() if json['type'] == Revoke.t: revoke = trade_view.RevokeView(json, resource_def, self.schema) return revoke.post() if json['type'] == 'ConfirmRevoke': revoke = trade_view.RevokeView(json, resource_def, self.schema) return revoke.post() if json['type'] == 'RevokeDocument': revoke = trade_view.RevokeDocumentView(json, resource_def, self.schema) return revoke.post() if json['type'] == 'ConfirmDocument': confirm = trade_view.ConfirmDocumentView(json, resource_def, self.schema) return confirm.post() if json['type'] == 'ConfirmRevokeDocument': confirm_revoke = trade_view.ConfirmRevokeDocumentView( json, resource_def, self.schema) return confirm_revoke.post() if json['type'] == 'DataWipe': erased = ErasedView(json, resource_def.schema) return erased.post() a = resource_def.schema.load(json) Model = db.Model._decl_class_registry.data[json['type']]() action = Model(**a) db.session.add(action) db.session().final_flush() ret = self.schema.jsonify(action) ret.status_code = 201 db.session.commit() return ret
def delete(self, id): tag = Tag.from_an_id(id).filter_by(owner=g.user).one() tag.delete() db.session().final_flush() db.session.commit() return Response(status=204)
def post(self): db.session().final_flush() ret = self.schema.jsonify(self.trade) ret.status_code = 201 db.session.commit() return ret