0

I have a Flask application which requires data from another python file ( every time i'm accessing /result-var - I want ANOTHER_FILE to be executed, to return updated variable_with_data to template. If I'm using subprocess.call - I don't have access to external variables. If I'm using import - ANOTHER_FILE only runs once ( to run again I have to restart Flask app ). But I need this variable_with_data each time /result-var accessed from browser.

@application.route('/result-var')
def result_var():
#    subprocess.call("ANOTHER_FILE.py", shell = True)
    from ANOTHER_FILE import output_in_var
    variable_with_data = output_in_var
    return render_template('result.html', variable_with_data=variable_with_data)

Please give an idea, what options I have. TIA!

ev47295
  • 19
  • 3
  • what do you mean by " If I'm using import - ANOTHER_FILE only runs once." should it not run once per every page load? – marxmacher Jan 04 '20 at 08:12
  • Thanks for reply! Yes, you are right. It should run once per every page load. But on each new request from browser I've got the same result, from first request. Now it runs only once per flask app load. – ev47295 Jan 04 '20 at 08:21

1 Answers1

1

If I understand the question correctly, then what you need to do is wrap the contents that you want to run from ANOTHER_FILE into a function, which you can then call.

So assuming you have ANOTHER_FILE which contains something like:

data = read_data() 
result = process_data(data) 
output_in_var = prepare_output(result)

then you can wrap all of that into a function,

def produces_output_in_var():
    data = read_data() 
    result = process_data(data) 
    output_in_var = prepare_output(result)

and then call the function to explicitly run the code (rather than implicitly running it on import):

from ANOTHER_FILE import produces_output_in_var

@application.route('/result-var')
def result_var():
    variable_with_data = produces_output_in_var()
    return render_template('result.html', variable_with_data=variable_with_data)

Also see: Why is Python running my module when I import it, and how do I stop it? and the python docs on this might help, but they're a little technical: https://docs.python.org/3/reference/import.html

Paradise
  • 1,408
  • 1
  • 14
  • 25
  • Hi, thanks for the idea, that could be one of the options! But other libraries import, variables, all that staff need to be moved to flask application, then? right? so it's not the optimal – ev47295 Jan 05 '20 at 05:37
  • Unfortunately you are correct. The hacky solution is to re-import the class which gets you the import side effects. I would not recommend this, and it is NOT best practice! This is a good lesson around importing and class structures That said, in python 2 you should be able to do `reload(ANOTHER_FILE)` before the import. In Python <3.4 `imp.reload(ANOTHER_FILE)`. in Python >=3.4 `importlib.reload(ANOTHER_FILE)` – Paradise Jan 07 '20 at 01:27