Skip to content

Commit 9bb570b

Browse files
committed
adding test and docstring
1 parent 7191e83 commit 9bb570b

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

dash/_callback.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,14 @@ def callback(
167167
Mark all dependencies as not required on the initial layout checks.
168168
:param hidden:
169169
Hide the callback from the devtools callbacks tab.
170+
:param api_endpoint:
171+
If provided, the callback will be available at the given API endpoint.
172+
This allows you to call the callback directly through HTTP requests
173+
instead of through the Dash front-end. The endpoint should be a string
174+
that starts with a forward slash (e.g. `/my_callback`).
175+
The endpoint is relative to the Dash app's base URL.
176+
Note that the endpoint will not appear in the list of registered
177+
callbacks in the Dash devtools.
170178
"""
171179

172180
background_spec = None
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
from dash import (
3+
Dash,
4+
Input,
5+
Output,
6+
html,
7+
ctx,
8+
)
9+
import requests
10+
import json
11+
from flask import jsonify
12+
13+
test_string = ('{"step_0": "Data fetched - 1", "step_1": "Data fetched - 1", "step_2": "Data fetched - 1", '
14+
'"step_3": "Data fetched - 1", "step_4": "Data fetched - 1"}')
15+
16+
def test_apib001_api_callback(dash_duo):
17+
18+
app = Dash(__name__)
19+
app.layout = html.Div([
20+
html.Button("Slow Callback", id="slow-btn"),
21+
html.Div(id="slow-output"),
22+
])
23+
24+
def get_data(n_clicks):
25+
# Simulate an async data fetch
26+
return f"Data fetched - {n_clicks}"
27+
28+
@app.callback(
29+
Output("slow-output", "children"),
30+
Input("slow-btn", "n_clicks"),
31+
prevent_initial_call=True,
32+
api_endpoint='/api/slow_callback', # Example API path for the slow callback
33+
)
34+
def slow_callback(n_clicks):
35+
data = {}
36+
for i in range(5):
37+
data[f'step_{i}'] = get_data(n_clicks)
38+
ret = f"{json.dumps(data)}"
39+
if ctx:
40+
return ret
41+
return jsonify(ret)
42+
43+
app.setup_apis()
44+
45+
dash_duo.start_server(app)
46+
47+
dash_duo.wait_for_element("#slow-btn").click()
48+
dash_duo.wait_for_text_to_equal("#slow-output", test_string)
49+
r = requests.post(dash_duo.server_url +'/api/slow_callback',
50+
json={'n_clicks': 1},
51+
headers={'Content-Type': 'application/json'})
52+
assert r.status_code == 200
53+
assert r.json() == test_string

0 commit comments

Comments
 (0)