按功能重新加载python flask服务器

moh*_*ium 6 python restart flask server

我正在编写一个python/flask应用程序,并希望添加重新加载服务器的功能.

我目前正在使用以下选项运行服务器

app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

每次代码更改发生时,都会产生以下结果

* Running on http://127.0.0.1:5000/
* Restarting with reloader
Run Code Online (Sandbox Code Playgroud)

但是在生产环境中,我宁愿没有debug=True设置,但只能在需要时重新加载应用程序服务器.

我正在努力让两件事有效:

  1. if reload_needed: reload_server(),和
  2. 如果用户单击管理面板中的"重新加载服务器"按钮,reload_server()则应调用该函数.

然而,尽管服务器在代码更改后重新加载,但我找不到让我这样做的功能.

如果可能的话,我想使用flask/werkzeug内部功能.我知道我可以通过添加诸如gunicorn/nginx/apache之类的东西来实现类似的东西.

小智 6

我想我也遇到过同样的问题。

因此,客户端上有一个 python/flask 应用程序 (XY.py)。我编写了一个构建步骤(Teamcity),它将这个 python 代码部署到客户端。假设 XY.py 已经在客户端上运行。部署这个新的/修复的/更正的 XY.py 后,我必须重新启动它才能对正在运行的代码应用更改。

我遇到的问题是,使用精细重新启动 oneliner 后,os.execl(sys.executable, *([sys.executable]+sys.argv))应用程序使用的端口仍然繁忙/已建立,因此重新启动后我无法访问它。

这就是我解决问题的方法:我让我的应用程序在单独的进程上运行并为其创建一个队列。为了更清楚地看到它,这里有一些代码。

global some_queue = None

@app.route('/restart')
def restart():
   try:
     some_queue.put("something")
     return "Quit"

def start_flaskapp(queue):
   some_queue = queue
   app.run(your_parameters)
Run Code Online (Sandbox Code Playgroud)

将其添加到您的主目录中:

q = Queue()
p = Process(target=start_flaskapp, args=[q,])
p.start()
while True: #wathing queue, sleep if there is no call, otherwise break
   if q.empty(): 
        time.sleep(1)
   else:
      break
p.terminate() #terminate flaskapp and then restart the app on subprocess
args = [sys.executable] + [sys.argv[0]]
subprocess.call(args)
Run Code Online (Sandbox Code Playgroud)

希望它足够干净、简短,对您有帮助!