Flask全部

2021/07/08に公開

Mac前提

インストール

python3 -m pip install flask

最初のアプリ

コード(app.py)

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'hello'

app.run('0.0.0.0', port=5000, debug=True)

実行

python3 app.py

ブラウザーで http://localhost:5000 を開く

パスパラメータを渡す

コード(app.py)

from flask import Flask

app = Flask(__name__)

@app.route('/<msg>')
def hello(msg):
    return msg

app.run('0.0.0.0', port=5000, debug=True)

実行

python3 app.py

ブラウザーで http://localhost:5000/hey を開く

テンプレート

テンプレートファイル(templates/hello.html

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf8">
        <title>hello world</title>
    </head>
    <body>
        <h1>hello</h1>
    </body>
</html>

コード(app.py

from flask import Flask, render_template

app = Flask(__name__)

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

app.run('0.0.0.0', port=5000, debug=True)

実行

python3 app.py

ブラウザーで http://localhost:5000 を開く

テンプレートに値を渡す

テンプレート(templates/hello.html

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf8">
        <title>hello world</title>
    </head>
    <body>
        <h1>{{ msg }}</h1>
    </body>
</html>

コード(app.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello():
    return render_template('hello.html', msg='hi')

app.run('0.0.0.0', port=5000, debug=True)

実行

python3 app.py

ブラウザーで http://localhost:5000 を開く

フォームの値を受け取る

コード(app.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/form', methods=['GET'])
def getForm():
    return render_template('form.html')

@app.route('/form', methods=['POST'])
def postForm():
    msg = request.form['msg']
    return msg

app.run('0.0.0.0', port=5000, debug=True)

フォーム(form.html

<form action="http://localhost:5000/form" method="POST">
    msg: <input type="text" name="msg">
    <button type="submit">送信</button>
</form>

実行

python3 app.py

ブラウザーで http://localhost:5000/form を開く
フォームからmsgに値を入れてボタンをクリック

テンプレートでのif

コード(app.py

from flask import Flask

app = Flask(__name__)

@app.route('/<msg>')
def hello(msg):
    return render_template('if.html', msg=msg)
    
app.run('0.0.0.0', port=5000, debug=True)

テンプレート(templates/if.html

<body>
{% if msg=='hello' %}
    <h1>Hello</h1>
{% else %}
    <h1>Good Bye!</h1>
{% endif %}
</body>

実行

python3 app.py

ブラウザーで http://localhost:5000/hello を開く
パラメータを変えてみる

テンプレートでのfor

コード(app.py

from flask import Flask

app = Flask(__name__)

@app.route('/<msg>')
def hello(msg):
    return render_template('for.html')
    
app.run('0.0.0.0', port=5000, debug=True)

テンプレート(templates/for.html

<body>
    {% for i in range(5) %}
        <h1>{{ i }}</h1>
    {% endfor %}
</body>

ブラウザーで http://localhost:5000

データベース接続

MongoDBを使う

MongoDB

インストール

brew install mongodb-community

起動

brew services start mongodb-community

PyMongo

インストール

python3 -m pip install pymongo

コード

from flask import Flask, request, render_template
from pymongo import MongoClient
from bson.json_util import dumps

app = Flask(__name__)
mongo = MongoClient('mongodb://{username}:{password}@{server}:{port}/{database}')
db = mongo['db_name']

@app.route('/users', methods=['GET'])
def getUsers():
    users = db.users.find()
    #return dumps(users), 200
    return render_template('users.html', users=users)

@app.route('/users', methods=['POST'])
def createUser():
    user = {}
    user['id'] = request.form['id']
    user['name'] = request.form['name']
    db.users.insert_one(user)
    return 'created', 200

@app.route('/users/<id>', methods=['GET'])
def getUser(id):
    user = db.users.find_one({'id':id})
    return dumps(user), 200

@app.route('/users/<id>', methods=['PUT'])
def updateUser(id):
    user = {}
    user['name'] = request.form['name']
    db.users.update_one({'id':id}, {'$set':{'name':user['name']}})
    return 'updated', 200

@app.route('/users/<id>', methods=['DELETE'])
def deleteUser(id):
    db.users.delete_one({'id':id})
    return 'deleted', 200

app.run('0.0.0.0', port=5000, debug=True)

テンプレート(users.html

<html>
    <body>
        <ul>
            {% for user in users %}
            <li> {{ user.userid }} - {{ user.name }}</li>
            {% endfor %}
        </ul>
    </body>
</html>

起動

python3 app.py

ブラウザーで http://localhost:5000/hello/taro を開く

Discussion