Skip to content

Instantly share code, notes, and snippets.

@w-e-w
Created December 28, 2024 05:56
Show Gist options
  • Save w-e-w/3b98e4fe30b3bf75c1f632bdb1ec704e to your computer and use it in GitHub Desktop.
Save w-e-w/3b98e4fe30b3bf75c1f632bdb1ec704e to your computer and use it in GitHub Desktop.
This is an extension of sd-webui for testing the ability add new middleware after the server has started
"""
This is an extension of sd-webui for testing the ability add new middleware after the server has started.
New middleware can be added by clicking the button in the Setting > Middleware section,
or by get request to /add-test-middleware.
The middleware will print the request url to the console with the middleware count and datetime.
[<Number>] <datetime>: <url>
Usage: save this script to extensions/<add_middleware>/scripts/sd_webui_add_middleware_test.py then restart the webui server.
"""
from modules import script_callbacks, shared
import gradio as gr
import datetime
store_app = None
add_middleware_count = 0
class OptionButton(shared.OptionInfo):
@staticmethod
def wrapped_button_component(on_click, **kwargs):
button = gr.Button(**kwargs)
button.click(fn=on_click)
return button
def __init__(self, button_text, on_button_click, **kwargs):
super().__init__(button_text, component=lambda **component_kwargs: OptionButton.wrapped_button_component(on_button_click, **component_kwargs), **kwargs)
self.do_not_save = True
def add_middleware():
if store_app is None:
return
global add_middleware_count
add_middleware_count += 1
count = add_middleware_count
print(f'Adding middleware [{count}]')
@store_app.middleware("http")
async def log_everything(req, call_next):
print(f'[{count}] {datetime.datetime.now()}: {getattr(req, "url", req)}')
return await call_next(req)
def on_ui_settings():
section = ('middleware', "Middleware")
shared.opts.add_option("add_middleware", OptionButton('Add middleware', add_middleware, section=section))
def on_app_started(demo, app):
global store_app
store_app = app
@app.get("/add-test-middleware")
async def add_test_middleware():
add_middleware()
return f"Added middleware [{add_middleware_count}]"
script_callbacks.on_ui_settings(on_ui_settings)
script_callbacks.on_app_started(on_app_started)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment