[PYTHON] Flask Primer Memo

Aidemy 2020/10/4

Introduction

Hello, it is Yope! I am a liberal arts student, but I was interested in the possibilities of AI, so I went to the AI-specialized school "Aidemy" to study. I would like to share the knowledge gained here with you, and I am summarizing it on Qiita. I am very happy that many people have read the previous summary article. Thank you! This time, I will post an introduction to Flask memo. Nice to meet you.

About Flask

What is Flask

-Flask is a Python web application framework. Similar to Rails in Ruby. -Use Flask as follows.

#Import Flask package
from flask import Flask
#Instantiate Flask class
app=Flask(__name__)
#Define the function when accessing the URL
@app.route('/')
def hello_world():
    return "Hello World"
#Only execute when the code is executed directly.
if __name__=='__main__':
    app.run()

[email protected] ("URL") __ is to execute the function defined after it when the URL is accessed. -The name will be described later.

What is name

-Name is a variable that is automatically defined for each file, and __the file name is stored. __ -In addition, __main is stored when the file is directly executed (when the file is executed by a command, etc.). __ (So, if you set name =='main', it will be the condition when the file is executed directly)

Implementation of handwriting character discrimination application

Code description

@app.route('/')
def hello_world():
    return render_template('index.html')

-When accessing the URL of @ app.route () with __render_template ('HTML file') __, HTML can be reflected. -The HTML file at this time must be put in the templates folder.

Rough flow

#First, list the classes to be classified
classes = ["0","1","2","3","4","5","6","7","8","9","10"]
#Specifying the image size
image_size = 28
#Specify the folder to save the uploaded image and specify the extension to allow uploading
UPLOAD_FOLDER = "uploads"
ALLOWED_EXTENSIONS = set(['png','jpg','jpeg'])

#Instantiation of Flask class
app = Flask(__name__)

#Judgment of extension of uploaded image
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

#Model loading
model = load_model('./model.h5')

-The extension judgments "'.' In filename" and "filename.rsplit ('.', 1) [1] .lower () in ALLOWED_EXTENSIONS" are conditional expressions. The result of the correctness judgment of this is returned by return.

-".' In filename" has a "." In the file name, or "filename.rsplit ('.', 1) [1] .lower () in ALLOWED_EXTENSIONS" has a "." After the file name. Indicates whether it corresponds to any of "ALLOWED_EXTENSIONS". At this time, __ "rsplit" __ means that the character string is separated from the back.

Process the uploaded image file on the HTML side

-On the HTML side, I explained "・ Input form: __ \

\ </ form> __ (upload the image with method =" POST ")", but here, the data entered in the input form is received. See the flow of executing the function.

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':

-If you set \ on the HTML side and then __ "if request.method =='POST'"__ in Flask, it is defined after that for the uploaded file. Functions etc. can be applied.

-Also, if the file is not stored in the received'POST', or if the file name is not attached in the first place, learning by the model is not possible, so in such a case, redirect to the original page.

#What to do if the file does not exist
  if 'file' not in request.files:
            flash('No file')
            return redirect(request.url)
        file = request.files['file']
#Processing when the file name is blank
        if file.filename == '':
            flash('No file')
            return redirect(request.url)

-After that, determine whether the extension is appropriate with the "allowed_file ()" defined earlier, and save it with "file.save".

Load the saved image and apply the model

#Read the received image and convert it to np format
            img = image.load_img(filepath, grayscale=True, target_size=(image_size,image_size))
            img = image.img_to_array(img)
            data = np.array([img])
#Pass the transformed data to the model for prediction
            result = model.predict(data)[0]
            predicted = result.argmax()
            pred_answer = "this is" + classes[predicted] + "is"

-By __image.load_img (URL of image, target_size = (vertical, horizontal)) __, load and resize the image at the same time. grayscale = True means that reading is done in monochrome. -__Image.img_to_array (image) __ makes the image a NumPy array. Furthermore, img is listed by __np.array ([img]) __. -The reason for converting in this way is that only the list of NumPy can be passed to the prediction by the model (model.predict ()).

  return render_template("index.html",answer=pred_answer)

-By setting __render_template ("HTML file", answer = prediction result) __, the prediction result can be passed to {{}} of the HTML file.

Deploy

-Deploying means publishing the created application through Heroku.

Recommended Posts

Flask Primer Memo
Flask basic memo
Flask introduction-Blueprint application memo
flask
flask
Hello World in Flask [Appropriate memo]
gzip memo
Raspberry-pi memo
Pandas memo
HackerRank memo
First Flask
Python memo
python memo
graphene memo
pyenv memo
Matplotlib memo
pytest memo
sed memo
Python memo
Install Memo
BeautifulSoup4 memo
networkx memo
python memo
tomcat memo
command memo
Generator memo.
psycopg2 memo
Python memo
SSH memo
Command memo
Image sending / receiving memo in Python (Flask)
Memo: rtl8812
pandas memo
Shell memo
Python memo
Pycharm memo
Python memo