3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flaskメモ

Last updated at Posted at 2018-06-07

DockerでFlask環境を作成などのメモ。

参考
https://qiita.com/nanakenashi/items/cbe8e8ef878121638514
https://a2c.bitbucket.io/flask/quickstart.html#http

Dockerfile

Dockerfile
# ベースイメージの指定
FROM python:3

# ソースを置くディレクトリを変数として格納                                                  
ARG project_dir=/flask/
ARG gcloud_dir=/gcloud/

# 必要なファイルをローカルからコンテナにコピー
ADD requirements.txt $project_dir
ADD hello.py $project_dir

# requirements.txtに記載されたパッケージをインストール                         
WORKDIR $project_dir
RUN pip install -r requirements.txt

# (コンテナ内で作業する場合)必要なパッケージをインストール
RUN apt-get -y update
RUN apt-get -y install vim git tar wget tmux tig

# gcloudのインストール
WORKDIR $gcloud_dir
RUN wget https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-192.0.0-linux-x86_64.tar.gz?hl=ja
RUN tar -zxvf google-cloud-sdk-192.0.0-linux-x86_64.tar.gz?hl=ja 
WORKDIR $project_dir
requirements.txt
click==6.6
Flask==0.11.1
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
Werkzeug==0.11.10
hello.py
from flask import Flask
app = Flask(__name__)

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

@app.route('/good')
def good():
    name = "Good"
    return name

## server run
if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=5000)

イメージの作成、コンテナの起動

flaskという名称のDockerイメージをビルド。

Dockerイメージ作成
docker build -t flask . 

flaskイメージから、flask_webという名称のコンテナを起動する。

コンテナ起動
docker run -d --name flask_web -p 5000:5000 -v `pwd`:/flask flask python hello.py

flaskメモ

外部ネットワークからのアクセス

runメソッドの中で以下指定する。

runメソッド
app.run(host='0.0.0.0')

デバッグモード

コード修正した際に自動でリロードしてくれるらしい。
runメソッドの中で以下指定する。

runメソッド
app.run(debug=True)

mongodb→pandasの中身表示

runメソッド
import pandas as pd
from pymongo import MongoClient

@app.route('/')
def 関数():
    client = MongoClient('host', port)
    collection = client.データベース.コレクション

    mongo = collection.find({条件})

    df = pd.DataFrame(list(mongo))

    return df.to_html(classes='test')
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?