Python

Summarize how to use Flask as a reminder

First, this article is written by a Japanese man who is studying English now, so I think it may use incorrect English grammar and phrases. I would appreciate your kind understanding.

I recently created an automatic article generation program using Flask. However, even though it is called automatic article generation, I just let it create articles using the Gemini API. So it’s not a big deal. But just in case, I’ll put a link to the source code uploaded on github.

nominal auto article generation

Back on topic, here is a summary of how to use Flask.

Work Step

The first four steps in developing a web application with Flask are as follows.

4 steps
  1. Creating a working directory
  2. Create a virtual environment using venv, the standard Python library
  3. Installing Flask
  4. First of all, Output “Hello world”

①Creating a working directory

First, create a working directory. The directory name can be anything.

mkdir newFlaskProject

Next, move the creating directory.

cd newFlaskProject

②Create a virtual environment using venv

Execute the following command.

python -m venv env

Next, activate the virtual environment.

source env/Scripts/activate

③Installing Flask

Do the following.

pip install Flask

④First of all, Output “Hello world”

That’s final step. First, you need to make main.py.

touch main.py

Write the following code in main.py.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    name = "Hello World"
    return name

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

When you have completed this step, execute the following command and access to 127.0.0.1:5000.

python main.py

▽Access this link.
http://127.0.0.1:5000/

If it looks like this, it’s ok.

If you want to return html file, write the following code in main.py.

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello():
    name = "Hello World from hello.html"
    return render_template('hello.html', name=name)

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

Next, create new directory that named “templates” and move to “templates”. The directory name must absolutely be “templates”.

mkdir templates
cd templates

And create new html files that named layout.html and hello.html. layout.html is common template. hello.html is top page content.

touch layout.html
touch hello.html

First, write the following code in layout.html.

<!doctype html>
<html>
<head>
<title>New Flask App</title>
</head>
<body>
{% block content %}
<!-- write your main content here -->
{% endblock %}
</body>
</html>

Next, write the following code in hello.html.

{% extends "layout.html" %}
{% block content %}
{{ name }}
{% endblock %}

Then, go to the working directory created in ① and run “python main.py”.

cd ..
python main.py

▽Access this link.
http://127.0.0.1:5000/

If it looks like this, it’s ok.