在python-eve API资源中添加实现HATEOAS的链接
我正在使用 python-eve 来构建一个API。
我的设计很简单,包含两个资源:用户和设备:
- /users[/ID]
- /users/ID/devices[/ID]
代码在 (settings.py) 中是:
users_schema = {
'nickName': {
'type': 'string',
'required': True,
},
'email': {
'type': 'string',
'required': True,
'unique': True
}
}
devices_schema = {
'name': {
'type': 'string',
'required': True,
},
'user_id': {
'type': 'objectid',
'data_relation': {
'resource': 'users',
'embeddable': True
},
}
}
users = {
'item_title': 'user',
'url': 'users',
'schema': users_schema,
}
user_devices = {
'resource_title': 'devices',
'url': 'users/<regex("[a-f0-9]{24}"):user_id>/devices',
'schema': devices_schema,
'datasource': {
'source': 'devices',
}
}
DOMAIN = {
'users': users,
'user_devices': user_devices
}
如果我创建一个用户,那么这个用户资源看起来像这样 (/users/54465ae80640fd0f60f6aa09):
{
"_updated": "Tue, 21 Oct 2014 13:08:56 GMT",
"_etag": "d6ff9457f5b196a8c245a7dc91e7fca0d28c5268",
"_links": {
"self": {
"href": "/users/54465ae80640fd0f60f6aa09",
"title": "user"
},
"parent": {
"href": "",
"title": "home"
},
"collection": {
"href": "/users",
"title": "users"
}
},
"_created": "Tue, 21 Oct 2014 13:08:56 GMT",
"_id": "54465ae80640fd0f60f6aa09",
"nickName": "superuser",
"email": "super@user.com"
}
HATEOAS 默认是启用的。 在之前的资源中,我希望能看到一个指向用户设备的链接,也就是 /users/54465ae80640fd0f60f6aa09/devices,因为这个接口是存在的,在代码中有定义(user_devices),而且运行得很好。
我该如何让 python-eve 理解 用户 和 用户设备 之间的关系,以便将这些设备链接添加到用户资源中?否则,用户 54465ae80640fd0f60f6aa09 就不知道如何获取设备。
我期待的结果是这样的:
{
"_updated": "Tue, 21 Oct 2014 13:08:56 GMT",
"_etag": "d6ff9457f5b196a8c245a7dc91e7fca0d28c5268",
"_links": {
"self": {
"href": "/users/54465ae80640fd0f60f6aa09",
"title": "user"
},
"devices": {
"href": "/users/54465ae80640fd0f60f6aa09/devices",
"title": "devices"
},
"parent": {
"href": "",
"title": "home"
},
"collection": {
"href": "/users",
"title": "users"
}
},
"_created": "Tue, 21 Oct 2014 13:08:56 GMT",
"_id": "54465ae80640fd0f60f6aa09",
"nickName": "superuser",
"email": "super@user.com"
}
这样就“显而易见”如何获取设备了。
非常感谢。
2 个回答
0
我创建了一个自定义的钩子,用来把一个项目和其他集合连接起来。
把下面的代码加到你的应用里,然后定义一下你的项目和相关集合之间的数据关系。
举个例子,我有一些菜单是通过父节点连接的,所以在我的数据结构中有两个关系:
- 当前项目的父菜单是哪个 --> 子菜单
- 父菜单 --> 子菜单
所以我的数据结构是这样的(第一个关系是子菜单,第二个是父菜单):
"menu": {
"type": "dict",
"schema": {
"_id": {
"type": "objectid",
"data_relation": {
"resource": "menu",
"field": "parent_menu",
"embeddable": False,
}
},
"id": { "type": "string" } ,
"label": { "type": "string" },
"url": { "type": "string" },
"parent_menu": {
"type": "objectid",
"data_relation": {
"resource": "menu",
"field": "_id",
"embeddable": True,
},
},
},
},
这是根菜单的显示方式(只显示子菜单,不显示父菜单,链接关系是“菜单”):
{
"_id":"5c6ab8a5467a938b027aae64",
"id":"root",
"label":"Home",
"url":"/",
"_links":{
...
"self":{
"title":"Menu",
"href":"menu/5c6ab8a5467a938b027aae64"
},
...
"menu":{
"title":"menu",
"href":"menu?where={\"parent_menu\":\"5c6ab8a5467a938b027aae64\"}"
}
}
}
这是子菜单的样子(包含父菜单和子菜单的链接):
{
"_id":"5c6ab8a5467a938b027aae65",
"id":"submenu1",
"label":"Submenu1",
"url":"/#submenu1",
"parent_menu":"5c6ab8a5467a938b027aae64",
"_links":{
...
"self":{
"title":"Menu",
"href":"menu/5c6ab8a5467a938b027aae65"
},
...
"menu":{
"title":"menu",
"href":"menu?where={\"parent_menu\":\"5c6ab8a5467a938b027aae65\"}"
},
"parent_menu":{
"title":"menu",
"href":"menu/5c6ab8a5467a938b027aae64"
}
}
}
应用的代码如下:
def createLink(ref_collection, ref_field, ref_value):
print(f"createLink({ref_collection}, {ref_field}, {ref_value})")
ref_value = f"{ref_value}"
linkSufix = "/" + ref_value if ref_field == "_id" else "?where={\"" + ref_field + "\":\"" + ref_value + "\"}"
linkRel = {
"title": ref_collection,
"href": ref_collection + linkSufix,
}
print(f"createLink result: \n{linkRel}")
return linkRel
def add_links(resource_name, resource, schema):
linked_item_keys = list(key for key in schema if "data_relation" in schema[key] and key in resource)
print(f"linked_item_keys: {linked_item_keys}")
for key in linked_item_keys:
print(f"link needed for: {resource_name}.{key}")
itemSchema = schema[key]
item = resource[key]
data_relation = itemSchema["data_relation"]
ref_collection = data_relation["resource"]
ref_field = data_relation["field"]
link = createLink(ref_collection, ref_field, item)
links = resource["_links"] if "_links" in resource else []
link_rel = ref_collection if resource_name == ref_collection and key == "_id" else key
links[link_rel] = link
resource["_links"] = links
def add_links_to_item(resource_name, response):
print(f"------------------------------------")
print(f"(on_fetched_item) {resource_name} ")
print(f"response: \n{response}")
schema = config.DOMAIN[resource_name]["schema"]
print(f"""schema: \n{schema}""")
add_links(resource_name, response, schema)
app = Eve()
app.on_fetched_item += add_links_to_item
希望这对你有帮助!!
1
你还需要在用户和设备之间建立一个连接。
users_schema = {
'nickName': {
'type': 'string',
'required': True,
},
'data_relation': {
'resource': 'user_devices', # link to device on a field _id
'field': '_id',
'embeddable': True
},
'email': {
'type': 'string',
'required': True,
'unique': True
}
}