# Blocks

```python
with gradio.Blocks():
```

### Description

Blocks is Gradio's low-level API that allows you to create more custom web applications and demos than Interfaces (yet still entirely in Python).   Compared to the Interface class, Blocks offers more flexibility and control over: (1) the layout of components (2) the events that trigger the execution of functions (3) data flows (e.g. inputs can trigger outputs, which can trigger the next level of outputs). Blocks also offers ways to group together related demos such as with tabs.   The basic usage of Blocks is as follows: create a Blocks object, then use it as a context (with the "with" statement), and then define layouts, components, or events within the Blocks context. Finally, call the launch() method to launch the demo.

### Example Usage

```python
import gradio as gr
def update(name):
    return f"Welcome to Gradio, {name}!"

with gr.Blocks() as demo:
    gr.Markdown("Start typing below and then click **Run** to see the output.")
    with gr.Row():
        inp = gr.Textbox(placeholder="What is your name?")
        out = gr.Textbox()
    btn = gr.Button("Run")
    btn.click(fn=update, inputs=inp, outputs=out)

demo.launch()
```

### Initialization

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `analytics_enabled` | `bool \| None` | `None` | Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True. |
| `mode` | `str` | `"blocks"` | A human-friendly name for the kind of Blocks or Interface being created. Used internally for analytics. |
| `title` | `str \| I18nData` | `"Gradio"` | The tab title to display when this is opened in a browser window. |
| `fill_height` | `bool` | `False` | Whether to vertically expand top-level child components to the height of the window. If True, expansion occurs when the scale value of the child components >= 1. |
| `fill_width` | `bool` | `False` | Whether to horizontally expand to fill container fully. If False, centers and constrains app to a maximum width. Only applies if this is the outermost `Blocks` in your Gradio app. |
| `delete_cache` | `tuple[int, int] \| None` | `None` | A tuple corresponding [frequency, age] both expressed in number of seconds. Every `frequency` seconds, the temporary files created by this Blocks instance will be deleted if more than `age` seconds have passed since the file was created. For example, setting this to (86400, 86400) will delete temporary files every day. The cache will be deleted entirely when the server restarts. If None, no cache deletion will occur. |
### Demos

**blocks_hello**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/blocks_hello)

```python
import gradio as gr

def welcome(name):
    return f"Welcome to Gradio, {name}!"

with gr.Blocks() as demo:
    gr.Markdown(
    """
    # Hello World!
    Start typing below to see the output.
    """)
    inp = gr.Textbox(placeholder="What is your name?")
    out = gr.Textbox()
    inp.change(welcome, inp, out)

if __name__ == "__main__":
    demo.launch()
```

**blocks_flipper**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/blocks_flipper)

```python
import numpy as np
import gradio as gr

def flip_text(x):
    return x[::-1]

def flip_image(x):
    return np.fliplr(x)

with gr.Blocks() as demo:
    gr.Markdown("Flip text or image files using this demo.")
    with gr.Tab("Flip Text"):
        text_input = gr.Textbox()
        text_output = gr.Textbox()
        text_button = gr.Button("Flip")
    with gr.Tab("Flip Image"):
        with gr.Row():
            image_input = gr.Image()
            image_output = gr.Image()
        image_button = gr.Button("Flip")

    with gr.Accordion("Open for More!", open=False):
        gr.Markdown("Look at me...")
        temp_slider = gr.Slider(
            0, 1,
            value=0.1,
            step=0.1,
            interactive=True,
            label="Slide me",
        )

    text_button.click(flip_text, inputs=text_input, outputs=text_output)
    image_button.click(flip_image, inputs=image_input, outputs=image_output)

if __name__ == "__main__":
    demo.launch()
```

**blocks_kinematics**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/blocks_kinematics)

```python
import pandas as pd
import numpy as np

import gradio as gr

def plot(v, a):
    g = 9.81
    theta = a / 180 * 3.14
    tmax = ((2 * v) * np.sin(theta)) / g
    timemat = tmax * np.linspace(0, 1, 40)

    x = (v * timemat) * np.cos(theta)
    y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2))
    df = pd.DataFrame({"x": x, "y": y})
    return df

demo = gr.Blocks()

with demo:
    gr.Markdown(
        r"Let's do some kinematics! Choose the speed and angle to see the trajectory. Remember that the range $R = v_0^2 \cdot \frac{\sin(2\theta)}{g}$"
    )

    with gr.Row():
        speed = gr.Slider(1, 30, 25, label="Speed")
        angle = gr.Slider(0, 90, 45, label="Angle")
    output = gr.LinePlot(
        x="x",
        y="y",
        tooltip=["x", "y"],
        x_lim=[0, 100],
        y_lim=[0, 60],
        height=300,
    )
    btn = gr.Button(value="Run")
    btn.click(plot, [speed, angle], output)

if __name__ == "__main__":
    demo.launch()
```

