与主应用程序并行运行Flask服务器 [英] Running a Flask server parallel to main app

查看:57
本文介绍了与主应用程序并行运行Flask服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于河内塔楼的简单游戏,目前可在码头上使用.它允许玩家输入自己的回合终端,并向终端输出可视化图像.

I have a simple game about hanoi towers that currently works in terminal. It allows the player to input his turn in terminal and outputs a visualization to terminal.

我的任务是制作一个Flask应用程序,该应用程序将打开一个html页面,其中JS脚本将轮询服务器以获取有关游戏的信息,并使从终端到网页的可视化效果加倍.

My task is to make a flask app that will open an html page where a JS script would poll the server for info about the game and double the visualization from terminal to the web page.

我的问题是游戏和游戏烧瓶都有一个主循环,如果我随后运行它们,它们将无法并行工作.

My problem is that both the game and flask have a main loop and if I run them sequently they won't work parallel.

因此,我需要游戏在终端上运行,而玩家需要在终端上轮流,但是我需要Web服务器来获取游戏状态并显示它.

So I need the game to run in terminal and the player to make turns in terminal, but I need the web server to get the game state and display it.

我的问题:我应该怎么用?多处理线程?

My question: what should I use for this? Threads of multiprocessing?

说我有一个烧瓶视图

from game import game

@app.route('/get_updates')
def get_updates():
   return flask.jsonify(game.instance().board)

如果flask和游戏在单独的线程中运行,它将如何工作?如何从另一个线程获取游戏对象?

How is it gonna work if flask and the game are running in separate threads? How can I get the game object from another thread?

推荐答案

在不同的线程中运行游戏可能会更好吗?

May be its better to run your game in s different thread?

import threading
import time
from flask import Flask, render_template

class myGame(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.board = 1

    def run(self):
        pass


app = Flask(__name__)
game = myGame()

@app.route('/get_updates') 
def get_updates(): 
    return flask.jsonify(game.board)

if __name__ == "__main__":
    game.start()
    app.run(port=81, host='0.0.0.0', debug=False, use_reloader=False)

这篇关于与主应用程序并行运行Flask服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