Add allowed_paths, blocked_paths, show_error, and favicon_path parameters to gr.mount_gradio_app (#7734)

* mount

* add params

* routes

* add changeset

* blocks

* fixes

* add changeset

* typo

* typo

* mount

---------

Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
This commit is contained in:
Abubakar Abid 2024-03-19 10:56:20 -07:00 committed by GitHub
parent 84f81fec92
commit 04857bc524
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 44 additions and 10 deletions

View File

@ -0,0 +1,5 @@
---
"gradio": minor
---
feat:Add `allowed_paths`, `blocked_paths`, `show_error`, and `favicon_path` parameters to `gr.mount_gradio_app`

View File

@ -1965,19 +1965,19 @@ Received outputs:
public link used by anyone to access the demo from their browser by setting share=True.
Parameters:
inline: whether to display in the interface inline in an iframe. Defaults to True in python notebooks; False otherwise.
inbrowser: whether to automatically launch the interface in a new tab on the default browser.
share: whether to create a publicly shareable link for the interface. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported.
inline: whether to display in the gradio app inline in an iframe. Defaults to True in python notebooks; False otherwise.
inbrowser: whether to automatically launch the gradio app in a new tab on the default browser.
share: whether to create a publicly shareable link for the gradio app. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported.
debug: if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output.
auth: If provided, username and password (or list of username-password tuples) required to access app. Can also provide function that takes username and password and returns True if valid login.
auth_message: If provided, HTML message provided on login page.
prevent_thread_lock: If True, the interface will block the main thread while the server is running.
show_error: If True, any errors in the interface will be displayed in an alert modal and printed in the browser console log
prevent_thread_lock: By default, the gradio app blocks the main thread while the server is running. If set to True, the gradio app will not block and the gradio server will terminate as soon as the script finishes.
show_error: If True, any errors in the gradio app will be displayed in an alert modal and printed in the browser console log
server_port: will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.
server_name: to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1".
max_threads: the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40).
width: The width in pixels of the iframe element containing the interface (used if inline=True)
height: The height in pixels of the iframe element containing the interface (used if inline=True)
width: The width in pixels of the iframe element containing the gradio app (used if inline=True)
height: The height in pixels of the iframe element containing the gradio app (used if inline=True)
favicon_path: If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page.
ssl_keyfile: If a path to a file is provided, will use this as the private key file to create a local server running on https.
ssl_certfile: If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.
@ -1985,7 +1985,7 @@ Received outputs:
ssl_verify: If False, skips certificate validation which allows self-signed certificates to be used.
quiet: If True, suppresses most print statements.
show_api: If True, shows the api docs in the footer of the app. Default True.
allowed_paths: List of complete filepaths or parent directories that gradio is allowed to serve (in addition to the directory containing the gradio python file). Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app.
allowed_paths: List of complete filepaths or parent directories that gradio is allowed to serve. Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app.
blocked_paths: List of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default.
root_path: The root path (or "mount point") of the application, if it's not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application. For example, if the application is served at "https://example.com/myapp", the `root_path` should be set to "/myapp". A full URL beginning with http:// or https:// can be provided, which will be used as the root path in its entirety. Can be set by environment variable GRADIO_ROOT_PATH. Defaults to "".
app_kwargs: Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}`

View File

@ -1022,6 +1022,10 @@ def mount_gradio_app(
auth_message: str | None = None,
auth_dependency: Callable[[fastapi.Request], str | None] | None = None,
root_path: str | None = None,
allowed_paths: list[str] | None = None,
blocked_paths: list[str] | None = None,
favicon_path: str | None = None,
show_error: bool = True,
) -> fastapi.FastAPI:
"""Mount a gradio.Blocks to an existing FastAPI application.
@ -1034,6 +1038,10 @@ def mount_gradio_app(
auth_message: If provided, HTML message provided on login page for this gradio app.
auth_dependency: A function that takes a FastAPI request and returns a string user ID or None. If the function returns None for a specific request, that user is not authorized to access the gradio app (they will see a 401 Unauthorized response). To be used with external authentication systems like OAuth. Cannot be used with `auth`.
root_path: The subpath corresponding to the public deployment of this FastAPI application. For example, if the application is served at "https://example.com/myapp", the `root_path` should be set to "/myapp". A full URL beginning with http:// or https:// can be provided, which will be used in its entirety. Normally, this does not need to provided (even if you are using a custom `path`). However, if you are serving the FastAPI app behind a proxy, the proxy may not provide the full path to the Gradio app in the request headers. In which case, you can provide the root path here.
allowed_paths: List of complete filepaths or parent directories that this gradio app is allowed to serve. Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app.
blocked_paths: List of complete filepaths or parent directories that this gradio app is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default.
favicon_path: If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for this gradio app's page.
show_error: If True, any errors in the gradio app will be displayed in an alert modal and printed in the browser console log. Otherwise, errors will only be visible in the terminal session running the Gradio app.
Example:
from fastapi import FastAPI
import gradio as gr
@ -1062,6 +1070,15 @@ def mount_gradio_app(
else:
blocks.auth = auth
blocks.auth_message = auth_message
blocks.favicon_path = favicon_path
blocks.allowed_paths = allowed_paths or []
blocks.blocked_paths = blocked_paths or []
blocks.show_error = show_error
if not isinstance(blocks.allowed_paths, list):
raise ValueError("`allowed_paths` must be a list of directories.")
if not isinstance(blocks.blocked_paths, list):
raise ValueError("`blocked_paths` must be a list of directories.")
if root_path is not None:
blocks.root_path = root_path

View File

@ -389,6 +389,11 @@ async def logout(request: Request):
@app.route('/login')
async def login(request: Request):
redirect_uri = request.url_for('auth')
# If your app is running on https, you should ensure that the
# `redirect_uri` is https, e.g. uncomment the following lines:
#
# from urllib.parse import urlparse, urlunparse
# redirect_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https'))
return await oauth.google.authorize_redirect(request, redirect_uri)
@app.route('/auth')

View File

@ -344,16 +344,23 @@ class TestRoutes:
with TestClient(app) as client:
assert client.get("/echo/docs-custom").is_success
def test_mount_gradio_app_with_auth_and_root_path(self):
def test_mount_gradio_app_with_auth_and_params(self):
app = FastAPI()
demo = gr.Interface(lambda s: f"You said {s}!", "textbox", "textbox").queue()
app = gr.mount_gradio_app(
app, demo, path="/echo", auth=("a", "b"), root_path="/echo"
app,
demo,
path="/echo",
auth=("a", "b"),
root_path="/echo",
allowed_paths=["test/test_files/bus.png"],
)
# Use context manager to trigger start up events
with TestClient(app) as client:
assert client.get("/echo/config").status_code == 401
assert demo.root_path == "/echo"
assert demo.allowed_paths == ["test/test_files/bus.png"]
assert demo.show_error
def test_mount_gradio_app_with_lifespan(self):
@asynccontextmanager