I am trying to achieve HTML display message on webpage using gradio mounted on fastapi.
import gradio as gr
from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware
import uuid
app = FastAPI()
def get_user_info(request: gr.Request):
return f"<b>Welcome {request.request.session.get('username', 'User')}!<b/>"
with gr.Blocks(title="test") as demo:
gr.Markdown("# Test App")
with gr.Row():
with gr.Column():
user_info = gr.components.HTML(get_user_info)
app = gr.mount_gradio_app(app, demo, "/home")
app.add_middleware(SessionMiddleware, secret_key=uuid.uuid4().hex)
The above code is throwing error as TypeError: get_user_info() missing 1 required positional argument: 'request'
If I write this code again using button click. It will work fine.
import gradio as gr
from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware
import uuid
app = FastAPI()
def get_user_info(request: gr.Request):
return f"<b>Welcome {request.request.session.get('username', 'User')}!<b/>"
with gr.Blocks(title="test") as demo:
gr.Markdown("# Test App")
with gr.Row():
with gr.Column():
user_info = gr.components.HTML()
b2 = gr.Button(value="Logging")
b2.click(get_user_info, outputs=user_info)
app = gr.mount_gradio_app(app, demo, "/home")
app.add_middleware(SessionMiddleware, secret_key=uuid.uuid4().hex)
Output before click
Output after click
How can i achieve same using first code and without using button. How to resolve the above error?
The function has to be called by gradio which only happens if you pass it as callable to a gradio Component, or call it yourself using get_user_info(request)
.
One way to do it is to use the gradio Blocks.load
instance method:
import gradio as gr
from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware
import uuid
app = FastAPI()
def get_user_info(request: gr.Request):
return f"<b>Welcome {request.request.session.get('username', 'User')}!<b/>"
with gr.Blocks(title="test") as demo:
gr.Markdown("# Test App")
with gr.Row():
with gr.Column():
user_info = gr.components.HTML()
demo.load(get_user_info, outputs=user_info)
app = gr.mount_gradio_app(app, demo, "/home")
app.add_middleware(SessionMiddleware, secret_key=uuid.uuid4().hex)
# to launch this example standalone:
#
# if __name__ == '__main__':
# import uvicorn
# uvicorn.run(app, host='127.0.0.1', port=8007)