10

我有一个请求来自一个用@app.route('/url/path/to/view').

它做了几件事来查找一些数据并进行一些计算,并且在此期间该函数正常运行。但是,最后我想开始一个新进程(从一个 python 函数,当前使用multiprocessing.Process)。一旦这个进程启动,我希望函数返回,而新进程继续独立运行。

我当前方法的伪代码

def start_process(arguments):
    # some code here that the process will run

p = multiprocessing.Process(target=start_process, args=(...))
p.start()

return app.response("{ 'status': 'ok' }", mimetype='application/json')

这种方法是否可行,Flask 应用程序能否继续运行而不影响新进程?

4

1 回答 1

6

使用多处理启动子进程是完全可以接受的。这是一个使用多处理在后台更新数据库的最小工作示例。正如 Audrius 所说,最终您可能需要一个适当的任务队列

from flask import Flask, jsonify
import multiprocessing
import dataset
import time
import random

app = Flask(__name__)
DATABASE_URL = 'sqlite:///dev.db'

def add_person(name):
    """ Add a person to the db. """
    person = {'name': name, 'age': -1, 'status': 'processing'}
    db = dataset.connect(DATABASE_URL)
    db['people'].insert(person)
    return True

def update_person(name):
    """ Update a person in db with a fake long running process 
    that guesses a random age. """
    time.sleep(10)  # simulate a long running process
    age = random.randint(1, 120)
    person = {'name': name, 'age': age, 'status': 'finished'}
    db = dataset.connect(DATABASE_URL)
    db['people'].update(person, ['name'])
    return True

def get_person(name):
    """ Retrieve a person from the db. """
    db = dataset.connect(DATABASE_URL)
    person = db['people'].find_one(name=name)
    return person

@app.route('/<name>')
def index(name):
    """ Get person. If name not found, add_person to db and start update_person. """
    if not get_person(name):
        add_person(name)
        thread = multiprocessing.Process(target=update_person, args=(name,))
        thread.start()
    person = get_person(name)
    return jsonify(person)

if __name__ == '__main__':
    app.run(debug=True)

localhost:5000/bert在子进程运行时访问:

{
    "status": "processing",
    "age": -1,
    "name": "bert",
    "id": 1
}

等待,然后刷新,您会看到子进程已完成:

{
    "status": "finished",
    "age": 28,
    "name": "bert",
    "id": 1
}
于 2017-03-27T03:50:45.237 回答