2016-12-02 88 views
1

我使用的是默认的例子..Python的前夜 - 更新记录,如果存在,否则插入

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

http://python-eve.org/features.html#event-hooks – metmirr

+0

UPSERT_ON_PUT功能已存在,但似乎无法正常工作。我错过了什么? –

+0

你会得到同样的错误吗?:'id = lookup [resource_def ['id_field']] KeyError:'_id' ' – metmirr

回答

1

您设置了additional_lookup额外的端点是只读的:

Besides the standard item endpoint which defaults to /<resource>/<ID_FIELD_value> , you can optionally define a secondary, read-only, endpoint like /<resource>/<person_name> .

在你的设置,我觉得你并不需要设置additional_lookup可言,因为它只是重新定义了item_lookup_field(它设置了您的读/写端点)。

+0

删除additional_lookup,并发送一个PUT请求到/ /NEW_ID_FIELD_VALUE与数据将在我的收藏中创建新的条目? –

+0

做了一个点安装升级前夕,一切开始工作,如记录在网站上。基本上我显然是在版本0.5.3。我想知道为什么? –

相关问题