Skip to main content

Google’s Mesop- Rapid Python Web Apps Made Simple

 

Mesop empowers Python developers—especially those without frontend expertise—to build full-featured, component-based web applications in under ten lines of code, with hot reload, strong type safety, and zero need for HTML/CSS/JavaScript.

Introduction

Building sleek, interactive web UIs traditionally requires mastery of HTML, CSS, and JavaScript. Mesop, Google’s open-sourced Python UI framework, upends this workflow by offering:

  • Idiomatic Python UI: Write pages and components entirely in Python functions

  • Hot Reload: Instantly see code changes reflected in the browser while preserving state

  • Reactive State Management: Define application state via @me.stateclass and update it declaratively

  • Component-Based Architecture: Compose reusable UI blocks, akin to React, without leaving Python

  • Enterprise-Grade Workflows: Rich IDE support, type safety, and one-command deployment

Mesop is ideal for AI/ML demos, internal tools, and production applications that demand rapid iteration without sacrificing flexibility.

Core Features

1. Pure-Python Pages and Components

Every Mesop page is a Python function decorated with @me.page. Pages render Mesop components—text, buttons, images, uploads, charts—via simple API calls:

import mesop as me
@me.page(path="/hello", title="Hello Mesop")
def hello():
me.text("Welcome to Mesop!")

This generates an HTTP endpoint at /hello, serving a page with the text “Welcome to Mesop!”[GitHub].

2. Reactive State Management

Define application state in a @me.stateclass. Mesop automatically tracks and persists state across user interactions and hot reloads:

@me.stateclass
class CounterState:
count: int = 0
def increment(evt: me.ClickEvent):
state = me.state(CounterState)
state.count += 1
@me.page(path="/counter")
def counter_page():
state = me.state(CounterState)
me.text(f"Count: {state.count}")
me.button("Increment", on_click=increment)

Here, clicking the “Increment” button updates state.count, and the new value displays instantly without full-page reload[GitHub]1.

3. Hot Reload & Developer Productivity

Mesop’s built-in hot reload watches your code and refreshes the browser, preserving application state. Combined with rich IDE autocompletion and type checking, this yields frictionless workflows that accelerate development significantly[GitHub].

4. Ready-to-Use Labs Components

Mesop Labs offers high-level UI primitives for common patterns—text-to-text, image generation, chat interfaces—enabling sophisticated prototypes in a handful of lines:

import mesop.labs as mel
@me.page(path="/text_to_text", title="Text Echo")
def text_app():
mel.text_to_text(lambda s: "Echo: " + s.upper())

This example creates a live text transformation app with no boilerplate[GitHub].

5. Custom Web Components

Extend Mesop with your own JavaScript components via @me.web_component, injecting custom elements when you need advanced interactivity:

@me.web_component(path="./my_toggle.js")
def toggle(value: bool, on_toggle: Callable):
return me.insert_web_component(
name="my-toggle",
events={"toggle": on_toggle},
properties={"value": value},
)

This bridges Mesop’s Python API with custom frontend code, offering limitless extensibility[Docs].

