Acessing “app” (Eve object) from hook callbacks

為{幸葍}努か 提交于 2019-12-24 02:30:24

问题


I'm using hooks in my Eve app to update a "summary" object every time a new item is added to my collection. To keep things clean, I've moved my callbacks to a separate dir/file that I import from run.py where I set up the hooks.

My problem is that I need to access the Eve() object (that I called "app") from inside my callback function (named on_inserted_expense). I couldn't find the "eve" way to do it, so I ended up using something like this decorator-like trick, which works:

from eve import Eve
from eventhooks import posthooks
from functools import wraps

app = Eve()

def passing_app(f):
  @wraps(f)
  def wrapper(*args, **kwargs):
    kwargs['app'] = app
    return f(*args, **kwargs)

  return wrapper

app.on_inserted_expenses += passing_app(posthooks.on_inserted_expense)

That way from eventhooks/posthooks.py I can do:

def on_inserted_expense(items, **kwargs):
  app = kwargs['app']
  for item in items:
    summaries = app.data.driver.db['summaries']
    summary = summaries.find_one({'title': 'default'})
    if not item_in_summary(item, summary):
      with app.test_request_context():
        update = update_summary(summary, item)
        patch_internal(summary, payload=update, concurrency_check=True)

My question, therefore, is: is there a way to retrieve the current "app" object from Eve in a cleaner way from anywhere within the application? If not, would that be something worth adding, maybe in the way of a singleton? Thanks!


回答1:


You probably want to to follow the Larger Flask Application pattern , so you can have your app object declared in your __init__.py and then you can import it anywhere you want. Remember, Eve is just a Flask application so whatever you can do with Flask you can generally do with Eve.




回答2:


I have been doing this:

from flask import current_app

And using current_app as the app.

Reference: http://flask.pocoo.org/docs/0.10/api/#flask.current_app

Are there pitfalls I should be aware of doing this? It seems to work when adding hooks.



来源:https://stackoverflow.com/questions/26347713/acessing-app-eve-object-from-hook-callbacks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!