Home > Back-end >  Recreate folder hierarchy (ParentID) using Python
Recreate folder hierarchy (ParentID) using Python

Time:08-24

The target is to get folders from one system and migrate to another using API. From system 1 I've got consistent response about folder name, it's id and parent id.

[{'depth': 0,
  'description': None,
  'display_order': 55,
  'id': 1,
  'name': 'Library',
  'parent_id': None,
  'suite_id': 8},
 {'depth': 1,
  'description': None,
  'display_order': 57,
  'id': 529466,
  'name': 'MYK [RE]',
  'parent_id': 1,
  'suite_id': 8},
 {'depth': 2,
  'description': None,
  'display_order': 59,
  'id': 530931,
  'name': 'MY BO',
  'parent_id': 529466,
  'suite_id': 8},
 {'depth': 3,
  'description': None,
  'display_order': 60,
  'id': 533682,
  'name': 'NU Robs',
  'parent_id': 530931,
  'suite_id': 8},

To create a folder in system 2 I can only send the ParentID and name. Could you please advise the logic how to create such loop in Python.

We could send inside the loop a get request to system 2 to check the existed folders, we'll receive a name and id(but it would be id for system 2 not for the first one) and parent id(the same way).

folders = client.send_get('get_sections/1')

for i in folders:

    response = requests.request(
        "GET",
        url_f,
        headers=headers,
    )

    zp_folders = response.json()
    # here we could check existed folders by name

Thank you!

CodePudding user response:

It is importand that the input is sorted by depth. Then you can simply iterarte through your data and be sure that the parent must have already been created in some step before. In each iteartion steo you can update a map from old id to new id. In this way you can translate between the two systems.

Pseudo code:

  1. Make sure that your source data is sorted by depth-property.
  2. Create an empty dict, e.g. named id_map, that maps ids from system 1 to system 2.
  3. Loop through your data and for each node from system 1:
    • get the new id of parent_id from id_map (if it's not None)
    • if parent_id is not in id_map stop with an error
    • create a new node in system 2:
    • store the mapping of old id to new id in id_map

CodePudding user response:

Something like that, using two functions with:

def find_sys2_parent_folder(folder_name: str):
response = requests.request(
    "GET",
    url_f,
    headers=headers,
)
for i in response:
    if i["values"]["name"] == folder_name:
        return i["parent_id"]


def create_sys2_folders(folders: List):
for i in folders:
    if i["parent_id"] is not None:
        i["parent_id"] = find_sys2_parent_folder(i["name"])
    response = requests.request(
        "POST",
        url_f,
        headers=headers,
        json=i
    )
    pprint(response)
  • Related