Getting Started

  1. Install Mesop

    pip install mesop
  2. Create main.py

    import mesop as me
    @me.page()
    def home():
    me.text("Hello, Mesop!")
    if __name__ == "__main__":
    me.run(home)
  3. Run Your App

    mesop main.py

    Navigate to the printed URL (e.g., http://localhost:32123) to view your app.

Building an Image Classifier Example

Below is a complete Mesop application that lets users upload an image and displays top-5 ImageNet predictions using PyTorch’s ResNet-18:

import mesop as me
import torch
import torchvision.transforms as T
from torchvision.models import resnet18
from PIL import Image
import io, base64, requests
# Load model and labels
model = resnet18(pretrained=True).eval()
LABELS = requests.get(
"https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json"
).json()
preprocess = T.Compose([
T.Resize(256), T.CenterCrop(224),
T.ToTensor(),
T.Normalize([0.485,0.456,0.406], [0.229,0.224,0.225]),
])
@me.stateclass
class State:
img_data: bytes = b""
preds: str = ""
def on_upload(e: me.UploadEvent):
state = me.state(State)
state.img_data = e.file.read()
img = Image.open(io.BytesIO(state.img_data))
tensor = preprocess(img).unsqueeze(0)
with torch.no_grad():
out = model(tensor)[0]
probs, idxs = torch.topk(torch.nn.functional.softmax(out, dim=0), 5)
state.preds = "\n".join(
f"{LABELS[i]}: {p:.2%}" for p, i in zip(probs, idxs)
)
@me.page(path="/", title="Image Classifier")
def app():
state = me.state(State)
me.text("Upload an image to classify:")
me.uploader(label="Choose Image", on_upload=on_upload)
if state.img_data:
img_b64 = base64.b64encode(state.img_data).decode()
me.image(src=f"data:image/jpeg;base64,{img_b64}")
if state.preds:
me.text("Top-5 Predictions:", type="headline-5")
me.text(state.preds)
if __name__ == "__main__":
me.run(app)

This example demonstrates Mesop’s seamless integration of uploader, image display, state, and third-party libraries—all through Python alone.

Deployment and Scaling

Mesop provides one-command deployment to major cloud platforms and integrates smoothly with CI/CD pipelines:

mesop deploy --provider=gcp

You can scale across regions, manage team permissions, and monitor metrics, all without touching frontend configurations.

Mesop represents a transformative leap for Python developers seeking to build web UIs without frontend overhead. Its combination of Python-first pages, reactive state management, hot reload, and extensibility makes it an outstanding choice for internal tools, AI/ML demos, and production apps. By eliminating context switches between languages and frameworks, Mesop streamlines development, speeds iteration, and empowers teams to deliver rich web experiences in pure Python

Click Here 
Redmi 
Python Simplified with Generative AI
Data Science and Machine Learning using Python
Learn Data Science from Scratch

Comments

Popular Post

Apply for Google Summer Internship-2025

Google is offering a summer internship in 2025 for students interested in technology, software engineering , and innovation. This program provides hands-on experience, mentorship, and opportunities to work on impactful projects. Ideal for students aiming to enhance their skills and gain industry insights. To apply for the Google summer internship 2025, you'll need an updated CV or resume and a current unofficial or official transcript in English. Click 'Apply' on the internship page and upload the following documents (PDFs preferred): In the 'Resume Section,' attach your updated CV or resume. In the 'Education Section,' attach your current or recent unofficial or official transcript in English. Under 'Degree Status,' select 'Now attending' to upload your transcript. You can choose your preferred working location from Bengaluru, Hyderabad, or Pune in India when applying. Minimum qualifications: Currently studying for a Bachelor's or Maste...

IIRS-ISRO offers AI/ML for Geo Data Analysis: A Free Course

AI has captured our imagination and research focus since the Dartmouth Conferences in 1956, where the field was born. Defined as programs that can sense, reason, act, and adapt, AI has been heralded as the key to a brighter future. Machine Learning (ML) involves algorithms that improve with data over time, while Deep Learning, a subset of ML, utilizes multilayered neural networks to learn from vast data. Technological advancements have enabled the processing and analysis of unprecedented data volumes, driven by the proliferation of internet-connected devices. These advancements bring us closer to creating intelligent machines seen in everyday applications like online recommendations and auto-generated photo tags. The main applications of deep learning AI include computer vision, natural language processing (NLP), and reinforcement learning. This course, scheduled from August 19-24, 2024 , covers AI, ML, Deep Learning, and data processing techniques, with case studies in geospatial dat...

Apply for Microsoft Software Engineering Internship

Join Microsoft as an intern to build community, explore your passions, and work on real-world projects. Software engineers collaborate to solve problems and create innovative solutions. Interns have fun while working globally, contributing to Microsoft's mission to empower everyone. Embrace a growth mindset, innovate , and build a culture of inclusion where all can thrive. Qualifications: Currently pursuing a bachelor's or master's degree in engineering, computer science, or a related field. Must have at least one more quarter/semester of college remaining after the internship. One year of experience programming in an object-oriented language . Responsibilities: Apply engineering principles to creatively solve complex problems. Quickly learn and integrate new engineering methods into workflows. Seek and apply feedback and best practices to improve technical solutions. Manage time effectively to complete software projects in a collaborative team environment. Click the bel...