Streamlit - python 快速生成UI框架

266 阅读1分钟

参考文档:Streamlit docs

安装 streamlit 环境

  • python 项目下终端执行:pip install streamlit
  • 验证:streamlit hello , 有跳转即成功

完成

效果

  • py 代码
    import streamlit as st
    import requests
    
    st.title("接口测试器")
    
    # url 接口地址,默认本地启动的地址
    def test_api(url):
        try:
            response = requests.get(url)
            if response.status_code == 200:
                st.success(f"接口 {url} 请求成功!")
                try:
                    data = response.json()
                    st.json(data)
                except ValueError:
                    st.text("响应不是有效的 JSON 数据")
                    st.text(response.text)
            else:
                st.error(f"接口 {url} 返回错误状态码: {response.status_code}")
                st.text(response.text)
        except Exception as e:
            st.error(f"接口 {url} 请求失败: {e}")
    
    # 输入框和按钮1
    url1 = st.text_input("接口1 URL", "http://localhost:8080/ping")
    if st.button("发送请求 到接口1"):
        test_api(url1)
    
    st.markdown("---")  # 分割线
    
    # 输入框和按钮2
    url2 = st.text_input("接口2 URL", "http://localhost:8080/hello")
    if st.button("发送请求 到接口2"):
        test_api(url2)
    
    # 你可以继续添加更多输入框和按钮,方式类似
    
  • 运行:streamlit run .\api_test.py
  • UI 界面 image.png

tips

可以使用 AI 生成需要的UI代码