Python Eve - 如果存在则更新记录否则插入

时间:2016-12-02 10:19:36

标签: python mongodb eve

我使用默认示例..

run.py

from eve import Eve
app = Eve(template_folder=tmpl_dir)

if __name__ == '__main__':
    app.run(debug=True)

settings.py

RESOURCE_METHODS = ['GET', 'POST', 'DELETE']
ITEM_METHODS = ['GET', 'PUT', 'PATCH', 'DELETE']
CACHE_CONTROL = 'max-age=20'
CACHE_EXPIRES = 20

IF_MATCH = False

people = {
    # 'title' tag used in item links.
    'item_title': 'person',
    'item_url': 'regex("[a-zA-Z0-9.]+")',
    'item_lookup': True,
    'item_lookup_field': 'firstname',
    'additional_lookup': {
        'url': 'regex("[\w]+")',
        'field': 'firstname'
    },
    'schema': {
        'firstname': {
            'type': 'string',
            #'required': True,
            'unique': True,
        },
        'age': {
            'type': 'integer'
        }
    }
}

DOMAIN = {
    'people': people
}

现在,我可以通过

轻松创建新条目
curl -X POST -F "firstname=john" -F "age=24" "http://127.0.0.1:5000/people"

输出

{"_updated": "Fri, 02 Dec 2016 10:12:58 GMT", "_created": "Fri, 02 Dec 2016 10:12:58 GMT", "_status": "OK", "_id": "5841492a10cf9320678bef65", "_links": {"self": {"href": "people/5841492a10cf9320678bef65", "title": "person"}}}

我现在可以轻松发送卷曲请求

curl -X GET "http://127.0.0.1:5000/people/john"

并获取记录,因为名字在我的附加查询中

输出

{"_updated": "Fri, 02 Dec 2016 10:12:58 GMT", "firstname": "john", "age": 24, "_links": {"self": {"href": "people/5841492a10cf9320678bef65", "title": "person"}, "collection": {"href": "people", "title": "people"}, "parent": {"href": "/", "title": "home"}}, "_created": "Fri, 02 Dec 2016 10:12:58 GMT", "_id": "5841492a10cf9320678bef65"}

我现在也可以修补文件并改变年龄,

curl -X PATCH -F "age=32" "http://127.0.0.1:5000/people/john"

输出

{"_updated": "Fri, 02 Dec 2016 10:15:56 GMT", "_created": "Fri, 02 Dec 2016 10:12:58 GMT", "_status": "OK", "_id": "5841492a10cf9320678bef65", "_links": {"self": {"href": "people/5841492a10cf9320678bef65", "title": "person"}}}

我的问题:

上面的 PATCH 只有在记录存在时才有效,有没有办法可以发送带有数据的PUT或PATCH请求,让我们决定创建新条目或修改如果条目已经存在?

希望我的问题足够清楚

0 个答案:

没有答案