Let's make an A to B conversion web application with Flask! From scratch ...

At first

An article that struggled to understand Flask. I would be very happy if you could comment if you have any advice such as that it is wrong here and that it should be interpreted like this. Here is the finished product. https://neutrino-converter.herokuapp.com/ OK, let's get started.

Overview

--Create a **-type web application that converts ** character strings in the form of A to B ――When working with NEUTRINO, it is troublesome to put spaces in the characters, so use this to eliminate the troublesomeness.

127.0.0.1_5000_.png

Part 1 "Prepare Flask"

The language I use is Python because I can only use it. I use a module called Flask, but this is actually my first experience. Let's explain step by step from 1.

Install Flask with pip

I used pipenv for this development, but this article will be explained with pip. Execute the following command to install Flask.

pip install Flask

Prepare the directory

--Create ʻapp, modelsfolders in theproject directory. --__ init__.pyin themodelsfolder --Createtemplates, static folders in the ʻapp folder. --Create ʻapp.py in the ʻapp folder. --Create run.py in the project directory.

I think this is what you notice.

project
 ├app/
 │ ├templates/
 │ ├static/
 │ └app.py
 ├models/
 │ └__init__.py
 └run.py

Prepare html

Prepare ʻindex.html in the ʻapp / templates folder. The contents are like this. This is the moto of the ** output page. ** **

index.html


<!DOCTYPE html>
<html>
    <head>
        <title>Character conversion for Musescore pouring</title>
    </head>
    <body>
        <h1>Here is index.It's html!</h1>
    </body>
</html>

Prepare a Python file

I will assemble the contents of the ~ .py that I made earlier.

run.py

Executed when starting the server. Simply call the app and run it.

run.py


from app.app import app

if __name__ == "__main__":
    app.run()

app.py

This is the core of a web application. Let's display Hello World. for the time being.

app.py


from flask import Flask, render_template, request

#Creating a Flask object
app = Flask(__name__)

@app.route('/')
def index():
    #Simply display the string
    return 'hello world.'


# 〜/If index is accessed, index.Draw html
@app.route('/index')
def post():
    return render_template('index.html')

I will explain the contents later. Now you're ready to go.

Part 2 "Let's do it for the time being"

The minimum configuration is complete. Let's start the server once with this configuration. The way to start it is to execute ** run.py in an environment where ** flask can be executed.

python run.py

When you execute it, various characters will appear in the terminal, but this is the point to watch.

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

When you open the displayed URL, you should see a screen like this.

スクリーンショット 2020-11-03 2.04.56.png

Let's compare this screen with the Python code.

app.py


@app.route('/')
def index():
    return 'Hello World'

The meaning of this code is as follows. --The function is called when you access /, that is, http://127.0.0.1:5000/. --The function simply returns the string Hello World. --The return value of this function, Hello World, is reflected on the page.

I feel like, did you understand somehow?

Certainly, you also entered such a code.

app.py


# 〜/If index is accessed, index.Draw html
@app.route('/index')
def post():
    return render_template('index.html')

The meaning of this code is as follows. --The function is called when you access / index, that is, http://127.0.0.1:5000/index. --The function returns render_template ('index.html'). --render… Draw --template… Template --In other words, render_template ('index.html') means ** to describe ʻindex.htmlas a template **. -That is, when you accesshttp://127.0.0.1:5000/index, ʻindex.html is displayed.

It's like that. I think I've come to understand how it works. Somehow it's okay, because I don't know the detailed meaning ...

Part 3 "Let's make a page"

review

This page is what I want to make this time.

127.0.0.1_5000_.png

Let's build the necessary elements for this page.

Build index.html

The html I was touching earlier was normal html, but from here I will write a slightly different html.

index.html


<!DOCTYPE html>
<html>
<head>
    <title>Character conversion for Musescore pouring</title>
</head>
<body>
    <!-- form -->
    <form action="/" method="POST">
        <textarea name="before" rows="4" cols="40">Put the text here</textarea>
        <input type="submit" value="conversion">
        {% if body %}
        <textarea name="after" rows="4">{{body}}</textarea>
        {% else %}
        <textarea name="after" rows="4">If you press the button, it will be output here</textarea>
        {% endif %}
    </form>
    <!-- form -->
</body>
</html>

Some characters are unfamiliar, so let's explain them step by step.

--html between {% if A%} and {% endif%} will not be displayed unless condition A is met.

