Can't run a Flask server
Question:
I’m trying to follow this online tutorial for a Flask/Tensorflow/React application, but I’m having some trouble at the end now trying to run the Flask server.
Flask version: 2.2.3
Python version: 3.10.0
I’ve search online for solutions, but nothing I’ve tried has worked. Here’s the ways I’ve tried to run the application:
Not sure if this could be helpful in coming to a solution, but incase it is, here’s my app.py file:
import os
import numpy as np
from flask import Flask, request
from flask_cors import CORS
from keras.models import load_model
from PIL import Image, ImageOps
app = Flask(__name__) # new
CORS(app) # new
@app.route('/upload', methods=['POST'])
def upload():
# Disable scientific notation for clarity
np.set_printoptions(suppress=True)
# Load the model
model = load_model("keras_Model.h5", compile=False)
# Load the labels
class_names = open("labels.txt", "r").readlines()
# Create the array of the right shape to feed into the keras model
# The 'length' or number of images you can put into the array is
# determined by the first position in the shape tuple, in this case 1
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
# Replace this with the path to your image
image = Image.open("<IMAGE_PATH>").convert("RGB")
# resizing the image to be at least 224x224 and then cropping from the center
size = (224, 224)
image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)
# turn the image into a numpy array
image_array = np.asarray(image)
# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
# Load the image into the array
data[0] = normalized_image_array
# Predicts the model
prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index]
confidence_score = prediction[0][index]
# Print prediction and confidence score
print("Class:", class_name[2:], end="")
print("Confidence Score:", confidence_score)
Does anyone know what I’m doing wrong here, is there maybe something obvious I’m missing that’s causing the problem? If there’s any other info I can add that may be helpful, please let me know, thanks.
Edit:
I’ve added the execution section at the end of my code:
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000)
And now ‘python -m flask run’ does attempt to run the app, so the original post question is answered. There does seem to be a subsequent problem now though, it constantly returns this error. I installed tensorflow using ‘pip3 install tensorflow’ and it does install successfully, but then it always returns with the module not found error. Tensorflow doesn’t appear in pip freeze package list, am now looking to see how/why this is.
Edit2: My question was flagged as already answered here, though I’m struggling to see how, as that post has absolutely no mention at all on why ‘flask run’ or any way of trying to run a flask app might not work, or what to do when it doesn’t, which is what this question is. That post is simply discussing the ‘correct’ way to run a flask app, not how to run one at all when it’s not running.
Answers:
At the end of the script, you need to use the function
app.run(host="0.0.0.0", port=81)
Otherwise, the app doesn’t deploy. You’re simply creating it. (Edit: You can use whatever host or port you’d like.)
I’m not sure why the website didn’t say this because this is a basic thing when using Flask. It’s a possibility you aren’t supposed to do this however, in general, you would run the "app.run".
You forgot an execution section at the end of your script, that’s why your program isn’t running.
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
# you need to include this section in your script to execute your program
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000)
I’m trying to follow this online tutorial for a Flask/Tensorflow/React application, but I’m having some trouble at the end now trying to run the Flask server.
Flask version: 2.2.3
Python version: 3.10.0
I’ve search online for solutions, but nothing I’ve tried has worked. Here’s the ways I’ve tried to run the application:
Not sure if this could be helpful in coming to a solution, but incase it is, here’s my app.py file:
import os
import numpy as np
from flask import Flask, request
from flask_cors import CORS
from keras.models import load_model
from PIL import Image, ImageOps
app = Flask(__name__) # new
CORS(app) # new
@app.route('/upload', methods=['POST'])
def upload():
# Disable scientific notation for clarity
np.set_printoptions(suppress=True)
# Load the model
model = load_model("keras_Model.h5", compile=False)
# Load the labels
class_names = open("labels.txt", "r").readlines()
# Create the array of the right shape to feed into the keras model
# The 'length' or number of images you can put into the array is
# determined by the first position in the shape tuple, in this case 1
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
# Replace this with the path to your image
image = Image.open("<IMAGE_PATH>").convert("RGB")
# resizing the image to be at least 224x224 and then cropping from the center
size = (224, 224)
image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)
# turn the image into a numpy array
image_array = np.asarray(image)
# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
# Load the image into the array
data[0] = normalized_image_array
# Predicts the model
prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index]
confidence_score = prediction[0][index]
# Print prediction and confidence score
print("Class:", class_name[2:], end="")
print("Confidence Score:", confidence_score)
Does anyone know what I’m doing wrong here, is there maybe something obvious I’m missing that’s causing the problem? If there’s any other info I can add that may be helpful, please let me know, thanks.
Edit:
I’ve added the execution section at the end of my code:
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000)
And now ‘python -m flask run’ does attempt to run the app, so the original post question is answered. There does seem to be a subsequent problem now though, it constantly returns this error. I installed tensorflow using ‘pip3 install tensorflow’ and it does install successfully, but then it always returns with the module not found error. Tensorflow doesn’t appear in pip freeze package list, am now looking to see how/why this is.
Edit2: My question was flagged as already answered here, though I’m struggling to see how, as that post has absolutely no mention at all on why ‘flask run’ or any way of trying to run a flask app might not work, or what to do when it doesn’t, which is what this question is. That post is simply discussing the ‘correct’ way to run a flask app, not how to run one at all when it’s not running.
At the end of the script, you need to use the function
app.run(host="0.0.0.0", port=81)
Otherwise, the app doesn’t deploy. You’re simply creating it. (Edit: You can use whatever host or port you’d like.)
I’m not sure why the website didn’t say this because this is a basic thing when using Flask. It’s a possibility you aren’t supposed to do this however, in general, you would run the "app.run".
You forgot an execution section at the end of your script, that’s why your program isn’t running.
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
# you need to include this section in your script to execute your program
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000)