flask 后台程序执行方法

由于flask后台多线程、多进程都是假的,所以想异步操作必须多一些代码内容。解决方法主要是2种:


一、使用Celery (http://www.celeryproject.org/),或者RQ (http://python-rq.org/).实现异步分布式后台操作。


二、简单的使用python代码了:


# -*- coding: utf8 -*-
from flask import Flask
from time import sleep
from concurrent.futures import ThreadPoolExecutor

# DOCS https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor
executor = ThreadPoolExecutor(1)

app = Flask(__name__)


@app.route('/jobs')
def run_jobs():
    executor.submit(some_long_task1)
    executor.submit(some_long_task2, 'hello', 123)
    return 'Two jobs was launched in background!'


def some_long_task1():
    print("Task #1 started!")
    sleep(10)
    print("Task #1 is done!")

def some_long_task2(arg1, arg2):
    print("Task #2 started with args: %s %s!" % (arg1, arg2))
    sleep(5)
    print("Task #2 is done!")


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


    app.run("0.0.0.0", 888, debug=True)



你可能感兴趣的:(python)