4
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.

DockerでFlask開発環境構築

Posted at

使うもの

  • macOS High Sierra
  • Docker
  • VSCode
  • brew

VSCodeの設定

まずはVSCodeにPythonの拡張機能をインストールします。

すると以下の警告が出ています。
スクリーンショット 2019-08-18 12.27.51.png

macに入っているデフォルトのPython2は推奨されないみたいなので、python3をインストールします。
brew install python3

「Select Python Interpreter」を押してPython3を設定。

あとは以下の警告も消すために「install」を押してpipもインストールしておきます。

スクリーンショット 2019-08-18 12.37.53.png

pip3 --versionでバージョン情報が出てばインストール完了。

VSCodeの設定はここで完了。

Dockerの設定

ディレクトリ構成はこんな感じ

root
├── Dockerfile
├── docker-compose.yml
└── main.py

それぞれのファイルは以下の通り

Dockerfile
FROM python:3.7

WORKDIR /app

RUN pip install flask
RUN pip install xmltodict

CMD [ "python", "main.py" ]
docker-compose.yml
version: '3'
services:
  api:
    build: .
    ports:
      - 80:8080
    volumes:
      - ./main.py:/app/main.py
    tty: true
main.py
from flask import Flask, jsonify, request
import json
import urllib.request
import xmltodict

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

@app.route("/", methods=['GET'])
def index():
    # パラメーター取得
    keyword = request.args.get('keyword')
    # API通信
    req = "https://news.google.com/rss/search?q=" + urllib.parse.quote_plus(keyword, encoding='utf-8') + "&hl=ja&gl=JP&ceid=JP:ja"
    # 結果取得
    with urllib.request.urlopen(req) as res:
        body = res.read()
    # XML → 辞書に変換
    dict = xmltodict.parse(body)
    # 辞書 → JSONに変換
    data = json.dumps(dict, indent=4, ensure_ascii=False)
    # 結果返却
    return data

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080)

keywordパラメータで受け取った文字列でGoogleNewsのRSS取得してJSON形式で返すだけのAPIです。

動作確認

docker-compose up -dでコンテナ起動

あとはこんな感じでAPI叩いて結果返ってくれば終わり
http://localhost?keyword=スマホ

以上。サクッとFlask環境構築でした。

4
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
4
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?