Skip to content

Replace deprecated flask shutdown with thread kill. #1963

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@
All notable changes to `dash` will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/).

## [Unreleased]

### Fixed

- [#1963](https://github.com/plotly/dash/pull/1963) Fix [#1780](https://github.com/plotly/dash/issues/1780) flask shutdown deprecation warning when running dashduo threaded tests.

## [2.3.0] - 2022-03-13

### Added
Expand Down
46 changes: 30 additions & 16 deletions dash/testing/application_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
import subprocess
import logging
import inspect
import ctypes

import runpy
import flask
import requests

from dash.testing.errors import NoAppFoundError, TestingTimeoutError, ServerCloseError
Expand Down Expand Up @@ -102,6 +102,26 @@ def tmp_app_path(self):
return self._tmp_app_path


class StoppableThread(threading.Thread):
def get_id(self): # pylint: disable=R1710
if hasattr(self, "_thread_id"):
return self._thread_id
for thread_id, thread in threading._active.items(): # pylint: disable=W0212
if thread is self:
return thread_id

def kill(self):
thread_id = self.get_id()
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(thread_id), ctypes.py_object(SystemExit)
)
if res == 0:
raise ValueError(f"Invalid thread id: {thread_id}")
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id), None)
raise SystemExit("Stopping thread failure")


class ThreadedRunner(BaseDashRunner):
"""Runs a dash application in a thread.

Expand All @@ -110,25 +130,14 @@ class ThreadedRunner(BaseDashRunner):

def __init__(self, keep_open=False, stop_timeout=3):
super().__init__(keep_open=keep_open, stop_timeout=stop_timeout)
self.stop_route = "/_stop-{}".format(uuid.uuid4().hex)
self.thread = None

@staticmethod
def _stop_server():
# https://werkzeug.palletsprojects.com/en/0.15.x/serving/#shutting-down-the-server
stopper = flask.request.environ.get("werkzeug.server.shutdown")
if stopper is None:
raise RuntimeError("Not running with the Werkzeug Server")
stopper()
return "Flask server is shutting down"

# pylint: disable=arguments-differ
def start(self, app, **kwargs):
"""Start the app server in threading flavor."""
app.server.add_url_rule(self.stop_route, self.stop_route, self._stop_server)

def _handle_error():
self._stop_server()
self.stop()

app.server.errorhandler(500)(_handle_error)

Expand All @@ -139,9 +148,13 @@ def run():
kwargs["port"] = self.port
else:
self.port = kwargs["port"]
app.run_server(threaded=True, **kwargs)

self.thread = threading.Thread(target=run)
try:
app.run_server(threaded=True, **kwargs)
except SystemExit:
logger.info("Server stopped")

self.thread = StoppableThread(target=run)
self.thread.daemon = True
try:
self.thread.start()
Expand All @@ -155,7 +168,8 @@ def run():
wait.until(lambda: self.accessible(self.url), timeout=1)

def stop(self):
requests.get("{}{}".format(self.url, self.stop_route))
self.thread.kill()
self.thread.join()
wait.until_not(self.thread.is_alive, self.stop_timeout)


Expand Down