Search code examples
pythonmonkeypatchingeve

Monkey patch eve.methods for additional callbacks


I am attempting to monkey patch eve methods to provide a callback to do some pre-process and post-process with respectively the request and the reply before they get turned into payloads, e.g.:

from eve.methods.patch import patch_internal as __patch_internal
def my_patch(resource, payload=None, **lookup):
    response, last_modified, etag, status = __patch_internal(
                                          resource, payload,
                                          concurrency_check=True,
                                          skip_validation=False, **lookup)
    # call callback depending on resource passing response
    return response, last_modified, etag, status
    import eve.methods
    eve.methods.patch = my_patch

The problem I am facing is most of the functions within Eve are imported directly. I am obliged to fork Eve to do so?


Solution

  • Have you looked into Event Hooks? They allow you to bind custom callback functions to pre and post events and database operations. Callbacks can alter the original query, the document being stored, or the returned payload.

    def inject_username_lookup(resource, request, lookup):
        # alter the original query
        lookup["username"] = {'$exists': True}
    
    app = Eve()
    
    app.on_pre_GET += inject_username_lookup
    app.run()
    

    Since you can hook more than one callback to the same event (they will be executed in sequence), it allows for some pretty nice separation of concerns implementation. Database events are powerful too.