### Methods

#### Description

Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called.

#### Supported Event Listeners

The `Blocks` component supports the following event listeners:

- `Blocks.launch(fn, ...)`: Launches a simple web server that serves the demo. Can also be used to create a public link used by anyone to access the demo from their browser by setting share=True.
- `Blocks.queue(fn, ...)`: By enabling the queue you can control when users know their position in the queue, and set a limit on maximum number of events allowed.
- `Blocks.integrate(fn, ...)`: A catch-all method for integrating with other libraries. This method should be run after launch()
- `Blocks.load(fn, ...)`: This listener is triggered when the Blocks initially loads in the browser.
- `Blocks.unload(fn, ...)`: This listener is triggered when the user closes or refreshes the tab, ending the user session. It is useful for cleaning up resources when the app is closed.

#### Event Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `inline` | `bool \| None` | `None` | whether to display in the gradio app inline in an iframe. Defaults to True in python notebooks; False otherwise. |
| `inbrowser` | `bool` | `False` | whether to automatically launch the gradio app in a new tab on the default browser. |
| `share` | `bool \| None` | `None` | 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. Can be set by environment variable GRADIO_SHARE=True. |
| `debug` | `bool` | `False` | if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output. |
| `max_threads` | `int` | `40` | the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40). |
| `auth` | `Callable[[str, str], bool] \| tuple[str, str] \| list[tuple[str, str]] \| None` | `None` | 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` | `str \| None` | `None` | If provided, HTML message provided on login page. |
| `prevent_thread_lock` | `bool` | `False` | 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` | `bool` | `False` | If True, any errors in the gradio app will be displayed in an alert modal and printed in the browser console log. They will also be displayed in the alert modal of downstream apps that gr.load() this app. |
| `server_name` | `str \| None` | `None` | 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". |
| `server_port` | `int \| None` | `None` | 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. |
| `height` | `int` | `500` | The height in pixels of the iframe element containing the gradio app (used if inline=True) |
| `width` | `int \| str` | `"100%"` | The width in pixels of the iframe element containing the gradio app (used if inline=True) |
| `favicon_path` | `str \| Path \| None` | `None` | 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` | `str \| None` | `None` | 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` | `str \| None` | `None` | 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. |
| `ssl_keyfile_password` | `str \| None` | `None` | If a password is provided, will use this with the ssl certificate for https. |
| `ssl_verify` | `bool` | `True` | If False, skips certificate validation which allows self-signed certificates to be used. |
| `quiet` | `bool` | `False` | If True, suppresses most print statements. |
| `footer_links` | `list[Literal['api', 'gradio', 'settings'] \| dict[str, str]] \| None` | `None` | The links to display in the footer of the app. Accepts a list, where each element of the list must be one of "api", "gradio", or "settings" corresponding to the API docs, "built with Gradio", and settings pages respectively. If None, all three links will be shown in the footer. An empty list means that no footer is shown. |
| `allowed_paths` | `list[str] \| None` | `None` | 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. Can be set by comma separated environment variable GRADIO_ALLOWED_PATHS. These files are generally assumed to be secure and will be displayed in the browser when possible. |
| `blocked_paths` | `list[str] \| None` | `None` | 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. Can be set by comma separated environment variable GRADIO_BLOCKED_PATHS. |
| `root_path` | `str \| None` | `None` | 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` | `dict[str, Any] \| None` | `None` | Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}` |
| `state_session_capacity` | `int` | `10000` | The maximum number of sessions whose information to store in memory. If the number of sessions exceeds this number, the oldest sessions will be removed. Reduce capacity to reduce memory usage when using gradio.State or returning updated components from functions. Defaults to 10000. |
| `share_server_address` | `str \| None` | `None` | Use this to specify a custom FRP server and port for sharing Gradio apps (only applies if share=True). If not provided, will use the default FRP server at https://gradio.live. See https://github.com/huggingface/frp for more information. |
| `share_server_protocol` | `Literal['http', 'https'] \| None` | `None` | Use this to specify the protocol to use for the share links. Defaults to "https", unless a custom share_server_address is provided, in which case it defaults to "http". If you are using a custom share_server_address and want to use https, you must set this to "https". |
| `share_server_tls_certificate` | `str \| None` | `None` | The path to a TLS certificate file to use when connecting to a custom share server. This parameter is not used with the default FRP server at https://gradio.live. Otherwise, you must provide a valid TLS certificate file (e.g. a "cert.pem") relative to the current working directory, or the connection will not use TLS encryption, which is insecure. |
| `auth_dependency` | `Callable[[fastapi.Request], str \| None] \| None` | `None` | 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 app (they will see a 401 Unauthorized response). To be used with external authentication systems like OAuth. Cannot be used with `auth`. |
| `max_file_size` | `str \| int \| None` | `None` | The maximum file size in bytes that can be uploaded. Can be a string of the form "<value><unit>", where value is any positive integer and unit is one of "b", "kb", "mb", "gb", "tb". If None, no limit is set. |
| `enable_monitoring` | `bool \| None` | `None` | Enables traffic monitoring of the app through the /monitoring endpoint. By default is None, which enables this endpoint. If explicitly True, will also print the monitoring URL to the console. If False, will disable monitoring altogether. |
| `strict_cors` | `bool` | `True` | If True, prevents external domains from making requests to a Gradio server running on localhost. If False, allows requests to localhost that originate from localhost but also, crucially, from "null". This parameter should normally be True to prevent CSRF attacks but may need to be False when embedding a *locally-running Gradio app* using web components. |
| `node_server_name` | `str \| None` | `None` |  |
| `node_port` | `int \| None` | `None` |  |
| `ssr_mode` | `bool \| None` | `None` | If True, the Gradio app will be rendered using server-side rendering mode, which is typically more performant and provides better SEO, but this requires Node 20+ to be installed on the system. If False, the app will be rendered using client-side rendering mode. If None, will use GRADIO_SSR_MODE environment variable or default to False. |
| `pwa` | `bool \| None` | `None` | If True, the Gradio app will be set up as an installable PWA (Progressive Web App). If set to None (default behavior), then the PWA feature will be enabled if this Gradio app is launched on Spaces, but not otherwise. |
| `mcp_server` | `bool \| None` | `None` | If True, the Gradio app will be set up as an MCP server and documented functions will be added as MCP tools. If None (default behavior), then the GRADIO_MCP_SERVER environment variable will be used to determine if the MCP server should be enabled. |
| `i18n` | `I18n \| None` | `None` | An I18n instance containing custom translations, which are used to translate strings in our components (e.g. the labels of components or Markdown strings). This feature can only be used to translate static text in the frontend, not values in the backend. |
| `theme` | `Theme \| str \| None` | `None` | A Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the Hugging Face Hub (e.g. "gradio/monochrome"). If None, will use the Default theme. |
| `css` | `str \| None` | `None` | Custom css as a code string. This css will be included in the demo webpage. |
| `css_paths` | `str \| Path \| list[str \| Path] \| None` | `None` | Custom css as a pathlib.Path to a css file or a list of such paths. This css files will be read, concatenated, and included in the demo webpage. If the `css` parameter is also set, the css from `css` will be included first. |
| `js` | `str \| Literal[True] \| None` | `None` | Custom js as a code string. The js code will automatically be executed when the page loads. For more flexibility, use the head parameter to insert js inside <script> tags. |
| `head` | `str \| None` | `None` | Custom html code to insert into the head of the demo webpage. This can be used to add custom meta tags, multiple scripts, stylesheets, etc. to the page. |
| `head_paths` | `str \| Path \| list[str \| Path] \| None` | `None` | Custom html code as a pathlib.Path to a html file or a list of such paths. This html files will be read, concatenated, and included in the head of the demo webpage. If the `head` parameter is also set, the html from `head` will be included first. |
- [Blocks And Event Listeners](https://www.gradio.app/guides/blocks-and-event-listeners/)
- [Controlling Layout](https://www.gradio.app/guides/controlling-layout/)
- [State In Blocks](https://www.gradio.app/guides/state-in-blocks/)
- [More Blocks Features](https://www.gradio.app/guides/more-blocks-features/)
