def edit(id): try: reqJson = request.get_json() with db.atomic(): driver = Driver.get_or_none(id) if not driver: raise Exception('Motorista não encontrado.') truckType = TruckType.get_or_none(reqJson['truck_type']) if not truckType: raise Exception('Tipo de caminhão inválido') stop_date = datetime.datetime.strptime(reqJson['stop_date'], '%d/%m/%Y %H:%M:%S') driver.name = reqJson['name'] driver.age = reqJson['age'] driver.gender = reqJson['gender'] driver.license_type = reqJson['license_type'] driver.has_truck = reqJson['has_truck'] driver.truck_type = reqJson['truck_type'] driver.loaded = reqJson['loaded'] driver.origin = reqJson['origin'] driver.destination = reqJson['destination'] driver.stop_date = stop_date driver.save() return model_to_dict(driver) except Exception as e: return {'error': str(e)}, 400
def create_user(): try: data = request.get_json() new_user = services.create_user(data) except ValueError as error: raise BadRequest(str(error)) from error else: return {'id': new_user.id}, 201
def login(): try: data = request.get_json() session_info = services.create_session(data['username'], data['password']) except ValueError as error: raise BadRequest(str(error)) from error else: return session_info
def update_records_label(record_uid): record = get_object_or_404(Record, record_uid) data = request.get_json() label_uid = data.pop('label_uid') if label_uid is not None: get_object_or_404(Label, label_uid) record.label_uid = label_uid db.session.add(record) db.session.commit() return record.to_dict()
def _get_body_argument(self, body, arguments, has_kwargs, sanitize): x_body_name = sanitize(self.body_schema.get("x-body-name", "body")) if is_jsan(request) and JSAN_CONTENT_TYPE in self.consumes: return { x_body_name: from_jsan(self.body_schema, request.get_json(force=True)) } return super()._get_body_argument(body, arguments, has_kwargs, sanitize)
def new_label(): label_data = request.get_json() try: label = Label(**label_data) db.session.add(label) db.session.commit() return label.to_dict() except exc.IntegrityError as ex: db.session.rollback() flask.abort(400, str(ex)) except ValueError as ex: flask.abort(400, str(ex))
def new_recorder(): recorder_data = request.get_json() try: recorder = Recorder(**recorder_data) db.session.add(recorder) db.session.commit() return recorder.to_dict() except exc.IntegrityError as ex: db.session.rollback() flask.abort(400, str(ex)) except ValueError as ex: flask.abort(400, str(ex))
def produce(): producer = KafkaProducer(bootstrap_servers='kafka:9092', max_request_size=10000000) print("create producer") req = request.get_json() msg = req["message"] topic_name = os.environ.get("TOPIC_NAME") producer.send(topic_name, msg.encode('utf-8')) producer.close() return 'OK'
def update_recorder(recorder_uid): recorder = get_object_or_404(Recorder, recorder_uid) recorder_data = request.get_json() location_description = recorder_data.pop('location_description') try: if location_description is not None: recorder.location_description = location_description db.session.commit() return recorder.to_dict() except exc.IntegrityError as ex: db.session.rollback() flask.abort(400, str(ex)) except ValueError as ex: flask.abort(400, str(ex))
def new_record(): record_data = request.get_json() recorder = flask.g.recorder if record_data["series_uid"] not in [s.uid for s in recorder.serieses]: flask.abort(403, "Recorder {} does not maintain series {}".format( recorder.uid, record_data["series_uid"] )) if record_data["label_uid"] is not None: get_object_or_404(Label, record_data["label_uid"]) try: record = Record(**record_data) db.session.add(record) db.session.commit() return record.to_dict() except exc.IntegrityError as ex: db.session.rollback() flask.abort(400, str(ex)) except ValueError as ex: flask.abort(400, str(ex))
def update_series_parameters(series_uid): series = get_object_or_404(Series, series_uid) parameters = request.get_json() try: uid = parameters.pop('uid') parameters_set = get_object(RecordingParameters, uid) except orm.exc.NoResultFound: parameters_set = RecordingParameters(uid=uid, **parameters) except KeyError: parameters_set = RecordingParameters(**parameters) series.parameters_uid = parameters_set.uid try: db.session.add(parameters_set) db.session.commit() return parameters_set.to_dict() except exc.IntegrityError as ex: db.session.rollback() flask.abort(400, str(ex)) except ValueError as ex: flask.abort(400, str(ex))
def update_series(series_uid): series = get_object_or_404(Series, series_uid) series_data = request.get_json() description = series_data.pop('description', None) recorder_uid = series_data.pop('recorder_uid', None) try: if description is not None: series.description = description if recorder_uid is not None: if series.records: flask.abort(400, "Cannot change recorder of non empty series") series.recorder_uid = recorder_uid db.session.commit() return series.to_dict() except exc.IntegrityError as ex: db.session.rollback() flask.abort(400, str(ex)) except ValueError as ex: flask.abort(400, str(ex))
def add(): try: reqJson = request.get_json() with db.atomic(): truckType = TruckType.get_or_none(reqJson['truck_type']) if not truckType: raise Exception('Tipo de caminhão inválido') stop_date = datetime.datetime.strptime(reqJson['stop_date'], '%d/%m/%Y %H:%M:%S') driver = Driver.create( name = reqJson['name'], age = reqJson['age'], gender = reqJson['gender'], license_type = reqJson['license_type'], has_truck = reqJson['has_truck'], truck_type = reqJson['truck_type'], loaded = reqJson['loaded'], origin = reqJson['origin'], destination = reqJson['destination'], stop_date = stop_date) return model_to_dict(driver) except Exception as e: return {'error': str(e)}, 400
def new_series(): series_data = request.get_json() get_object_or_404(Recorder, series_data['recorder_uid']) parameters = series_data.pop('parameters') try: try: uid = parameters.pop('uid') parameters_obj = get_object(RecordingParameters, uid) except orm.exc.NoResultFound: parameters_obj = RecordingParameters(uid=uid, **parameters) except KeyError: parameters_obj = RecordingParameters(**parameters) db.session.add(parameters_obj) db.session.commit() series = Series(parameters_uid=parameters_obj.uid, **series_data) db.session.add(series) db.session.commit() return series.to_dict() except exc.IntegrityError as ex: db.session.rollback() flask.abort(400, str(ex)) except ValueError as ex: flask.abort(400, str(ex)) return {}
def vrp_procedure(): """ Main RPC endpoint for passing input data for optimized outputs. :origin_latitude: float :origin_longitude: float :unit: string; maps to unit of measure key from POST :demand: list-like; contains ordered demand nodes represented as dict-like objects :demand_longitude: float :demand_quantity: int :demand_cluster: int :vehicle_max_capacity_quantity: int :vehicle_definitions': list-like; int for vehicle max capacity overrides """ if request.is_json: body = ProcedureRequest.from_dict(request.get_json()) # noqa: E501 else: return make_response( jsonify( InvalidUsageError( f"Incorrect request format! Content type received '{request.content_type}' instead of 'application/json'" )), 400, ) demand = body.demand demand_latitudes = [d.latitude for d in demand] demand_longitudes = [d.longitude for d in demand] demand_quantities = [d.quantity for d in demand] # cluster by location (lat, lon) clusters = distance.create_dbscan_clusters(demand_latitudes, demand_longitudes) origin = body.origin # list of lists for all-to-all distances matrix = distance.create_matrix( (origin.latitude, origin.longitude), demand_latitudes, demand_longitudes, ) # manage solve solution = model.create_vehicles(matrix, [0] + demand_quantities, clusters) response = { "origin": origin, "demand": demand, "unit": body.unit, "vehicle_capacity": body.vehicle_capacity, } response_solution = [{ "cluster": clusters[i], "stop_id": solution["stops"][i], "vehicle_id": solution["id"][i], } for i in range(len(demand))] response["solution"] = response_solution return jsonify(response)
def create_task(user): data = request.get_json() new_task = services.create_task(user, data) return {'id': new_task.id}, 201
def update_task(task_id, user): updated_task = services.update_task(task_id, user, request.get_json()) if not updated_task: raise exc.NotFound() return NoContent
def route_procedure(): """ Main RPC endpoint for passing input data for optimized outputs. :stack_id: integer :origin_latitude: float :origin_longitude: float :unit: string; maps to unit of measure key from POST :demand: list-like; contains ordered demand nodes represented as dict-like objects :demand_longitude: float :demand_quantity: int :demand_cluster: int :vehicle_max_capacity_quantity: int :vehicle_definitions': list-like; int for vehicle max capacity overrides """ if request.is_json: body = ProcedureRequest.from_dict(request.get_json()) # noqa: E501 else: return make_response( jsonify( InvalidUsageError( f"Incorrect request format! Content type received '{request.content_type}' instead of 'application/json'" )), 400, ) demand = body.demand stack_id = body.stack_id demand_ids = [int(d.id) for d in demand] demand_latitudes = [float(d.latitude) for d in demand] demand_longitudes = [float(d.longitude) for d in demand] demand_quantities = [d.quantity for d in demand] origin = body.origin # manage solve routes = model.create_vehicles( origin_lat=origin.latitude, origin_lon=origin.longitude, dest_lats=demand_latitudes, dest_lons=demand_longitudes, demand_quantities=demand_quantities, max_vehicle_capacity=body.vehicle_capacity, ) default_response = { "stack_id": stack_id, "origin": origin, "demand": demand, "unit": body.unit, "vehicle_capacity": body.vehicle_capacity, } if len(routes["stops"]) == 0: default_response["routes"] = routes return make_response(jsonify(default_response), 200) results = [{ "depot_id": origin.id, "demand_id": demand[i].id, "stop_number": routes["stops"][i], "vehicle_id": routes["id"][i], } for i in range(len(demand))] try: if not request.headers.get("Authorization"): raise ValueError("Unauthroized request") input_data: dict = {"stack_id": stack_id, "routes": results} response = requests.post(CRUD_URL, headers=request.headers, json=input_data) if response.status_code not in [200, 201]: raise ValueError("Integration error") return make_response(jsonify(loads(response.text)), 200) except: default_response["routes"] = results return make_response(jsonify(default_response), 200)
def add_new_place(): req = request.get_json() new_place = Place.create(req['title']) return new_place.to_dict(), 201, {}