Python web Applications Examples
Ready-to-deploy micro-applications for over 20 Python frameworks. Copy, paste, install dependencies, and launch.
Quick Jump Index
Deployment Instructions: The commands below assume your main python file is named main.py or your application instance is named app. Install the required packages via the IDE Packages panel, then open the Hosting Dashboard, enter the Start Command and Internal Port exactly as shown below.
Static HTML Vanilla Web
Host standard web files without a Python framework.
- Start Command:
python -m http.server 8000 - Internal Port:
8000 - Required Packages:
None
Setup: Name this file index.html (not main.py) and place it in your project root.
<!DOCTYPE html>
<html>
<head>
<title>Static Site</title>
<style>
body { font-family: sans-serif; text-align: center; margin-top: 50px; }
h1 { color: #3b82f6; }
</style>
</head>
<body>
<h1>Hosted on Python Online</h1>
<p>This is a pure HTML file served natively.</p>
</body>
</html>
Flask Web API
A dynamic Markdown-to-HTML rendering API.
- Start Command:
python -m flask --app main run - Internal Port:
5000 - Required Packages:
flaskmarkdown
from flask import Flask, request, render_template_string
import markdown
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
html_output = ""
if request.method == 'POST':
raw_md = request.form.get('markdown_text', '')
html_output = markdown.markdown(raw_md)
return render_template_string('''
<h1>Markdown Renderer</h1>
<form method="POST">
<textarea name="markdown_text" rows="10" cols="50">**Type** markdown _here_</textarea><br>
<input type="submit" value="Render">
</form>
<hr>
<div>{{ html_output | safe }}</div>
''', html_output=html_output)
Django Web Framework
A highly optimized "Single-File Django" micro-app. Bypasses the complex boilerplate for instant deployment.
- Start Command:
python main.py runserver - Internal Port:
8000 - Required Packages:
django
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
from django.http import HttpResponse
from django.urls import path
# 1. Configure Settings
settings.configure(
DEBUG=True,
SECRET_KEY='a-bad-secret-key-change-me',
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=['*'],
)
# 2. View Function
def index(request):
return HttpResponse("<h1>Hello from Single-File Django!</h1><p>No boilerplate required.</p>")
# 3. URL Routing
urlpatterns = [
path('', index),
]
# 4. Entry Point
if __name__ == '__main__':
execute_from_command_line(sys.argv)
FastAPI Async API
An in-memory CRUD API for managing a Task List using Pydantic validation.
- Start Command:
python -m uvicorn main:app - Internal Port:
8000 - Required Packages:
fastapiuvicorn
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
app = FastAPI(title="Task Manager API")
class Task(BaseModel):
id: int
title: str
completed: bool = False
db: List[Task] = [Task(id=1, title="Learn FastAPI")]
@app.get("/")
def home():
return {"message": "Go to /docs for the Swagger UI"}
@app.get("/tasks", response_model=List[Task])
def get_tasks():
return db
@app.post("/tasks", response_model=Task)
def create_task(task: Task):
db.append(task)
return task
Streamlit Data Dashboard
An interactive data dashboard that generates a random dataset and plots it.
- Start Command:
streamlit run main.py --server.headless true - Internal Port:
8501 - Required Packages:
streamlitpandasnumpy
Important: The --server.headless true flag is strictly required to prevent crashes.
import streamlit as st
import pandas as pd
import numpy as np
st.title("Data Dashboard")
st.write("Welcome to your interactive Streamlit app hosted on Python Online.")
# Slider widget
num_points = st.slider("Select number of data points", 10, 500, 50)
# Generate data
st.write(f"Generating chart with {num_points} points...")
chart_data = pd.DataFrame(
np.random.randn(num_points, 3),
columns=['Metric A', 'Metric B', 'Metric C']
)
# Plot
st.line_chart(chart_data)
Gradio Machine Learning UI
A text-analysis UI that takes user input and returns word counts and reversed text.
- Start Command:
python main.py - Internal Port:
7860 - Required Packages:
gradio
import gradio as gr
def text_analyzer(text):
word_count = len(text.split())
char_count = len(text)
reversed_text = text[::-1]
summary = f"Words: {word_count}\nCharacters: {char_count}"
return summary, reversed_text
with gr.Blocks() as demo:
gr.Markdown("# Text Analysis Dashboard")
with gr.Row():
inp = gr.Textbox(placeholder="Enter text here...", lines=4)
with gr.Column():
out_summary = gr.Textbox(label="Statistics")
out_reverse = gr.Textbox(label="Reversed String")
btn = gr.Button("Analyze")
btn.click(fn=text_analyzer, inputs=inp, outputs=[out_summary, out_reverse])
if __name__ == "__main__":
# Gradio handles localhost binding automatically
demo.launch()
Dash (Plotly) Analytical App
An interactive graph application built with Plotly.
- Start Command:
python main.py - Internal Port:
8050 - Required Packages:
dashpandas
from dash import Dash, html, dcc, callback, Output, Input
import plotly.express as px
import pandas as pd
df = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
"Amount": [4, 1, 2, 2, 4, 5],
"City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})
app = Dash(__name__)
app.layout = html.Div([
html.H1(children='Dashboard', style={'textAlign': 'center'}),
dcc.Dropdown(df.City.unique(), 'SF', id='dropdown-selection'),
dcc.Graph(id='graph-content')
])
@callback(
Output('graph-content', 'figure'),
Input('dropdown-selection', 'value')
)
def update_graph(value):
dff = df[df.City == value]
return px.bar(dff, x='Fruit', y='Amount', color='City', barmode='group')
if __name__ == '__main__':
app.run(debug=False)
NiceGUI Stateful UI
An interactive, stateful to-do list operating via WebSockets.
- Start Command:
python main.py - Internal Port:
8080 - Required Packages:
nicegui
from nicegui import ui
todos = []
def add_todo():
if new_item.value:
todos.append(new_item.value)
new_item.value = ''
todo_list.refresh()
@ui.refreshable
def todo_list():
if not todos:
ui.label('Nothing to do!').classes('text-gray-500 italic')
for idx, item in enumerate(todos):
with ui.row().classes('items-center'):
ui.label(f"• {item}").classes('text-lg')
ui.button('Done', on_click=lambda i=idx: remove_todo(i)).props('flat color=green')
def remove_todo(index):
todos.pop(index)
todo_list.refresh()
ui.markdown('### NiceGUI Todo List')
with ui.row():
new_item = ui.input('New Task').on('keydown.enter', add_todo)
ui.button('Add', on_click=add_todo)
todo_list()
# Fast execution, binding to 0.0.0.0
ui.run(host='0.0.0.0', port=8080, show=False)
Panel (HoloViz) Widget Dashboard
A reactive widget app.
- Start Command:
panel serve main.py - Internal Port:
5006 - Required Packages:
panel
import panel as pn
pn.extension()
text_input = pn.widgets.TextInput(name='Enter your name', value='Python Online')
greeting = pn.bind(lambda name: f'# Hello, {name}!', text_input)
app = pn.Column(
"# Panel Dashboard",
text_input,
greeting
)
app.servable()
Starlette Async Microframework
A lightweight, high-performance async JSON responder.
- Start Command:
python -m uvicorn main:app - Internal Port:
8000 - Required Packages:
starletteuvicorn
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
async def homepage(request):
return JSONResponse({
'hello': 'world',
'framework': 'Starlette',
'is_async': True
})
app = Starlette(debug=True, routes=[
Route('/', homepage),
])
Sanic Fast Async Server
A pure async Python web server that goes fast.
- Start Command:
sanic main:app - Internal Port:
8000 - Required Packages:
sanic
from sanic import Sanic
from sanic.response import text
app = Sanic("MyHelloWorldApp")
@app.get("/")
async def hello_world(request):
return text("Sanic is running at light speed!")
Litestar Modern API
A powerful, lightweight ASGI framework.
- Start Command:
uvicorn main:app - Internal Port:
8000 - Required Packages:
litestaruvicorn
from litestar import Litestar, get
@get("/")
async def hello_world() -> dict[str, str]:
return {"hello": "Litestar"}
app = Litestar(route_handlers=[hello_world])
AIOHTTP Async IO Server
An asynchronous HTTP client/server framework.
- Start Command:
python main.py - Internal Port:
8080 - Required Packages:
aiohttp
from aiohttp import web
async def handle(request):
name = request.match_info.get('name', "Anonymous")
text = f"Hello, {name}! Welcome to AIOHTTP."
return web.Response(text=text)
app = web.Application()
app.add_routes([web.get('/', handle),
web.get('/{name}', handle)])
if __name__ == '__main__':
# Our platform will NAT this loopback bind to the public internet
web.run_app(app, host='127.0.0.1', port=8080)
Tornado Scalable Server
A non-blocking web server capable of handling tens of thousands of open connections.
- Start Command:
python main.py - Internal Port:
8888 - Required Packages:
tornado
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, Tornado world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
Falcon Bare-Metal API
A minimalist framework for building rapid APIs.
- Start Command:
gunicorn main:app - Internal Port:
8000 - Required Packages:
falcongunicorn
import falcon
class QuoteResource:
def on_get(self, req, resp):
quote = {
'quote': 'I\'ve always been more interested in the future than in the past.',
'author': 'Grace Hopper'
}
resp.media = quote
app = falcon.App()
app.add_route('/quote', QuoteResource())
# Will also handle requests to the root
app.add_route('/', QuoteResource())
Pyramid Routing Framework
A general, open-source Python web framework.
- Start Command:
python main.py - Internal Port:
8080 - Required Packages:
pyramidwaitress
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
return Response('Hello from Pyramid!')
if __name__ == '__main__':
with Configurator() as config:
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 8080, app)
server.serve_forever()
Bottle Micro Web-Framework
A fast, simple and lightweight WSGI micro web-framework.
- Start Command:
python main.py - Internal Port:
8080 - Required Packages:
bottle
from bottle import route, run, template
@route('/hello/<name>')
def index(name):
return template('<b>Hello {{name}}</b>!', name=name)
@route('/')
def home():
return "<h1>Bottle running! Try visiting /hello/YourName</h1>"
run(host='0.0.0.0', port=8080)
Masonite Modern MVC
A developer-centric Python web framework.
- Start Command:
python craft serve - Internal Port:
8000 - Required Packages:
masonite
Project Scaffolding Required:
Masonite is not designed for single-file scripts. To use it, open the Pro Terminal, run craft project, and then deploy using the command above.
Reflex Full-Stack Web Apps
Build web apps in pure Python without writing HTML or JS.
- Start Command:
reflex run - Internal Port:
3000 - Required Packages:
reflex
Init Required:
Before running a Reflex app, you must open the Pro Terminal and run reflex init to generate the project structure.
import reflex as rx
class State(rx.State):
count: int = 0
def increment(self):
self.count += 1
def decrement(self):
self.count -= 1
def index():
return rx.vstack(
rx.heading("Reflex Counter"),
rx.hstack(
rx.button("Decrement", on_click=State.decrement, color_scheme="red"),
rx.heading(State.count, font_size="2em"),
rx.button("Increment", on_click=State.increment, color_scheme="green"),
),
padding="50px"
)
app = rx.App()
app.add_page(index)
Flet Flutter for Python
Build interactive multi-user web apps.
- Start Command:
flet run main.py --web --port 8000 - Internal Port:
8000 - Required Packages:
flet
Web Mode: Flet defaults to desktop mode. The --web flag in the Start Command is required to serve it to the browser.
import flet as ft
def main(page: ft.Page):
page.title = "Flet Counter"
page.vertical_alignment = ft.MainAxisAlignment.CENTER
txt_number = ft.TextField(value="0", text_align=ft.TextAlign.RIGHT, width=100)
def minus_click(e):
txt_number.value = str(int(txt_number.value) - 1)
page.update()
def plus_click(e):
txt_number.value = str(int(txt_number.value) + 1)
page.update()
page.add(
ft.Row(
[
ft.IconButton(ft.icons.REMOVE, on_click=minus_click),
txt_number,
ft.IconButton(ft.icons.ADD, on_click=plus_click),
],
alignment=ft.MainAxisAlignment.CENTER,
)
)
# When using 'flet run --web', view=ft.AppView.WEB_BROWSER is inferred.
ft.app(target=main)
Anvil Uplink Script
Connect your Python Online server scripts to your visual Anvil UI using the Uplink connection.
- Start Command:
python main.py - Internal Port:
None (Runs as Daemon) - Required Packages:
anvil-uplink
Note: If you are using Anvil Uplink, you do not need to "Deploy" a web server. Simply run this script in a Pro Terminal, and it will communicate securely outbound.
import anvil.server
# Replace with your actual Uplink key from the Anvil IDE
UPLINK_KEY = "your-uplink-key-here"
anvil.server.connect(UPLINK_KEY)
@anvil.server.callable
def process_data(name):
print(f"Received request from Anvil UI for: {name}")
return f"Hello {name}, your data was processed on a secure Linux container!"
print("Uplink active. Waiting for Anvil requests...")
anvil.server.wait_forever()
Raw Socket Low-Level Network
A foundational TCP socket server using Python's standard library.
- Start Command:
python main.py - Internal Port:
8000 - Required Packages:
None
import socket
HOST = '127.0.0.1'
PORT = 8000
# Create a socket object
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
print(f"Raw socket listening on port {PORT}...")
while True:
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
# Receive data
data = conn.recv(1024)
if not data:
break
# Send HTTP Response
http_response = (
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Hello from a raw TCP socket!"
)
conn.sendall(http_response.encode('utf-8'))