Introduction to Bobo: A Lightweight Python Microframework
If you’re looking for a minimalistic and efficient Python web framework, Bobo is an excellent choice. Bobo is tailored specifically for building web applications quickly, with its simple and intuitive API for creating web routes and handling HTTP requests. In this guide, we’ll explore the core features of Bobo and provide dozens of API examples, alongside a complete functional app example at the end.
Getting Started with Bobo
Before diving into the API, ensure you have Bobo installed. You can install it via pip:
pip install bobo
Once installed, you’re ready to start building. Bobo’s philosophy heavily relies on Python decorators to create routes and methods that respond to HTTP requests.
Bobo API Overview with Examples
1. Creating Your First Bobo Route
Define your application and expose routes using the @bobo.query
decorator:
import bobo @bobo.query("/") def hello(): return "Welcome to Bobo!"
2. Handling GET Parameters
You can accept input parameters directly from the URL:
@bobo.query("/greet") def greet(name): return f"Hello, {name}!"
Example: Accessing /greet?name=John
will return “Hello, John!”
3. Serving JSON Responses
Bobo allows you to send JSON responses easily:
import json @bobo.query("/data") def data(): return bobo.Response(json.dumps({"key": "value"}), content_type="application/json")
4. Handling POST Requests
Use @bobo.post
to process POST requests:
@bobo.post("/submit") def submit(body): return f"Data received: {body}"
5. Adding Middleware
Middleware can process requests and responses globally before they reach routes:
def log_middleware(next_app, environ, start_response): print(f"Request made to: {environ['PATH_INFO']}") return next_app(environ, start_response) @bobo.scan_factory def create_app(): return bobo.application(middleware=log_middleware)
6. Static File Serving
Bobo can serve static files directly from disk:
@bobo.query('/static/') def static_files(path): with open(f'./static/{path}', 'rb') as f: return bobo.Response(f.read(), content_type='application/octet-stream')
7. URL Routing with Variables
Routes can include variable segments:
@bobo.query('/user/') def user_profile(user_id): return f"User ID: {user_id}"
Complete App Example: To-Do Manager
Here’s a complete example of a small to-do application using Bobo:
import bobo todos = [] @bobo.query("/") def home(): return "Bobo To-Do Manager" @bobo.query("/tasks") def list_tasks(): return ", ".join(todos) if todos else "No tasks yet" @bobo.post("/tasks") def add_task(body): todos.append(body) return f"Task added: {body}" @bobo.post("/tasks/") def delete_task(task_id: int): if 0 <= task_id < len(todos): removed = todos.pop(task_id) return f"Task removed: {removed}" return "Invalid task ID"
Conclusion
Bobo is a remarkably minimalistic tool, enabling developers to build web services or APIs with minimal overhead. Combined with Python’s simplicity, it’s perfect for small, efficient projects.