I'm not sure how to write this, but if you are familiar with web applications, please explain ... --When you receive an element called body from Flask, it will be inserted into{{body}}.

If you've ever scratched the programming, you'll feel familiar with it. Now, let's pay attention to the following points.

When it receives an element called body from Flask, it is inserted into{{body}}.

What does this look like? Here is ʻapp.py that actually passes the element body` from the Flask side.

app.py


@app.route('/', methods=['post'])
def post():
    body = 'hoge'
    return render_template('index.html', body=body)

It's a simple story, just prepare body as the argument of the return value. Conversely, when passing an element from the html side to the Flask side:

index.html


<form action="/" method="POST">
    <textarea name="before" rows="4" cols="40">Put the text here</textarea>
    <input type="submit" value="conversion">
</form>

app.py


body = request.form['before']

--Create a POST form and specify the page where the action will occur when this form is executed with ʻaction. --Set textarea to name = "before" . --Set type =" submit " to ʻinput. --If you press the button in this state, the page will be displayed in the form of ** Obtaining the element specified on the Flask side from html **.

In other words

This is スクリーンショット 2020-11-03 2.35.53.png

It will be like this スクリーンショット 2020-11-03 2.36.48.png

... Oh, the procedure is skipped. Let's follow the quick steps.

Part 4 "Creating a mechanism to convert character strings"

That's right, how I converted the string is skipped.

Put your own modules in the models folder

If you want to use your own modules in Flask, put them together in the models folder. The contents of the folder should look like this.

models/
 ├__init__.py
 └convert.py

By putting __init__.py, you can import from models.

Reference: Summary of how to import files in Python 3 -Qiita

Now let's play with convert.py.

Convert a string with a regular expression

This time I will attack with regular expressions. I wanted to put them together in a function, but honestly, it didn't seem to save the number of lines, so I put them together.

When I explain the procedure, it looks like this.

--Search for a string with (.), And place a space behind it with \ 1 without making any changes to the string.

I think there is a smarter way to do this, but please let me know. --Search for two or more consecutive spaces with \ s {2,} and remove the extra spaces.

convert.py


import re

def convert(arg: str):
    pattern_before = r'(.)'
    pattern_after = r'\1 '
    s = arg
    s = re.sub(pattern_before, pattern_after, s)

    pattern_before = r'\s(Ya|Shu|Yo|Ah|I|U|Eh|Mm|YA|Yu|Yo|A|I|U|E|Oh)'
    pattern_after = r'\1'
    s = re.sub(pattern_before, pattern_after, s)

    pattern_before = r'\s{2,}'
    pattern_after = r' '
    s = re.sub(pattern_before, pattern_after, s)

    return s

Call convert.py with app.py

Now let's call convert.py from ʻapp.py` and use it.

app.py


from models import convert

@app.route('/', methods=['post'])
def post():
    body = request.form['before']
    body = convert.convert(body)
    return render_template('index.html', body=body)

--Import convert with from models import convert. --Get the before element when you press the button on the form --Execute the convert function for before. --Depict the converted string body

It's like that.

In other words, this is finally

This is スクリーンショット 2020-11-03 2.35.53.png

Will be like this スクリーンショット 2020-11-03 2.36.48.png

I was able to explain it properly.

Part 5 "Once the function is completed, the next appearance"

It looks a little ugly as it is, so use bootstrap to adjust the appearance.

There is a folder called static in the ʻapp` folder. CSS, JS, etc. are put in here. This time, we will use only CSS, so we will not prepare a JS folder.

app/
 └static/
   └css
     └bootstrap.min.css

Let's go with the configuration. You're messing with bootstrap ... ʻindex.html`, right?

index.html


<!DOCTYPE html>
<html>

<head>
    <title>Character conversion for Musescore pouring</title>
    <link href="../static/css/bootstrap.min.css" rel="stylesheet">

</head>

<body>
    <div class="jumbotron text-center">
        <h1 class="display-4">Lyrics -> Musescore</h1>
        <p class="lead">for NEUTRINO</p>
        <hr class="my-4">
        <p>It is a guy who automatically adds a space to the lyrics to be poured when preparing Musescore for NEUTRINO.</p>
        <p>Aiue Okyakyukyo → Aiue Okyakyukyo</p>
    </div>

    <!-- form -->
    <form action="/" method="POST">
        <div class="container-fluid">
            <div class="row justify-content-around form-group">
                <textarea class="col-11 col-md-4 form-control" name="before" rows="4" cols="40">Put the text here</textarea>
                <div class="col-md-1 my-md-auto">
                    <input type="submit" class="btn btn-primary btn-lg" value="conversion">
                </div>
                {% if body %}
                <textarea class="col-11 col-md-4 form-control" name="after" rows="4">{{body}}</textarea>
                {% else %}
                <textarea class="col-11 col-md-4 form-control" name="after" rows="4">If you press the button, it will be output here</textarea>
                {% endif %}
            </div>
        </div>
    </form>o

    <!-- form -->
    <footer class="text-muted ">
        <div class="container">
            <p class="text-center">
