Convert Figma logo to code with AI

pywebio logoPyWebIO

Write interactive web app in script way.

4,590
385
4,590
34

Top Related Projects

36,194

Streamlit β€” A faster way to build and share data apps.

21,827

Data Apps & Dashboards for Python. No JavaScript Required.

34,595

Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work!

20,936

πŸ•ΈοΈ Web apps in pure Python 🐍

11,752

Flet enables developers to easily build realtime web, mobile and desktop apps in Python. No frontend experience required.

Quick Overview

PyWebIO is a Python library that allows developers to create interactive web applications directly from Python code, without the need for complex web development frameworks or knowledge of HTML, CSS, or JavaScript. It provides a simple and intuitive API for building web-based user interfaces, handling user input, and managing application logic.

Pros

  • Simplicity: PyWebIO abstracts away the complexities of web development, allowing developers to focus on the application logic rather than the underlying web technologies.
  • Rapid Prototyping: The library's concise and expressive API enables developers to quickly build and iterate on web applications.
  • Cross-Platform Compatibility: PyWebIO applications can be deployed on various platforms, including desktop, mobile, and cloud environments.
  • Seamless Integration: PyWebIO integrates well with other Python libraries and frameworks, making it easy to incorporate into existing projects.

Cons

  • Limited Customization: While PyWebIO provides a set of built-in UI components, the level of customization and styling options may be limited compared to more traditional web development frameworks.
  • Performance Concerns: For large-scale or highly interactive applications, the performance of PyWebIO-based applications may not be as optimal as those built with more specialized web frameworks.
  • Dependency on WebSocket: PyWebIO relies on WebSocket connections for real-time communication, which may not be supported in all environments or may require additional configuration.
  • Smaller Community: Compared to more established web development frameworks, PyWebIO has a relatively smaller community, which may impact the availability of resources, plugins, and third-party integrations.

Code Examples

Creating a Simple Web Application

from pywebio.input import input, NUMBER
from pywebio.output import put_text

def calculator():
    a = input("Enter the first number:", type=NUMBER)
    b = input("Enter the second number:", type=NUMBER)
    put_text(f"The sum of {a} and {b} is {a + b}")

if __name__ == "__main__":
    calculator()

This code creates a simple web-based calculator application using PyWebIO. The input() function is used to collect user input, and the put_text() function is used to display the result.

Handling User Interactions

from pywebio.input import input, FLOAT
from pywebio.output import put_text, put_button, clear
from pywebio.session import run_js

def temperature_converter():
    put_text("Temperature Converter")

    def convert(from_unit, to_unit):
        temp = input(f"Enter temperature in {from_unit}:", type=FLOAT)
        if from_unit == "Celsius":
            result = (temp * 9/5) + 32 if to_unit == "Fahrenheit" else temp + 273.15
        else:
            result = (temp - 32) * 5/9 if to_unit == "Celsius" else temp + 273.15
        put_text(f"{temp}Β°{from_unit} is equal to {result:.2f}Β°{to_unit}")
        clear()

    put_button("Celsius to Fahrenheit", onclick=lambda: convert("Celsius", "Fahrenheit"))
    put_button("Celsius to Kelvin", onclick=lambda: convert("Celsius", "Kelvin"))
    put_button("Fahrenheit to Celsius", onclick=lambda: convert("Fahrenheit", "Celsius"))
    put_button("Fahrenheit to Kelvin", onclick=lambda: convert("Fahrenheit", "Kelvin"))

if __name__ == "__main__":
    temperature_converter()

This code creates a temperature conversion web application using PyWebIO. The put_button() function is used to create interactive buttons, and the run_js() function is used to execute JavaScript code within the PyWebIO application.

Getting Started

To get started with PyWebIO, follow these steps:

  1. Install the PyWebIO library using pip:

    pip install pywebio
    
  2. Create a new Python file (e.g., app.py) and import the necessary PyWebIO modules:

    from pywebio.input import input, NUMBER
    from py
    

Competitor Comparisons

36,194

Streamlit β€” A faster way to build and share data apps.

Pros of Streamlit

  • More mature and widely adopted, with a larger community and ecosystem
  • Offers more built-in components and visualization options out-of-the-box
  • Better documentation and extensive examples available

