0

Let's say I want to execute a random function :

def compute_average( user) 

This function will compute the average of few value and insert it into a user field. It's just an example.

How to call this function using the eve api?

I looked up the documentation but did not find anything.

Babajaga
  • 77
  • 1
  • 3
  • 8

2 Answers2

2

Since Eve derives from Flask, you can route pages the Flask way:

from flask import jsonify
from eve import Eve
app = Eve()

@app.route('/average/<user>')
def compute_average(user):
    return jsonify({user:47})

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

Usage:

$ curl http://localhost:5000/average/joe

Result:

{
  "joe": 47
}
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • On running this I get error that says "ValueError: Attempted relative import in non-package". The shows up at the 3rd line: app=Eve(). Can you help me out? stuck for 3hrs.. https://stackoverflow.com/q/11536764/5658251 couldn't figure from this.. – Eswar Dec 20 '18 at 13:29
0

If I understand, what you want is to run custom code before/after requests. To do that, you can use Event Hooks to set callbacks before/after request or database events. An example to run your compute_average before any GET to users resource:

def compute_average(request, lookup) 
    # your code

app = Eve()
app.on_pre_GET_users += compute_average

app.run()

Your function parameters would change a little. As the documentation states, callbacks to a specific resource receive the original flask.request object and the current lookup dictionary as arguments.

But you can perform mongodb queries in your code as usual if you need to retrieve documents to perform your calculations. Check the documentation for more details.

gcw
  • 1,639
  • 1
  • 18
  • 37