Contact us here:<a href="https://twitter.com/_Sotono">@_Sotono</a>
            </p>
        </div>
    </footer>


</body>

</html>

Now it looks like this.

127.0.0.1_5000_.png

It was a long journey ... After that, you can handle it freely by publishing it, boiling it, or baking it.

Extra edition "Clogged place and solution"

--Q. I'm running ʻapp.py in the test, but it says No module named app"and it doesn't work ... --A. Runrun.py`, it will solve everything.

――Q. I'm spitting out a long error that I don't understand ... jinja2.exceptions.TemplateNotFound is written at the end ... --A. ʻindex.html and ʻapp.py may not mesh well, let's check the code properly. Are you calling an element that does not exist?

in conclusion

It became a long sentence. I made this this time because when I was composing as a hobby, I thought, "Amendokuse !!!". I think NEUTRINO is an amazing technology, so I look forward to future developments. end.

Recommended Posts

Let's make an A to B conversion web application with Flask! From scratch ...
Let's make a WEB application for phone book with flask Part 1
Let's make a WEB application for phone book with flask Part 2
Let's make a WEB application for phone book with flask Part 3
Let's make a WEB application for phone book with flask Part 4
Let's make a web framework with Python! (1)
Let's make a web framework with Python! (2)
I want to make a web application using React and Python flask
[ES Lab] I tried to develop a WEB application with Python and Flask ②
WEB scraping with python and try to make a word cloud from reviews
I tried to make an OCR application with PySimpleGUI
Web application development with Flask
Beginners try to make an online battle Othello web application with Django + React + Bootstrap (1)
Web application with Python + Flask ② ③
[Learning memo] How to make an application with Django ~ From virtual environment to pushing to github ~
Web application with Python + Flask ④
How to deploy a web app made with Flask to Heroku
How to make a Cisco Webex Teams BOT with Flask
How to convert an array to a dictionary with Python [Application]
Creating a web application using Flask ②
Let's make a GUI with python.
Let's make a breakout with wxPython
Build a web application with Django
Creating a web application using Flask ①
Make Flask a Cloud Native application
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
Creating a web application using Flask ③
Creating a web application using Flask ④
If you know Python, you can make a web application with Django
Build a Flask / Bottle-like web application on AWS Lambda with Chalice
Re: Life in Heroku starting from scratch with Flask ~ PhantomJS to Heroku ~
Try to extract a character string from an image with Python3
Try to make a web service-like guy with 3D markup language
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
Let's make a web chat using WebSocket with AWS serverless (Python)!
Let's make a shiritori game with Python
How to make an artificial intelligence LINE bot with Flask + LINE Messaging API
Python beginners decided to make a LINE bot with Flask (Flask rough commentary)
Make a rare gacha simulator with Flask
I came up with a way to make a 3D model from a photo.
Let's make a voice slowly with Python
Let's make a simple language with PLY 1
[Python] A quick web application with Bottle!
Create a simple web app with flask
[GCP] Procedure for creating a web application with Cloud Functions (Python + Flask)
[Streamlit] I hate JavaScript, so I make a web application only with Python
I tried to make a Web API
Run a Python web application with Docker
Create a web service with Docker + Flask
Let's make a tic-tac-toe AI with Pylearn 2
Let's make a Twitter Bot with Python!
How to build an application from the cloud using the Django web framework
I made a WEB application with Django
Implement a simple application with Python full scratch without using a web framework.
(Note) A web application that uses TensorFlow to infer recommended song names [Create an execution environment with docker-compose]
Let's make a nervous breakdown application with Vue.js and Django-Rest-Framework [Part 3] ~ Implementation of nervous breakdown ~
I tried to make a simple mail sending application with tkinter of Python
Let's make a nervous breakdown application with Vue.js and Django-Rest-Framework [Part 6] ~ User Authentication 2 ~
I tried to extract a line art from an image with Deep Learning