烧瓶多处理

时间:2018-06-24 19:07:27

标签: python flask multiprocessing

我正在尝试开发一个小型应用程序,该应用程序基本上将根据用户提供或请求的数据集绘制一些图形。 process_order函数应同时运行不同的数据集。由于某种原因,我只能得到第一个图,而不能得到第二个和连续图。我用不同的用户打开了一个不同的浏览器会话,结果相同。

示例我试图从IE打开一个浏览器,然后从Chrome打开另一个浏览器,以user1的身份登录并设置了5个输入-在IE中(预期5个图形),以user2的身份登录了20个输入-在Chrome中(预期的20个)图形)我期望2个浏览器窗口中的5个图形来自一个窗口,而20个图形来自第二个窗口:

如果它已经在不同的问题中问过/回答过,我对python和flask的道歉还是陌生的

app = Flask(__name__)
plot = None
my_session = None
session_id = None

@app.route('/')
def home():
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        return render_template('template.html')

@app.route('/login', methods=['POST'])
def do_admin_login():

    if request.form['password'] == 'password' and request.form['username'] in 'admin' :
        session['logged_in'] = True
        my_session = Bot(request.form['username'])
        my_session.session_id = request.form['username']
        session['user'] = request.form['username']
        return render_template('template.html')
    else:
        flash('wrong password!')
    return home()

@app.route("/ask", methods=['POST','GET'])
def ask():

    string = str(request.form['message'])

    res = my_session.process(string)
    return jsonify({'status':'OK','answer':bot_res})


class Bot():
    #Define user level 
    def __init__(self,session_id):
      self.return_string = ""
      self.session_id = session_id

    def process(self, string):
        self.session_id = session['user']
        self.string = string
        self.return_string = self.process_order() #  This method I would like to execute as concurrent at the same time for multiple users/session with different set ot data
        return self.return_string

    def process_order(self):

        self.plot = Plot()
        self.plot.global_url = range(5)
        self.i = 0
        self.inputs = [] #tuples
        self.number = range(5)

        self.url_values = zip(self.number,self.inputs)

        self.pool = Pool()
        self.func = partial(self.plot.do_plot,self.var1)
        self.pool.map(self.func,self.url_values)
        self.pool.close()
        self.pool.join()

        process_confirmation = "Your request is complete"
        return process_confirmation


class Plot():

    def __init__(self):
        pass
    def do_plot(self, var1):

        self.number, self.url = plot_values
        self.var1 = var1

        fig = plt.figure(self.number)
        self.line = str(self.url[1])

        self.res  = urllib.request.urlopen(self.line)
        plt.imshow(plt.imread(self.res))

        self.file_name = "%03d.png"%(self.number,)
        plt.savefig(self.file_name)

        plt.close()

if __name__ == "__main__":
    session_id = None
    app.secret_key = os.urandom(12)
    my_session = Bot(session_id)
    app.run(host='0.0.0.0', port=80)

1 个答案:

答案 0 :(得分:0)

如果您遇到的问题是单个请求需要很长时间,那么您的问题可能出在使用内置的flasks服务器上。

您可以尝试使用gevent部署应用程序: http://flask.pocoo.org/docs/1.0/deploying/wsgi-standalone/#gevent