Cons of Streamlit

  • Less flexible in terms of UI customization and layout control
  • Heavier resource usage, especially for larger applications
  • Steeper learning curve for developers new to web development

Code Comparison

PyWebIO:

from pywebio.input import input
from pywebio.output import put_text

name = input("What's your name?")
put_text(f"Hello, {name}!")

Streamlit:

import streamlit as st

name = st.text_input("What's your name?")
if name:
    st.write(f"Hello, {name}!")

Summary

Both PyWebIO and Streamlit are Python libraries for creating web applications. PyWebIO focuses on simplicity and ease of use, making it ideal for quickly prototyping ideas or creating simple web interfaces. Streamlit, on the other hand, offers more advanced features and is better suited for data science and machine learning applications. The choice between the two depends on the specific project requirements, development experience, and desired level of customization.

21,827

Data Apps & Dashboards for Python. No JavaScript Required.

Pros of Dash

  • More mature and feature-rich ecosystem for building complex data visualization applications
  • Extensive documentation and community support
  • Seamless integration with Plotly's powerful charting library

Cons of Dash

  • Steeper learning curve, especially for beginners
  • Requires more boilerplate code for simple applications
  • Heavier dependency footprint

Code Comparison

Dash example:

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash(__name__)
app.layout = html.Div([
    html.H1('Hello Dash'),
    dcc.Graph(id='example-graph')
])

PyWebIO example:

from pywebio.output import put_text, put_chart

def main():
    put_text('Hello PyWebIO')
    put_chart([['x', 'y'], [1, 1], [2, 2], [3, 3]])

if __name__ == '__main__':
    start_server(main, port=8080)

PyWebIO offers a more straightforward approach for simple web applications, with less boilerplate code and an easier learning curve. However, Dash provides a more comprehensive toolkit for building complex, interactive data visualization applications, especially when leveraging Plotly's charting capabilities.

34,595

Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work!

Pros of Gradio

  • More focused on machine learning model deployment and visualization
  • Offers a wider range of pre-built components for ML tasks
  • Supports more advanced features like real-time updates and custom CSS

Cons of Gradio

  • Steeper learning curve for non-ML developers
  • Less flexibility for general-purpose web applications
  • Requires more setup for simple tasks compared to PyWebIO

Code Comparison

PyWebIO example:

from pywebio.input import input
from pywebio.output import put_text

name = input("What's your name?")
put_text(f"Hello, {name}!")

Gradio example:

import gradio as gr

def greet(name):
    return f"Hello, {name}!"

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

Both libraries aim to simplify web application development, but Gradio is more specialized for machine learning tasks, while PyWebIO offers a more general-purpose approach. Gradio provides more advanced features and pre-built components for ML model deployment, but may be overkill for simple applications. PyWebIO, on the other hand, offers a more straightforward API for basic web interactions but may lack some of the specialized tools that Gradio provides for ML-specific tasks.

20,936

πŸ•ΈοΈ Web apps in pure Python 🐍

Pros of Reflex

  • Full-stack framework with built-in state management and routing
  • Supports creating more complex, interactive web applications
  • Offers a more React-like development experience for Python developers

Cons of Reflex

  • Steeper learning curve, especially for those unfamiliar with React concepts
  • More opinionated structure, which may limit flexibility for some projects
  • Requires more setup and configuration compared to PyWebIO

Code Comparison

PyWebIO example:

from pywebio.input import input
from pywebio.output import put_text

def main():
    name = input("What's your name?")
    put_text(f"Hello, {name}!")

if __name__ == '__main__':
    main()

Reflex example:

import reflex as rx

class State(rx.State):
    name: str = ""

def index():
    return rx.vstack(
        rx.input(placeholder="What's your name?", on_change=State.set_name),
        rx.text(f"Hello, {State.name}!")
    )

app = rx.App()
app.add_page(index)

Both PyWebIO and Reflex allow for creating web applications using Python, but they differ in complexity and approach. PyWebIO is simpler and more straightforward for basic applications, while Reflex offers more advanced features for building complex, interactive web apps with a structure similar to modern JavaScript frameworks.

11,752

Flet enables developers to easily build realtime web, mobile and desktop apps in Python. No frontend experience required.

Pros of Flet

  • Cross-platform support for desktop, web, and mobile applications
  • Rich set of pre-built UI controls and layouts
  • Utilizes Flutter's rendering engine for smooth and responsive UIs

