クッキーもぐもぐ

PC関係とか映画とかゲームとかの

Flaskを使って簡単なWebアプリ作成(環境構築

pythonのプログラムを作成しつつ、それをweb上でサービスとして公開できるようになりたい。

とういことでフレームワークのflaskを導入してみる

導入

ライブラリの確認

$ pip list
Package         Version
--------------- ---------
certifi         2017.4.17
chardet         3.0.4
cycler          0.10.0
idna            2.5
kiwisolver      1.0.1
matplotlib      2.2.2
numpy           1.15.0
pip             18.0
pyparsing       2.2.0
python-dateutil 2.7.3
pytz            2018.5
requests        2.18.2
setuptools      20.10.1
six             1.11.0
urllib3         1.22

flaskは入っていない模様

なので導入

$ pip install flask
Collecting flask
  Downloading https://files.pythonhosted.org/packages/7f/e7/08578774ed4536d3242b14dacb4696386634607af824ea997202cd0edb4b/Flask-1.0.2-py2.py3-none-any.whl (91kB)
Collecting Jinja2>=2.10 (from flask)
  Downloading https://files.pythonhosted.org/packages/7f/ff/ae64bacdfc95f27a016a7bed8e8686763ba4d277a78ca76f32659220a731/Jinja2-2.10-py2.py3-none-any.whl (126kB)
Collecting Werkzeug>=0.14 (from flask)
  Downloading https://files.pythonhosted.org/packages/20/c4/12e3e56473e52375aa29c4764e70d1b8f3efa6682bef8d0aae04fe335243/Werkzeug-0.14.1-py2.py3-none-any.whl (322kB)
Collecting click>=5.1 (from flask)
  Downloading https://files.pythonhosted.org/packages/34/c1/8806f99713ddb993c5366c362b2f908f18269f8d792aff1abfd700775a77/click-6.7-py2.py3-none-any.whl (71kB)
Collecting itsdangerous>=0.24 (from flask)
  Downloading https://files.pythonhosted.org/packages/dc/b4/a60bcdba945c00f6d608d8975131ab3f25b22f2bcfe1dab221165194b2d4/itsdangerous-0.24.tar.gz (46kB)
Collecting MarkupSafe>=0.23 (from Jinja2>=2.10->flask)
  Downloading https://files.pythonhosted.org/packages/4d/de/32d741db316d8fdb7680822dd37001ef7a448255de9699ab4bfcbdf4172b/MarkupSafe-1.0.tar.gz
Installing collected packages: MarkupSafe, Jinja2, Werkzeug, click, itsdangerous, flask
  Running setup.py install for MarkupSafe: started
    Running setup.py install for MarkupSafe: finished with status 'done'
  Running setup.py install for itsdangerous: started
    Running setup.py install for itsdangerous: finished with status 'done'
Successfully installed Jinja2-2.10 MarkupSafe-1.0 Werkzeug-0.14.1 click-6.7 flask-1.0.2 itsdangerous-0.24

ライブラリを確認すると無事入ってる

$ pip list
Package         Version
--------------- ---------
certifi         2017.4.17
chardet         3.0.4
click           6.7
cycler          0.10.0
Flask           1.0.2
idna            2.5
itsdangerous    0.24
Jinja2          2.10
kiwisolver      1.0.1
MarkupSafe      1.0
matplotlib      2.2.2
numpy           1.15.0
pip             18.0
pyparsing       2.2.0
python-dateutil 2.7.3
pytz            2018.5
requests        2.18.2
setuptools      20.10.1
six             1.11.0
urllib3         1.22
Werkzeug        0.14.1

(jinja2というhtmlにpythonの値を組み込めるライブラリも同時に入る!

いや~pipさん便利すぎる

app作成

続いてgithubでアプリを作るためのリポジトリ作成

f:id:christmas-cookies:20180804121117p:plain

これでローカルの方にもクローンを作成

$ git clone git@github.com:cookie777/predict-gacha-app.git
Cloning into 'predict-gacha-app'...
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Receiving objects: 100% (3/3), done.

作ったフォルダにメインのapp,pyを作成する

#app.py
from flask import Flask
app = Flask(__name__)

# http://127.0.0.1:5000をルートとして、("")の中でアクセスポイント指定
# @app.route("hoge")などで指定すると、http://127.0.0.1:5000/hogeでの動作を記述できる。
@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    # webサーバー立ち上げ
    app.debug = True
    #どっから来たアクセスを許可するか。host='0.0.0.0'ならだれでも、デフォルトは127.0.0.1つまり自分のPCからのアクセスのみ。portはその中のさらにどの扉からきたかの指定
    app.run()
    # app.run(host='0.0.0.0', port=80)

これでapp.pyを実行したとき、ローカルサーバーが起動し、ルート/=トップにアクセスしたときdef helloが実行されるのでhello worldが表示される仕組み

試しにapp.py起動

$ python app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

http://127.0.0.1:5000にアクセスする(port5000なのはflaskの仕様

f:id:christmas-cookies:20180804121552p:plain

ちゃんと表示された。やったぜ

html表示

htmlファイルはtemplatesフォルダに作成し、そこに入れる

f:id:christmas-cookies:20180804122858p:plain

f:id:christmas-cookies:20180804122907p:plain

呼び出すときはrender_templateで呼び出す htmlファイルはこんな感じ

<p>ぶうぅうううううううん<p/>
<p>ふぉおおおおおおおおおおおお<p/>

app.pyはrender_templateを読み、returnを変える

#app.py
from flask import Flask, render_template
app = Flask(__name__)

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

結果OK

f:id:christmas-cookies:20180804123054p:plain

何が良いかというとhtmlにpythonからの変数を入れたり、逆にhtmlから受けた変数をpython側に返せるということ

変数受け渡し+layout導入

試しにindex.htmlに変数を渡してみる。ついでにlayout.html(簡単にいうと、メインコンテンツ以外のテンプレ部分)を作成

f:id:christmas-cookies:20180804123442p:plain

app.py

#app.py
from flask import Flask, render_template
app = Flask(__name__)

# http://127.0.0.1:5000をルートとして、("")の中でアクセスポイント指定
# @app.route("hoge")などで指定すると、http://127.0.0.1:5000/hogeでの動作を記述できる。
@app.route("/")
def hello():
    return render_template('index.html',title='test',name='お金')

if __name__ == "__main__":
    # webサーバー立ち上げ
    app.debug = True
    #どっから来たアクセスを許可するか。host='0.0.0.0'ならだれでも、デフォルトは127.0.0.1つまり自分のPCからのアクセスのみ。portはその中のさらにどの扉からきたかの指定
    app.run()
    # app.run(host='0.0.0.0', port=80)

index.html

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

<h3>ぶうううん</h3>
{{ name }}ほしい

{% endblock %}

layout.html

<!doctype html>
<html>
<head>
<title>{{ title }}</title>
<body>
{% block content %}
<!-- ここにメインコンテンツを書く -->
{% endblock %}
</body>
</head>

仕組みとしてはapp立ち上げ→hellow実行→index.html表示+変数test,nameにtest,お金を代入

indext.htmlの表示時に受け取ったtest,nameを使う

index,htmlでは{% block content %} ~ {% endblock %} 以外の部分はlayout.htmlを表示してる

結果

f:id:christmas-cookies:20180804123947p:plain

f:id:christmas-cookies:20180804124002p:plain

ちゃんと変数が渡っていることがわかる

まとめ

flaskを使って環境構築と簡単なhtml表示と変数の受け渡し実行をした

今後はhtmlのpostを使ってpythonに値を渡したい

参考

http://python.zombie-hunting-club.com/entry/2017/11/03/223503 https://www.yoheim.net/blog.php?q=20160505 http://programming-study.com/technology/python-if-main/ https://qiita.com/zaburo/items/5091041a5afb2a7dffc8#%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB