Search code examples
pythonmongodbeve

Python Eve - Update Record if exists otherwise Insert


I'm using the default example..

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
}

Now, i can easily create new entries by

curl -X POST -F "firstname=john" -F "age=24" "http://127.0.0.1:5000/people"

OUTPUT

{"_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"}}}

I can now easily send a curl request

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

and get the record since firstname is in my additional lookup

OUTPUT

{"_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"}

I can now also patch the document and change the age by,

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

OUTPUT

{"_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"}}}

My Question:

The above PATCH will only work when the record exists, is there a way i can send a PUT or a PATCH request with the data and let eve decide to either create new entry or modify if the entry already exists?

hope my question is clear enough


Solution

  • The additional endpoint you set up with additional_lookup is read-only:

    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>.

    In your settings, I think you do not need to set additional_lookup at all, as it is just redefining item_lookup_field(which sets up your read/write endpoint).