多个进程启动flask服务

2023-05-16

需求:

  在不同的进程中分别启动flask服务,或将其部署到不同的端口号上。

# 导入flask类
import flask
import multiprocessing as mp
import time

# 创建Flask实例,接收参数__name__表示当前文件名,默认会自动指定静态文件static
app1 = flask.Flask(__name__)
app2 = flask.Flask(__name__)
app3 = flask.Flask(__name__)

# app1
@app1.route('/',methods=['POST', 'GET'])
def hello_word1():
    time.sleep(1)
    return '<h1>Hello World!</h1>'

# app2
@app2.route('/',methods=['POST', 'GET'])
def hello_word2():
    return '<h1>Hello Fancp!</h1>'

# app3
@app3.route('/',methods=['POST', 'GET'])
def hello_word3():
    return '<h1>Hello nihao!</h1>'


def startServer1(inDebug, port1): 
    print("Starting Main Mock Server1") 
    app1.run(debug=inDebug, port=port1) 


def startServer2(inDebug, port2): 
    print("Starting Main Mock Server2")
    app2.run(debug=inDebug, port=port2) 

#参考链接:http://cn.voidcc.com/question/p-npbaicvr-bdp.html
if __name__ == '__main__': 
    p = mp.Process(target=startServer1, args=(False, 8082)) 
    p.deamon = True 
    p.start() 
    p1 = mp.Process(target=startServer2, args=(False, 8083)) 
    p1.deamon = True 
    p1.start() 
    p.join() 
    p1.join()

输出结果:

Starting Main Mock Server1
Starting Main Mock Server2
 * Serving Flask app "__mp_main__" (lazy loading)
 * Serving Flask app "__mp_main__" (lazy loading)
 * Environment: production
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.   WARNING: This is a development server. Do not use it in a production deployment.

   Use a production WSGI server instead.   Use a production WSGI server instead.
 * Debug mode: off

 * Debug mode: off
 * Running on http://127.0.0.1:8082/ (Press CTRL+C to quit)
 * Running on http://127.0.0.1:8083/ (Press CTRL+C to quit)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

多个进程启动flask服务 的相关文章

随机推荐