用python编写web 界面可以用哪些库

背景:

很多人熟悉python, 但不熟悉前端语言js, 为了项目快速落地,也不太想去专门学习 React/Angular/Vue这些框架,那么就会问一个问题,能不能用Python直接写出一个简单web界面呢?答案是可以的,而且有多种框架可以用。常见的有下面的几种,可自行搜索学习,选用适合自己的

 

Plotly Dash, 基于Flask,Plotly.js。 画出来的图标很漂亮,尤其是交互式图标很炫酷。 适用于数据展示

Streamlit,也比较常用

Panel, 感觉比Steamlit 少见一些

Gradio, 做单页网页很方便,而且自带 rest api, 如果要做多页网页,就要配合 flask这些框架(下面是用flask+Gradio写的一个多网页demo)

from flask import Flask, render_template_string
import gradio as gr

app = Flask(__name__)

# Define the first Gradio interface for the "/greet" API endpoint
def greet(name):
    return f"Hello, {name}!"

greet_interface = gr.Interface(fn=greet, inputs="text", outputs="text")

# Define the second Gradio interface for the "/square" API endpoint
def square(x):
    return x ** 2

square_interface = gr.Interface(fn=square, inputs="number", outputs="number")

# Define the third Gradio interface for the "/echo" API endpoint
def echo(text):
    return f"You said: {text}"

echo_interface = gr.Interface(fn=echo, inputs="text", outputs="text")

# HTML template for embedding Gradio apps in iframes
iframe_template = '''
    <h1>{{ title }}</h1>
    <iframe src="{{ gradio_url }}" width="100%" height="800px" frameborder="0"></iframe>
'''

# Flask route for the homepage
@app.route('/')
def index():
    return "Welcome to the multi-page Gradio app!"

# Flask route for the "/greet" page
@app.route('/greet')
def greet_page():
    return render_template_string(iframe_template, title="Greet Page", gradio_url=greet_interface.local_url)

# Flask route for the "/square" page
@app.route('/square')
def square_page():
    return render_template_string(iframe_template, title="Square Page", gradio_url=square_interface.local_url)

# Flask route for the "/echo" page
@app.route('/echo')
def echo_page():
    return render_template_string(iframe_template, title="Echo Page", gradio_url=echo_interface.local_url)

if __name__ == '__main__':

    greet_interface.launch(prevent_thread_lock=True)
    square_interface.launch(prevent_thread_lock=True)
    echo_interface.launch(prevent_thread_lock=True)
    # Run the Flask app
    app.run()

 

posted @ 2024-09-05 09:14  mashuai_191  阅读(38)  评论(0编辑  收藏  举报