Reputation: 31
I have a python flask program(mini project) which get the image form user and process OCR detection. It works perfectly but now I came to notice that this code executes once when the server started and if the user selects the image again after running for the first time, it does not work properly. I simply used print
statement to detect where the error has been occurred and came to know that the import function not working at the second and more iterations.
my main.py:
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename
import shutil
import logging
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
from livereload import Server, shell
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def upload_form():
return render_template('upload.html')
@app.route('/', methods=['POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the files part
if 'files[]' not in request.files:
flash('No file part')
return redirect(request.url)
files = request.files.getlist('files[]')
for file in files:
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
log_file(filename)
flash('File(s) successfully uploaded')
ocr_detection()
return redirect('/')
def ocr_detection():#OCR
print('OCR')
import ocrDetection
ocrDetection.mask()
flash('JSON created')
def log_file(filename):
log_format = '%(asctime)s %(message)s'
log_path="D:/SARIGHA/OCR/source_code/log_path/"+"check_log.log"
logging.basicConfig(filename=log_path ,format='%(asctime)s %(message)s',level=logging.INFO,datefmt='%m/%d/%Y %I:%M:%S %p')
logging.info("FILE UPLOADED_"+filename)
if __name__ == "__main__":
#app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD']=True
app.run(host='192.168.106.51',debug=True,use_reloader=True)
It seems that the control enters into ocr_detection()
and execute the print('OCR')
and flash('JSON created')
but not importing ocrDetection import ocrDetection
and work
I also tried by putting import ocrDetection
at the top of the program like:
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename
import shutil
import logging
import ocrDetection
this makes me in big trouble that the detection starts before the flask server open.
Upvotes: 2
Views: 201
Reputation: 407
I suggest that you will go with the subprocess method in python:
def ocr_detection():
try:
proc = subprocess.Popen(shlex.split("python ocrDetection.py"),stdout=subprocess.PIPE)
out = proc.communicate()
except Exception as e:
print('something went wrong')
print(e)
Upvotes: 2
Reputation: 434
Maybe reloading the module helps?
from importlib import reload
try:
ocrDetection = reload(ocrDetection)
except NameError:
import ocrDetection
Upvotes: 0