帮我用python写 import requests 部门树 简要描述 部门树 修改历史 日期 修改人 涉及接口 修改内容 2024年3月20日 朱晓锟 新增接口 请求URL GET /api/departments
时间: 2024-10-20 15:05:23 浏览: 20
Python中创建部门树通常涉及到数据结构,如字典、列表嵌套或者类来模拟树状结构。这里是一个简单的例子,假设我们有一个JSON格式的部门信息API返回的数据,我们可以使用requests库来获取数据并构建部门树:
```python
import requests
# 定义一个简单的部门类
class Department:
def __init__(self, id, name, children=[]):
self.id = id
self.name = name
self.children = children
# 请求API数据
def get_department_tree(url):
response = requests.get(url)
data = response.json() # 假设API返回的是一个包含部门信息的json数据
# 构建部门树
def build_tree(data):
departments = []
for dept in data:
department = Department(dept['id'], dept['name'])
if 'children' in dept:
department.children = [build_tree([child]) for child in dept['children']]
departments.append(department)
return departments
tree = build_tree(data)
return tree
# 示例URL
url = "http://example.com/api/departments" # 替换成实际的API地址
# 获取部门树并打印
department_tree = get_department_tree(url)
for department in department_tree:
print(f"{department.name} (ID: {department.id})")
print("Children:")
for child in department.children:
print(child.name)
阅读全文