2
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 3 years have passed since last update.

multiprocessingを使ってflask起動後に他の処理を立ち上げる

Posted at

きっかけ

flaskを起動しつつ、他の処理をさせたいことがあったので、なんとかならないかなと書いてみました。とりあえず動いたので公開します。長時間の検証はしていません。

動作環境

Python 3.9.1
flask 1.1.2

flask_hogehoge.py
from flask import Flask
from multiprocessing import Process
import datetime
import time

app = Flask(__name__)

@app.route('/')
def index():
        return "Hello World!"

def hogehoge():
    i = 0
    while True:
        print("{}, {}".format(i, datetime.datetime.now()))
        i += 1
        time.sleep(10)

def run(**kwargs):
    app.run(**kwargs)

if __name__ == '__main__':
    server = Process(target = run, kwargs = {'host': '0.0.0.0', 'port': 5001, 'threaded': True})
    server.start()

    hogehoge()

解説

  • def hogehoge()に、flask起動後に処理したい内容を書きます。
  • server = Process(...
    のところは、
    target = app.run, kwargs = {...
    と書いたのですが、app.runにうまく引数が渡せなかったので、
    def run(**kwargs)app.runとし、
    target = run, kwargs = {...としています。
2
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
2
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?