Skip to content

Commit 936c713

Browse files
Documents auth in the guides, in the view API page, and also types the Blocks.config object (gradio-app#8720)
* auth docs * changes * add changeset * add changeset * add changeset * type * changes * snippets * import * add changeset * changes * fix typing --------- Co-authored-by: gradio-pr-bot <[email protected]>
1 parent 012da05 commit 936c713

16 files changed

+127
-24
lines changed

.changeset/witty-pugs-beg.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@gradio/app": patch
3+
"@gradio/client": patch
4+
"gradio": patch
5+
---
6+
7+
fix:Documents auth in the guides, in the view API page, and also types the Blocks.config object

client/js/src/types.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ export type SpaceStatusCallback = (a: SpaceStatus) => void;
153153
// Configuration and Response Types
154154
// --------------------------------
155155
export interface Config {
156-
auth_required: boolean;
156+
auth_required?: true;
157157
analytics_enabled: boolean;
158158
connect_heartbeat: boolean;
159159
auth_message: string;
@@ -181,6 +181,7 @@ export interface Config {
181181
protocol: "sse_v3" | "sse_v2.1" | "sse_v2" | "sse_v1" | "sse" | "ws";
182182
max_file_size?: number;
183183
theme_hash?: number;
184+
username: string | null;
184185
}
185186

186187
// todo: DRY up types

globals.d.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ declare global {
1616
}
1717

1818
export interface Config {
19-
auth_required: boolean;
19+
auth_required?: true;
2020
auth_message: string;
2121
components: any[];
2222
css: string | null;
@@ -41,4 +41,5 @@ export interface Config {
4141
is_space: boolean;
4242
protocol: "ws" | "sse" | "sse_v1" | "sse_v2" | "sse_v2.1" | "sse_v3";
4343
theme_hash?: number;
44+
username: string | null;
4445
}

gradio/blocks.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
get_render_context,
4848
set_render_context,
4949
)
50-
from gradio.data_classes import FileData, GradioModel, GradioRootModel
50+
from gradio.data_classes import BlocksConfigDict, FileData, GradioModel, GradioRootModel
5151
from gradio.events import (
5252
EventData,
5353
EventListener,
@@ -1024,7 +1024,7 @@ def __init__(
10241024
self.predict = None
10251025
self.input_components = None
10261026
self.output_components = None
1027-
self.__name__ = None
1027+
self.__name__ = None # type: ignore
10281028
self.api_mode = None
10291029

10301030
self.progress_tracking = None
@@ -1082,7 +1082,7 @@ def _is_running_in_reload_thread(self):
10821082
@classmethod
10831083
def from_config(
10841084
cls,
1085-
config: dict,
1085+
config: BlocksConfigDict,
10861086
fns: list[Callable],
10871087
proxy_url: str,
10881088
) -> Blocks:
@@ -1978,8 +1978,8 @@ def create_limiter(self):
19781978
def get_config(self):
19791979
return {"type": "column"}
19801980

1981-
def get_config_file(self):
1982-
config = {
1981+
def get_config_file(self) -> BlocksConfigDict:
1982+
config: BlocksConfigDict = {
19831983
"version": routes.VERSION,
19841984
"mode": self.mode,
19851985
"app_id": self.app_id,
@@ -2015,7 +2015,7 @@ def get_config_file(self):
20152015
"fill_height": self.fill_height,
20162016
"theme_hash": self.theme_hash,
20172017
}
2018-
config.update(self.default_config.get_config())
2018+
config.update(self.default_config.get_config()) # type: ignore
20192019
config["connect_heartbeat"] = utils.connect_heartbeat(
20202020
config, self.blocks.values()
20212021
)

gradio/data_classes.py

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@
88
import shutil
99
from abc import ABC, abstractmethod
1010
from enum import Enum, auto
11-
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, TypedDict, Union
11+
from typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple, TypedDict, Union
1212

1313
from fastapi import Request
1414
from gradio_client.utils import traverse
15+
from typing_extensions import NotRequired
1516

1617
from . import wasm_utils
1718

@@ -288,3 +289,45 @@ def __init__(self, paths: list[str | pathlib.Path]) -> None:
288289
@classmethod
289290
def clear(cls):
290291
cls.all_paths = []
292+
293+
294+
class BodyCSS(TypedDict):
295+
body_background_fill: str
296+
body_text_color: str
297+
body_background_fill_dark: str
298+
body_text_color_dark: str
299+
300+
301+
class Layout(TypedDict):
302+
id: int
303+
children: list[int | Layout]
304+
305+
306+
class BlocksConfigDict(TypedDict):
307+
version: str
308+
mode: str
309+
app_id: int
310+
dev_mode: bool
311+
analytics_enabled: bool
312+
components: list[dict[str, Any]]
313+
css: str | None
314+
connect_heartbeat: bool
315+
js: str | None
316+
head: str | None
317+
title: str
318+
space_id: str | None
319+
enable_queue: bool
320+
show_error: bool
321+
show_api: bool
322+
is_colab: bool
323+
max_file_size: int | None
324+
stylesheets: list[str]
325+
theme: str | None
326+
protocol: Literal["ws", "sse", "sse_v1", "sse_v2", "sse_v2.1", "sse_v3"]
327+
body_css: BodyCSS
328+
fill_height: bool
329+
theme_hash: str
330+
layout: NotRequired[Layout]
331+
dependencies: NotRequired[list[dict[str, Any]]]
332+
root: NotRequired[str | None]
333+
username: NotRequired[str | None]

gradio/external.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,7 @@ def from_spaces_blocks(space: str, hf_token: str | None) -> Blocks:
464464
predict_fns.append(endpoint.make_end_to_end_fn(helper))
465465
else:
466466
predict_fns.append(None)
467-
return gradio.Blocks.from_config(client.config, predict_fns, client.src)
467+
return gradio.Blocks.from_config(client.config, predict_fns, client.src) # type: ignore
468468

469469

470470
def from_spaces_interface(

gradio/route_utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
from starlette.types import ASGIApp, Message, Receive, Scope, Send
4242

4343
from gradio import processing_utils, utils
44-
from gradio.data_classes import PredictBody
44+
from gradio.data_classes import BlocksConfigDict, PredictBody
4545
from gradio.exceptions import Error
4646
from gradio.helpers import EventData
4747
from gradio.state_holder import SessionState
@@ -640,7 +640,7 @@ def move_uploaded_files_to_cache(files: list[str], destinations: list[str]) -> N
640640
shutil.move(file, dest)
641641

642642

643-
def update_root_in_config(config: dict, root: str) -> dict:
643+
def update_root_in_config(config: BlocksConfigDict, root: str) -> BlocksConfigDict:
644644
"""
645645
Updates the root "key" in the config dictionary to the new root url. If the
646646
root url has changed, all of the urls in the config that correspond to component
@@ -649,7 +649,7 @@ def update_root_in_config(config: dict, root: str) -> dict:
649649
previous_root = config.get("root")
650650
if previous_root is None or previous_root != root:
651651
config["root"] = root
652-
config = processing_utils.add_root_url(config, root, previous_root)
652+
config = processing_utils.add_root_url(config, root, previous_root) # type: ignore
653653
return config
654654

655655

gradio/routes.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,7 @@ def main(request: fastapi.Request, user: str = Depends(get_current_user)):
384384
if (app.auth is None and app.auth_dependency is None) or user is not None:
385385
config = blocks.config
386386
config = route_utils.update_root_in_config(config, root)
387+
config["username"] = user
387388
elif app.auth_dependency:
388389
raise HTTPException(
389390
status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated"
@@ -440,6 +441,7 @@ def get_config(request: fastapi.Request):
440441
request=request, route_path="/config", root_path=app.root_path
441442
)
442443
config = route_utils.update_root_in_config(config, root)
444+
config["username"] = get_current_user(request)
443445
return ORJSONResponse(content=config)
444446

445447
@app.get("/static/{path:path}")

gradio/utils.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252

5353
import gradio
5454
from gradio.context import get_blocks_context
55-
from gradio.data_classes import FileData
55+
from gradio.data_classes import BlocksConfigDict, FileData
5656
from gradio.exceptions import Error
5757
from gradio.strings import en
5858

@@ -1363,11 +1363,21 @@ def _parse_file_size(size: str | int | None) -> int | None:
13631363
return multiple * size_int
13641364

13651365

1366-
def connect_heartbeat(config: dict[str, Any], blocks) -> bool:
1366+
def connect_heartbeat(config: BlocksConfigDict, blocks) -> bool:
1367+
"""
1368+
Determines whether a heartbeat is required for a given config.
1369+
"""
13671370
from gradio.components import State
13681371

13691372
any_state = any(isinstance(block, State) for block in blocks)
13701373
any_unload = False
1374+
1375+
if "dependencies" not in config:
1376+
raise ValueError(
1377+
"Dependencies not found in config. Cannot determine whether"
1378+
"heartbeat is required."
1379+
)
1380+
13711381
for dep in config["dependencies"]:
13721382
for target in dep["targets"]:
13731383
if isinstance(target, (list, tuple)) and len(target) == 2:

guides/08_gradio-clients-and-lite/01_getting-started-with-the-python-client.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,20 @@ from gradio_client import Client
8888
client = Client("https://bec81a83-5b5c-471e.gradio.live")
8989
```
9090

91+
## Connecting to a Gradio app with auth
92+
93+
If the Gradio application you are connecting to [requires a username and password](/guides/sharing-your-app#authentication), then provide them as a tuple to the `auth` argument of the `Client` class:
94+
95+
```python
96+
from gradio_client import Client
97+
98+
Client(
99+
space_name,
100+
auth=[username, password]
101+
)
102+
```
103+
104+
91105
## Inspecting the API endpoints
92106

93107
Once you have connected to a Gradio app, you can view the APIs that are available to you by calling the `Client.view_api()` method. For the Whisper Space, we see the following:

0 commit comments

Comments
 (0)