PythonのFlaskでHelloWorld

  • 2020.11.03
  • 2021.01.24
  • Flask
NO IMAGE

FlaskでHelloWorldを出力してみた。

前提条件:
・Mac
・Python3
・pip
の環境があること。

コマンド操作でFlaskをインストールします。

$ pip install Flask

ファイル階層はこんな感じです。

helloworld
  ├── main.py
  └── templates
              └── index.html


フォルダを作成していきましょう。

コマンドで作成出来るよう書いておきます。

$ mkdir helloworld
$ cd helloworld
$ touch main.py
$ mkdir templates
$ touch templates/index.html


main.pyを編集します。

from flask import Flask, render_template
app = Flask(__name__)

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

@app.route('/index', methods = ['GET'])
def index():
    return render_template('index.html')
if __name__ == '__main__':
    app.run(debug=True)

これだけでも実行はできますが、index.htmlからも動かしたいので
templates/index.htmlも編集します。

<h1>Hello World HTML</h1>

準備完了しました。
コマンドからpythonを実行します。

$ python main.py

コマンドに以下のように出ましたら、OKです。

(base) aaaMacBookPro:helloworld aaa$ python main.py
  * Serving Flask app "main" (lazy loading)
  * Environment: production
    WARNING: Do not use the development server in a production environment.
    Use a production WSGI server instead.
  * Debug mode: on
  * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
  * Restarting with stat
  * Debugger is active!
  * Debugger PIN: 123-456-789 

下記URLにアクセスしてみましょう。

http://localhost:5000/
http://localhost:5000/index

Hello World」と「Hello World HTML」が無事表示されたら完成です。

Flaskカテゴリの最新記事