Cons of Flet

  • Steeper learning curve for developers unfamiliar with Flutter concepts
  • Limited customization options compared to PyWebIO's flexibility
  • Larger application size due to bundled Flutter runtime

Code Comparison

PyWebIO example:

from pywebio.input import input
from pywebio.output import put_text

name = input("What's your name?")
put_text(f"Hello, {name}!")

Flet example:

import flet as ft

def main(page: ft.Page):
    name_input = ft.TextField(label="What's your name?")
    greeting = ft.Text()
    
    def update_greeting(e):
        greeting.value = f"Hello, {name_input.value}!"
        page.update()

    page.add(name_input, ft.ElevatedButton("Greet", on_click=update_greeting), greeting)

ft.app(target=main)

Both PyWebIO and Flet offer Python-based solutions for creating web applications, but they differ in their approach and capabilities. PyWebIO focuses on simplicity and ease of use, while Flet provides a more comprehensive framework for building cross-platform applications with a richer set of UI components.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

PyWebIO

Write interactive web app in script way.

Percy visual test Code coverage Jsdelivr hit count Documentation Status Package version Python Version
License
[Document] | [Demos] | [Playground] | [Why PyWebIO?]

English | À¸­æ–‡

PyWebIO provides a series of imperative functions to obtain user input and output on the browser, turning the browser into a "rich text terminal", and can be used to build simple web applications or browser-based GUI applications without the need to have knowledge of HTML and JS. PyWebIO can also be easily integrated into existing Web services. PyWebIO is very suitable for quickly building applications that do not require complex UI.

PyWebIO output demo PyWebIO input demo

Features:

  • Use synchronization instead of a callback-based method to get input
  • Non-declarative layout, simple and efficient
  • Less intrusive: old script code can be transformed into a Web application only by modifying the input and output operation
  • Support integration into existing web services, currently supports Flask, Django, Tornado, aiohttp, FastAPI framework
  • Support for asyncio and coroutine
  • Support data visualization with third-party libraries, e.g., plotly, bokeh, pyecharts.

Installation

Stable version:

pip3 install -U pywebio

Development version:

pip3 install -U https://github.com/pywebio/PyWebIO/archive/dev-release.zip

Prerequisites: PyWebIO requires Python 3.5.2 or newer

Quickstart

Hello, world

Here is a simple PyWebIO script to calculate the BMI:

from pywebio.input import input, FLOAT
from pywebio.output import put_text

def bmi():
    height = input("Your Height(cm):", type=FLOAT)
    weight = input("Your Weight(kg):", type=FLOAT)

    BMI = weight / (height / 100) ** 2

    top_status = [(14.9, 'Severely underweight'), (18.4, 'Underweight'),
                  (22.9, 'Normal'), (27.5, 'Overweight'),
                  (40.0, 'Moderately obese'), (float('inf'), 'Severely obese')]

    for top, status in top_status:
        if BMI <= top:
            put_text('Your BMI: %.1f, category: %s' % (BMI, status))
            break

if __name__ == '__main__':
    bmi()

This is just a very simple script if you ignore PyWebIO, but using the input and output functions provided by PyWebIO, you can interact with the code in the browser [demo]:

PyWebIO demo

Serve as web service

The above BMI program will exit immediately after the calculation, you can use pywebio.start_server() to publish the bmi() function as a web application:

from pywebio import start_server
from pywebio.input import input, FLOAT
from pywebio.output import put_text

def bmi(): # bmi() keep the same
    ...  

if __name__ == '__main__':
    start_server(bmi, port=80)

Integration with web framework

To integrate a PyWebIO application into Tornado, all you need is to add a RequestHandler to the existing Tornado application:

import tornado.ioloop
import tornado.web
from pywebio.platform.tornado import webio_handler

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/bmi", webio_handler(bmi)),  # bmi is the same function as above
    ])
    application.listen(port=80, address='localhost')
    tornado.ioloop.IOLoop.current().start()

Now, you can open http://localhost/bmi for BMI calculation.

For integration with other web frameworks, please refer to document.

Demos

  • Basic demo : PyWebIO basic input and output demos and some small applications written using PyWebIO.
  • Data visualization demo : Data visualization with the third-party libraries, e.g., plotly, bokeh, pyecharts.

Links