How to add to a list type in Python Eve without replacing old values

时光毁灭记忆、已成空白 提交于 2019-11-30 18:53:13

POST will allow you to add a new document to the users endpoint. If it is returning a 405 then you most likely need to enable the POST method by adding it to the RESOURCE_METHODS list, as all endpoints are read-only by default; see docs (alternatively you can only enable POST for the individual endpoint by adding the method to the local resource_methods instead.)

PATCH allows for the replacing of individual fields (as opposed to PUT, which will replace the whole document). So with PATCH you can atomically update the friends list by replacing it with a new value (a new list ObjectIds in your case), but you cannot push a single new ObjectId inside the existing list, I am afraid.

Here is the workaround that I used. It's probably not the most efficient way to do this, but it worked for me.

Instead of having a users/friends list like I had originally planned, I ended up creating a resource for shares. In my case, I wanted to know which crystals were shared with which users. So when I query crystals/<crystal_id>/shares, I should get a list of the shares for that crystal.

I think you could apply a solution like this to the users/friends scenario if you swap crystals for users and shares for friends. You might put two different user_id data_relations in your friends_schema (my shares_schema).

shares_schema = {
    'crystal_id': {
        'type': 'objectid',
        'required': True,
        'data_relation': {
            'resource': 'crystals',
            'embeddable': True,
        },
    },
    'user_id': {
        'type': 'objectid',
        'required': True,
        'data_relation': {
            'resource': 'users',
            'embeddable': True,
        },
    },
}

shares = {
    'internal_resource': True,
    'schema': shares_schema,
}

crystals_shares = {
    'schema': shares_schema,
    'url': 'crystals/<regex("[a-f0-9]{24}"):crystal_id>/shares',
    'datasource': {'source': 'shares'},
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!