diff --git a/aw_server/api.py b/aw_server/api.py index a143c0c..3c672ed 100644 --- a/aw_server/api.py +++ b/aw_server/api.py @@ -107,7 +107,11 @@ def import_bucket(self, bucket_data: Any): bucket_id = bucket_data["id"] logger.info(f"Importing bucket {bucket_id}") - # TODO: Check that bucket doesn't already exist + if bucket_id in self.db.buckets(): + raise Exception( + f"Bucket '{bucket_id}' already exists. Delete it first or rename the bucket before importing." + ) + self.db.create_bucket( bucket_id, type=bucket_data["type"], @@ -132,8 +136,15 @@ def import_bucket(self, bucket_data: Any): ) def import_all(self, buckets: Dict[str, Any]): - for bid, bucket in buckets.items(): - self.import_bucket(bucket) + imported: List[str] = [] + try: + for _bid, bucket in buckets.items(): + self.import_bucket(bucket) + imported.append(bucket["id"]) + except Exception: + for bid in imported: + self.db.delete_bucket(bid) + raise def create_bucket( self, diff --git a/aw_server/rest.py b/aw_server/rest.py index 5a6b822..1d3089c 100644 --- a/aw_server/rest.py +++ b/aw_server/rest.py @@ -370,18 +370,22 @@ class ImportAllResource(Resource): @api.expect(buckets_export) @copy_doc(ServerAPI.import_all) def post(self): - # If import comes from a form in th web-ui - if len(request.files) > 0: - # web-ui form only allows one file, but technically it's possible to - # upload multiple files at the same time - for filename, f in request.files.items(): - buckets = json.loads(f.stream.read())["buckets"] + try: + # If import comes from a form in the web-ui + if len(request.files) > 0: + # web-ui form only allows one file, but technically it's possible to + # upload multiple files at the same time + for filename, f in request.files.items(): + buckets = json.loads(f.stream.read())["buckets"] + current_app.api.import_all(buckets) + # Normal import from body + else: + buckets = request.get_json()["buckets"] current_app.api.import_all(buckets) - # Normal import from body - else: - buckets = request.get_json()["buckets"] - current_app.api.import_all(buckets) - return None, 200 + except Exception as e: + logger.exception("Import failed") + return {"message": str(e)}, 400 + return {"message": "Import successful"}, 200 # LOGGING