A lightweight ASGI framework/toolkit for building async web services in Python with WebSocket support, background tasks, and comprehensive middleware.
Use Starlette to build lightweight, high-performance async web applications and APIs in Python using the ASGI standard.
This skill helps you scaffold and build web applications using Starlette, a lightweight ASGI framework. Starlette provides the foundation for building async web services with features like WebSocket support, background tasks, middleware, and more.
Install Starlette and an ASGI server (like uvicorn):
```bash
pip install starlette uvicorn
```
For all optional dependencies:
```bash
pip install starlette[full]
```
Create a new file `main.py` with a simple Starlette app:
```python
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
async def homepage(request):
return JSONResponse({'hello': 'world'})
routes = [
Route("/", endpoint=homepage)
]
app = Starlette(debug=True, routes=routes)
```
Start the development server:
```bash
uvicorn main:app --reload
```
The `--reload` flag enables auto-reloading on code changes.
Expand your application with more endpoints:
```python
from starlette.responses import PlainTextResponse
async def about(request):
return PlainTextResponse('About page')
async def user_profile(request):
username = request.path_params['username']
return JSONResponse({'user': username})
routes = [
Route("/", endpoint=homepage),
Route("/about", endpoint=about),
Route("/users/{username}", endpoint=user_profile),
]
```
Include middleware for common functionality:
```python
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.gzip import GZipMiddleware
middleware = [
Middleware(CORSMiddleware, allow_origins=['*']),
Middleware(GZipMiddleware, minimum_size=1000),
]
app = Starlette(debug=True, routes=routes, middleware=middleware)
```
Create WebSocket endpoints:
```python
from starlette.websockets import WebSocket
async def websocket_endpoint(websocket):
await websocket.accept()
await websocket.send_text('Hello, WebSocket!')
await websocket.close()
from starlette.routing import WebSocketRoute
routes = [
Route("/", endpoint=homepage),
WebSocketRoute("/ws", endpoint=websocket_endpoint),
]
```
Add background tasks to run after sending a response:
```python
from starlette.background import BackgroundTask
def cleanup_task(name: str):
# Perform cleanup
print(f"Cleaning up {name}")
async def endpoint(request):
task = BackgroundTask(cleanup_task, name="example")
return JSONResponse(
{'status': 'success'},
background=task
)
```
Use Starlette components independently:
```python
from starlette.responses import PlainTextResponse
async def app(scope, receive, send):
assert scope['type'] == 'http'
response = PlainTextResponse('Hello, world!')
await response(scope, receive, send)
```
1. Use async/await for all route handlers
2. Enable debug mode only in development (`debug=True`)
3. Use type hints for better IDE support
4. Leverage middleware for cross-cutting concerns
5. Use the TestClient for comprehensive testing
6. Consider using Starlette with FastAPI for automatic API documentation
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/starlette-asgi-framework/raw