Archive

Cannot open or write to file from custom controller

Path Finder

I've been experimenting with creating a custom controller for an splunk webapp we're working on. Ultimately, we want to be able to pass values to the controller and have it write those to a file on the server. I am able to get the webapp to call the controller, pass it values, and have it send a return, but if I add commands to open a file on the server it gives a "path not found" error (which I suspect is caused by Splunk not being able to run the script).

Here's the code that does run:

import logging
import os
import sys
import cherrypy

import splunk
import splunk.bundle as bundle
import splunk.appserver.mrsparkle.controllers as controllers
import splunk.appserver.mrsparkle.lib.util as util
from splunk.appserver.mrsparkle.lib.decorators import expose_page

class testService(controllers.BaseController):
    '''A test controller, to practice calling controllers from inside SPLUNK'''
    @expose_page(must_login=True, methods=['GET']) 
    def show(self, **kwargs):
        return self.render_template('/boti:/templates/WriteFile.html')

    @expose_page(must_login=True, methods=['POST'])
    def DocumentWriter(self, **params):
        return self.render_template('/boti:/templates/DocumentWritten.html')

When I change the DocumentWriter method like so:

@expose_page(must_login=True, methods=['POST'])
    def DocumentWriter(self, **params):
        outfile = open("find_me.txt", "w+")
        outfile.write("Found you")
        outfile.close()
        return self.render_template('/boti:/templates/DocumentWritten.html')

it won't even load the show() method. Is it simply not possible to read/write files on the server from a controller, or am I doing something horribly wrong?

Tags (3)
0 Karma
1 Solution

Path Finder

Fixed it. Changed the DocumentWriter code to the following:

@expose_page(must_login=True, trim_spaces = True, methods=['POST'])
def DocumentWriter(self, **params):

    output='<p>'
    for key,val in params.iteritems():
            output+=key+": "+val+"<br>"
    output+='</p>'

    writer=open("*file location*","w+")
    writer.write(output)
    writer.close()
    return output

Not sure why trim_spaces=true was so important, but it works now.

View solution in original post

0 Karma

Path Finder

Fixed it. Changed the DocumentWriter code to the following:

@expose_page(must_login=True, trim_spaces = True, methods=['POST'])
def DocumentWriter(self, **params):

    output='<p>'
    for key,val in params.iteritems():
            output+=key+": "+val+"<br>"
    output+='</p>'

    writer=open("*file location*","w+")
    writer.write(output)
    writer.close()
    return output

Not sure why trim_spaces=true was so important, but it works now.

View solution in original post

0 Karma