2016-12-02 90 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。我想知道爲什麼? –

相關問題