Question

I have some custom flask methods in an eve app that need to communicate with a telnet device and return a result, but I also want to pre-populate data into some resources after retrieving data from this telnet device, like so:

@app.route("/get_vlan_description", methods=['POST'])
def get_vlan_description():
    switch = prepare_switch(request)
    result = dispatch_switch_command(switch, 'get_vlan_description')

    # TODO: populate vlans resource with result data and return status

My settings.py looks like this:

SERVER_NAME = '127.0.0.1:5000'
DOMAIN = {
    'vlans': {
        'id': {
            'type': 'integer',
            'required': True,
            'unique': True
        },
        'subnet': {
            'type': 'string',
            'required': True
        },
        'description': {
            'type': 'boolean',
            'default': False
        }
    }
}

I'm having trouble finding docs or source code for how to access a mongo resource directly and insert this data.

Was it helpful?

Solution

Have you looked into the on_insert hook? From the documentation:

When documents are about to be stored in the database, both on_insert(resource, documents) and on_insert_<resource>(documents) events are raised. Callback functions could hook into these events to arbitrarily add new fields, or edit existing ones. on_insert is raised on every resource being updated while on_insert_<resource> is raised when the <resource> endpoint has been hit with a POST request. In both circumstances, the event will be raised only if at least one document passed validation and is going to be inserted. documents is a list and only contains documents ready for insertion (payload documents that did not pass validation are not included).

So, if I get what you want to achieve, you could have something like this:

def telnet_service(resource, documents):
    """ 
        fetch data from telnet device;
        update 'documents' accordingly 
    """
    pass

app = Eve()
app.on_insert += telnet_service

if __name__ == "__main__":
    app.run()

Note that this way you don't have to mess with the database directly as Eve will take care of that.

If you don't want to store the telnet data but only send it back along with the fetched documents, you can hook to on_fetch instead.

Lastly, if you really want to use the data layer you can use app.data.driveras seen in this example snippet.

OTHER TIPS

use post_internal

Usage example:

from run import app
from eve.methods.post import post_internal

payload = {
    "firstname": "Ray",
    "lastname": "LaMontagne",
    "role": ["contributor"]
}

with app.test_request_context():
    x = post_internal('people', payload)
    print(x)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top