Python Eve: Add custom route, changing an object manually

746 views Asked by At

I just started using Eve and it's really great for quickly getting a full REST API to run. However, I'm not entirely convinced that REST is perfect in all cases, e.g. I'd like to have a simple upvote route where I can increase the counter of an object. If I manually retrieve the object, increase the counter, and update it, I can easily run into problems with getting out-of-sync. So I'd like to add a simple extra-route, e.g. /resource/upvote that increases the upvote count by one and returns the object.

I don't know how "hacky" this is, so if it's over-the-top please tell me. I don't see a problem with having custom routes for some important tasks that would be too much work to do in a RESTful way. I know I could treat upvotes as its own resource, but hey I thought we're doing MongoDB, so let's not be overly relational.

So here is as far as I got:

@app.route('/api/upvote/<type>/<id>')
def upvote(type, id):
    obj = app.data.find_one_raw(type, id)
    obj['score'] += 1
  • Problem #1 find_one_raw returns None all the time. I guess I have to convert the id parameter? (I'm using the native MongoDB ObjectId)
  • Problem #2 How to save the object? I don't see a handy easy-to-use method like save_raw
  • Problem #3 Can we wrap the whole thing in a transaction or similar to make sure it's thread-safe? (I'm also new to MongoDB as you can tell).
1

There are 1 answers

1
Mandar Vaze On

1: type happens to be python keyword. Do you mean to say something like resource_type ?

2: There is app.data.insert (to create new) or app.data.update (to update existing one)

3: Apparently there are no transactions in mongodb as apparent from this thread (As you can tell, I am new to mongodb myself)