1
0

More than 1 year has passed since last update.

ThreadでFlaskを起動する

Last updated at Posted at 2022-03-11

やりたい事

  • WebUI用のFlaskとAPI用のFlaskを一つのアプリケーション内で実現したい。
  • プロセスを2つ立ち上げる方法もあるが、サブとなるAPI用をThreadで起動したい。
$ curl localhost:5001/
This is WebUI
$ curl localhost:5002/api/
This is api

ファイル構成

+ app.py
└ api
   └ views.py

コード

app.py
import threading
from flask import Flask


class APIThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True

    def run(self):
        api_app = Flask(__name__)
        from api.views import api
        api_app.register_blueprint(api, url_prefix="/api")
        api_app.run(use_reloader=False, threaded=True, port=5002)


app = Flask(__name__)


@app.route('/')
def index():
    return "This is WebUI"


def main():
    thread = APIThread()
    thread.start()
    app.run(port=5001)


if __name__ == '__main__':
    main()
api/views.py
from flask import Blueprint

api = Blueprint("api", __name__)


@api.route('/')
def index():
    return "This is api"

https://ai-can-fly.hateblo.jp/entry/flask-directory-structure
https://www.subarunari.com/entry/2018/03/10/%E3%81%84%E3%81%BE%E3%81%95%E3%82%89%E3%81%AA%E3%81%8C%E3%82%89_Flask_%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6%E3%81%BE%E3%81%A8%E3%82%81%E3%82%8B_%E3%80%9CDebugger%E3%80%9C
https://news.mynavi.jp/techplus/article/python-33/
https://stackoverflow.com/questions/40460846/using-flask-inside-class
https://qiita.com/yaaamaaaguuu/items/486968e3b566f8340a9e

1
0
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
0