LoginSignup
1
1

More than 5 years have passed since last update.

Flask入門1

Posted at

PythonでWeb開発をやってみたいと思ったので、よく名前を聞くFlaskを触ってみました。

インストール

$ pip install Flask

とりあえずHello Worldしてみる

hello_flask.py
# encoding: utf-8
from flask import Flask

app = Flask(__name__)

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

@app.route('/ja')
def hello_world_ja():
    return 'こんにちは 世界!'

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

上記のファイルを保存し、実行する。
ブラウザーを開いて、http://localhost:5000 にアクセスすると、Hello World!と表示されます。

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

ここでルーティングの設定をしています。上のリンクにアクセスするとhello_world()が実行されて「Hello World!」が返ってきます。

HTMLファイルを使ってみる

つぎはHTMLファイルが表示されるようにしてみましょう。
FlaskでHTMLファイルを表示させるコードは以下のようになります。

hello_flask.py
# coding: utf-8
from flask import Flask, render_template
app = Flask(__name__)

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

上記のスクリプトと同じディレクトリにtemplatesというディレクトリを作成し、その中にhtmlファイルを入れます。

templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <h1>Sample Page</h1>
</body>
</html>

再度pythonスクリプトを実行し、ブラウザでhttp://localhost:5000/index にアクセスするとhtmlファイルが表示されます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1