JimmyDiJim
JimmyDiJim

Reputation: 61

pass parameters from Flask main

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?

Upvotes: 2

Views: 958

Answers (1)

Pax Vobiscum
Pax Vobiscum

Reputation: 2639

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)

Upvotes: 1

Related Questions