Skip to content

Api exposure callbacks #3347

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

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
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
16 changes: 15 additions & 1 deletion dash/_callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def is_no_update(obj):
GLOBAL_CALLBACK_LIST = []
GLOBAL_CALLBACK_MAP = {}
GLOBAL_INLINE_SCRIPTS = []
GLOBAL_API_PATHS = {}


# pylint: disable=too-many-locals
Expand All @@ -87,6 +88,7 @@ def callback(
cache_args_to_ignore: Optional[list] = None,
cache_ignore_triggered=True,
on_error: Optional[Callable[[Exception], Any]] = None,
api_endpoint: Optional[str] = None,
**_kwargs,
) -> Callable[..., Any]:
"""
Expand Down Expand Up @@ -178,6 +180,7 @@ def callback(
)
callback_map = _kwargs.pop("callback_map", GLOBAL_CALLBACK_MAP)
callback_list = _kwargs.pop("callback_list", GLOBAL_CALLBACK_LIST)
callback_api_paths = _kwargs.pop("callback_api_paths", GLOBAL_API_PATHS)

if background:
background_spec: Any = {
Expand Down Expand Up @@ -217,12 +220,14 @@ def callback(
callback_list,
callback_map,
config_prevent_initial_callbacks,
callback_api_paths,
*_args,
**_kwargs,
background=background_spec,
manager=manager,
running=running,
on_error=on_error,
api_endpoint=api_endpoint,
)


Expand Down Expand Up @@ -585,7 +590,12 @@ def _prepare_response(

# pylint: disable=too-many-branches,too-many-statements
def register_callback(
callback_list, callback_map, config_prevent_initial_callbacks, *_args, **_kwargs
callback_list,
callback_map,
config_prevent_initial_callbacks,
callback_api_paths,
*_args,
**_kwargs,
):
(
output,
Expand Down Expand Up @@ -638,6 +648,10 @@ def register_callback(

# pylint: disable=too-many-locals
def wrap_func(func):
if _kwargs.get("api_endpoint"):
api_endpoint = _kwargs.get("api_endpoint")
callback_api_paths[api_endpoint] = func

if background is None:
background_key = None
else:
Expand Down
38 changes: 38 additions & 0 deletions dash/dash.py
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,7 @@ def __init__( # pylint: disable=too-many-statements
self.callback_map = {}
# same deps as a list to catch duplicate outputs, and to send to the front end
self._callback_list = []
self.callback_api_paths = {}

# list of inline scripts
self._inline_scripts = []
Expand Down Expand Up @@ -778,6 +779,41 @@ def _setup_routes(self):
# catch-all for front-end routes, used by dcc.Location
self._add_url("<path:path>", self.index)

def setup_apis(self):
# Copy over global callback data structures assigned with `dash.callback`
for k in list(_callback.GLOBAL_API_PATHS):
if k in self.callback_api_paths:
raise DuplicateCallback(
f"The callback `{k}` provided with `dash.callback` was already "
"assigned with `app.callback`."
)
self.callback_api_paths[k] = _callback.GLOBAL_API_PATHS.pop(k)

def make_parse_body(func):
def _parse_body():
if flask.request.is_json:
data = flask.request.get_json()
return flask.jsonify(func(**data))
return flask.jsonify({})

return _parse_body

def make_parse_body_async(func):
async def _parse_body_async():
if flask.request.is_json:
data = flask.request.get_json()
result = await func(**data)
return flask.jsonify(result)
return flask.jsonify({})

return _parse_body_async

for path, func in self.callback_api_paths.items():
if asyncio.iscoroutinefunction(func):
self._add_url(path, make_parse_body_async(func), ["POST"])
else:
self._add_url(path, make_parse_body(func), ["POST"])

def _setup_plotlyjs(self):
# pylint: disable=import-outside-toplevel
from plotly.offline import get_plotlyjs_version
Expand Down Expand Up @@ -1346,6 +1382,7 @@ def callback(self, *_args, **_kwargs) -> Callable[..., Any]:
config_prevent_initial_callbacks=self.config.prevent_initial_callbacks,
callback_list=self._callback_list,
callback_map=self.callback_map,
callback_api_paths=self.callback_api_paths,
**_kwargs,
)

Expand Down Expand Up @@ -1496,6 +1533,7 @@ def dispatch(self):
def _setup_server(self):
if self._got_first_request["setup_server"]:
return

self._got_first_request["setup_server"] = True

# Apply _force_eager_loading overrides from modules
Expand Down
Loading