2

I'm new at Flask. I try to pass a parameter from the main, but it doesn't work. Hope somebody can help me. Here is my code

from flask import Flask, render_template, request
import controllFlask
import pickle

app = Flask(__name__) # creates a flask object
import subprocess 


@app.route('/', methods=['GET', 'POST'])
def ner():
    '''controlls input of Webapp and calls proccessing methods'''
    knownEntities = pickle.load( open( "entityDictThis.p", "rb" ))
    print("loades")
    content = ""
    if request.method == 'POST':
        testText = (request.form['input'])
        app.ma = controllFlask.controll(testText, knownEntities)
        subprocess.call("controllFlask.py", shell=True)
        with open("test.txt", "r") as f:
            content = f.read()    
    return render_template("ner.jinja2", content=content)

def flaskApp():
    app.debug = True
    app.run()

I want to open entityDictThis in flaskApp and give it to the ner-function. Because I hope in this way it loads only one time. At the moment it loads every time the page is reloaded and it takes very long. Is there a easy way?

JimmyDiJim
  • 61
  • 5
  • 1
    Are either of the suggested answers in https://stackoverflow.com/questions/14860007/pass-another-object-to-the-main-flask-application helpful? – bouteillebleu Nov 03 '17 at 13:48
  • Another possible way is to process `entityDictThis.p` within the main code of the module (remembering to close it once you've read it, too) and set the processed contents to a module-global variable that your view function `ner()` can access, but that may be kind of hacky. – bouteillebleu Nov 03 '17 at 13:49

1 Answers1

1

This seems to be only a scoping problem, simply put the line that loads the pickle file in the scope above and it should solve the issue.

from flask import Flask, render_template, request
import controllFlask
import pickle

app = Flask(__name__) # creates a flask object
import subprocess 

knownEntities = pickle.load( open( "entityDictThis.p", "rb" ))

@app.route('/', methods=['GET', 'POST'])
def ner():
    '''controlls input of Webapp and calls proccessing methods'''
    print("loades")
    content = ""
    if request.method == 'POST':
        testText = (request.form['input'])
        app.ma = controllFlask.controll(testText, knownEntities)
        subprocess.call("controllFlask.py", shell=True)
        with open("test.txt", "r") as f:
            content = f.read()    
    return render_template("ner.jinja2", content=content)

def flaskApp():
    app.debug = True
    app.run()

I would also suggest, as @bouteillebleu mentioned, to close the loaded file, using the with keyword, which does this automagically for you.

with open( "entityDictThis.p", "rb" ) as f:
    knownEntities = pickle.load(f)
Pax Vobiscum
  • 2,551
  • 2
  • 21
  • 32