Flask中线程重复启动以及跨域问题的解决

做了一个项目,项目中使用了cafee 的两个预训练模型识别物体,以及使用了keras的四个模型(因为keras的模型识别耗时长,只启用了2个)。并能显示出图片以及每种模型识别的信息。为了能够在浏览器中循环加载新的图片,就使用了Flask完成了一个http服务器。

在运行期间,发现此识别线程重复启动。一张图片被这四个模型识别了2次。

以及跨域问题,跨域问题。对比了集中解决方法,使用下面这两行解决

from flask_cors import CORS
CORS(app, supports_credentials=True)


错误日志摘要如下:

from ._conv import register_converters as _register_converters

Using TensorFlow backend.
init first
init second
init third
threading starting.
threading started.
 * Restarting with stat
[INFO] loading model...
第1个信息的处理结果:....
第15个信息的处理结果:....
7547549568117}, {"name": "ballplayer", "pred": 0.061236153123900294}]}]}
init first
init second
init third
threading starting.
threading started.
第16个信息的处理结果:...

解决方法:
# will be reloaded
if __name__ == '__main__':  
    app.run(debug=True, host='0.0.0.0', port=8888)     

-->

方法1
# this is work
if __name__ == '__main__':  
    app.run(debug=False, host='0.0.0.0', port=8888)

方法2    
-->    
# this is also work
if __name__ == '__main__':  
    app.run(debug=True, use_reloader=False, host='0.0.0.0', port=8888) 

The duplicate output from your function can be explained by the reloader. The first thing it does is start the main function in a new thread so it can monitor the source files and restart the thread when they change. Disable this with the use_reloader=False option.

If you want to be able to run your function when starting the server from a different module, wrap it in a function, and call that function from the other module:

def run_server(dom):
        _run_on_start("%s" % dom)
        app.run(debug=True, use_reloader=False)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        raise Exception("Must provide domain for application execution.")
    else:
        DOM = sys.argv[1]
        run_server(DOM)

原因:

DEBUG模式下flask开多一个线程来监视项目的变化。

The first thing it does is start the main function in a new thread so it can monitor >the source files and restart the thread when they change.

参考自这篇文章http://stackoverflow.com/questions/9276078/whats-the-right-approach-for-calling-functions-after-a-flask-app-is-run



正确代码如下:

# Usage 在
# python .\classify\slaskserver.py
# http://127.0.0.1:8888/feature/1000
# http://127.0.0.1:8888/hello
# 如何调用其他文件中的方法
# 第一种方法 不定义成类,
# import neee  # 引用同路径的neee.py文件
# neee.process() # 引用neee.py中的process方法
# 第二种方法,定义类
# import classify as Clsfy # 引用同路径的neee.py文件,声明别名Clsfy
# clss = Clsfy.classify()  # 使用neee中的类classify()创建一个对象
# clss.process()  # 调用实例对象的process方法
# 第三种方法,定义类,并在定义类的文件中先创建一个此类的对象
# from classify import clss # 从同路径的neee.py文件,引用其中已经创建好的类classify()的实例clss 
# clss.process()  # 调用实例对象的process方法
 
from flask import Flask 
from flask import send_from_directory
from flask_cors import CORS
from classify import clss
import threading
import json
import os
import signal


# just use this code to enable ctrl+c to kill python 
# vctrl+c关闭多线程python程序
# t.setDaemon(True)
def kill(a, b): 
    print("kill!")
    os.kill(os.getpid(), signal.SIGINT)


signal.signal(signal.SIGINT, kill)

app = Flask(__name__) 
# 解决跨域问题
CORS(app, supports_credentials=True) 


t1 = threading.Thread(target=clss.process, args=())
print('threading starting.')
t1.setDaemon(True) 
t1.start()
print('threading started.')


@app.route('/status')  
def status():  
    return 'Working'  


@app.route('/')
def index():
    root_dir = os.getcwd()
    return send_from_directory(os.path.join(root_dir, 'classify'), 'client.html')


@app.route('/hello')  
def hello_world():  
    return 'Hello world 20180327!'  


# http://127.0.0.1:5000/feature/1000 
@app.route('/feature/<string:count>', methods=['GET'])   
def hello_world1(count): 
    return json.dumps(clss.getlast(int(count)))  
    # return count


# port = 5000
if __name__ == '__main__':  
    app.run(debug=True, use_reloader=False, host='0.0.0.0', port=8888) 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值