Streamlit自定义认证组件生产环境加载失败求助
自定义Streamlit认证组件生产环境渲染失败问题及解决
问题现象
- 测试一款自定义Streamlit认证组件,开发环境可正常运行,但生产环境(含Linux Docker容器部署场景)无法渲染组件。
- 排查发现组件声明失败,抛出
AssertionError,报错核心为assert module is not None断言不成立,回溯信息如下:
venv\lib\site-packages\streamlit\components\v1\components.py:284, in declare_component(name, path, url) 281 # Get the caller's module name. `__name__` gives us the module's 282 # fully-qualified name, which includes its package. 283 module = inspect.getmodule(caller_frame) --> 284 assert module is not None ... 288 # user executed `python my_component.py`), then this name will be 289 # "__main__" instead of the actual package name. In this case, we use 290 # the main module's filename, sans `.py` extension, as the component name. AssertionError:
相关代码与路径信息
构建路径获取代码
root_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(root_dir, "frontend" , "dist")
返回的构建路径:
'c:\\Users\\initials\\xxx\\Desktop\\Absence importer\\absense_importer\\frontend\\dist'
组件声明代码
_USE_WEB_DEV_SERVER = os.getenv("USE_WEB_DEV_SERVER", False) _WEB_DEV_SERVER_URL = os.getenv("WEB_DEV_SERVER_URL", "http://localhost:5173") COMPONENT_NAME = "msal_authentication" root_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(root_dir, "frontend" , "dist") if _USE_WEB_DEV_SERVER: _component_func = components.declare_component(name=COMPONENT_NAME, url=_WEB_DEV_SERVER_URL) else: _component_func = components.declare_component(name=COMPONENT_NAME, path=build_dir)
环境版本:Python 3.10.7、Streamlit 1.18.1
问题根源与解决办法
经定位,问题本质是浏览器无法读取编译后的前端代码,原因是MIME类型不匹配。可通过以下两种方式修复:
- 手动添加MIME类型映射:
import mimetypes mimetypes.add_type('application/javascript', '.js') mimetypes.add_type('text/css', '.css')
- 使用组件作者提供的示例库
效果对比
解决前组件渲染异常:

解决后组件正常渲染:

内容的提问来源于stack exchange,提问作者Artem
相关产品推荐
相关产品推荐

