Welcome to the ultimate beginner’s guide to the Python Pyramid web framework. Whether you’re transitioning from Flask or Django, or you’re brand‑new to web development, Pyramid offers a flexible, “pay‑only‑what‑you‑use” architecture that scales from simple prototypes to large‑scale applications. In this article we’ll walk through everything you need to get started: installation, project layout, routing, views, templates, static assets, testing, and deployment. By the end, you’ll have a solid foundation to build your first Pyramid app and feel confident exploring its powerful extensions.
Why Choose Pyramid?
Pyramid stands out among Python web frameworks for several reasons:
- Flexibility: Start with a minimal “hello world” and add components only when you need them.
- Scalability: Works equally well for tiny APIs and enterprise‑level services.
- Compatibility: Supports both
WSGIandASGIservers, and integrates smoothly with popular libraries such as SQLAlchemy, Jinja2, and Celery. - Clear Documentation: The official Pyramid docs are thorough, making self‑learning straightforward.
- Community & Ecosystem: A vibrant community provides add‑ons, tutorials, and best‑practice guides.
Getting Started: Installation & Project Setup
1. Prerequisites
Before you dive in, make sure you have the following installed on your development machine:
- Python 3.9 or newer
pip(Python package manager)- Virtual environment tool (
venvorvirtualenv)
2. Create a Virtual Environment
python -m venv venv
source venv/bin/activate # On Windows use: venv\Scripts\activate
3. Install Pyramid
Use pip to install the core framework and a starter template:
pip install "pyramid==2.0" waitress
waitress is a production‑ready WSGI server that works out of the box with Pyramid.
4. Scaffold a New Project
Pyramid provides a convenient command‑line tool called pcreate. Install it and generate a starter project:
pip install pyramid-cookiecutter
pcreate -s starter mypyramidapp
cd mypyramidapp
pip install -e .
The -e . flag installs your app in “editable” mode, allowing you to modify source files without reinstalling.
Understanding the Project Structure
A typical Pyramid project generated by pcreate looks like this:
mypyramidapp/
├── mypyramidapp/
│ ├── __init__.py # Application factory
│ ├── routes.py # URL route definitions
│ ├── views.py # View callables
│ ├── models.py # Database models (optional)
│ └── templates/
│ └── home.jinja2
├── development.ini # Development server config
└── setup.py
Key files:
__init__.py: Contains themainfunction that builds the WSGI app.routes.py: Maps URL patterns to view callables.views.py: Holds the business logic that returns a response.templates/: Stores Jinja2 or Chameleon templates for HTML rendering.development.ini: Configures the server, logging, and debugging options.
Defining Routes and Views
Routing Basics
In Pyramid, a route connects a URL pattern to a view name. Routes are defined in routes.py and added to the configurator in __init__.py:
# mypyramidapp/routes.py
def includeme(config):
config.add_route('home', '/')
config.add_route('hello', '/hello/{name}')
# mypyramidapp/__init__.py
def main(global_config, **settings):
config = Configurator(settings=settings)
config.include('.routes')
config.scan('.views')
return config.make_wsgi_app()
Creating Views
Views are regular Python callables that receive a request object and return a response. They can render templates, return JSON, or perform redirects.
# mypyramidapp/views.py
from pyramid.view import view_config
from pyramid.response import Response
from pyramid.renderers import render_to_response
@view_config(route_name='home', renderer='templates/home.jinja2')
def home_view(request):
return {'project': 'My Pyramid App'}
@view_config(route_name='hello')
def hello_view(request):
name = request.matchdict.get('name', 'World')
return Response(f'Hello, {name}!')
The renderer argument tells Pyramid to automatically render the home.jinja2 template with the dictionary returned from the view.
Working with Templates
Pyramid supports multiple templating engines; Jinja2 is a popular choice for its Django‑like syntax. Install the Jinja2 integration:
pip install pyramid_jinja2
Then enable it in __init__.py:
config.include('pyramid_jinja2')
Example templates/home.jinja2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ project }}</title>
</head>
<body>
<h1>Welcome to {{ project }}!</h1;
<p>This is a minimal Pyramid application.</p>
<a href="{{ request.route_url('hello', name='Pyramid') }}">Say hello</a>
</body>
</html>
Handling Static Assets
Static files such as CSS, JavaScript, and images are served via the static_view helper. Add a static directory to your project and configure it in __init__.py:
# Directory layout
mypyramidapp/
├── static/
│ ├── css/
│ │ └── style.css
│ └── js/
│ └── script.js
# In __init__.py
config.add_static_view(name='static', path='mypyramidapp:static')
Reference assets in your template with {{ request.static_url('mypyramidapp:static/css/style.css') }}.
Adding a Database with SQLAlchemy
Most real‑world apps need persistence. Pyramid integrates cleanly with SQLAlchemy:
pip install sqlalchemy pyramid_sqlalchemy
Define a model in models.py:
# mypyramidapp/models.py
from sqlalchemy import Column, Integer, Text
from . import Base # Base is created in __init__.py
class Article(Base):
__tablename__ = 'articles'
id = Column(Integer, primary_key=True)
title = Column(Text, nullable=False)
content = Column(Text)
Configure the engine and session in __init__.py:
from sqlalchemy import engine_from_config
from .models import Base
def main(global_config, **settings):
config = Configurator(settings=settings)
engine = engine_from_config(settings, 'sqlalchemy.')
Base.metadata.bind = engine
config.registry['dbsession_factory'] = sessionmaker(bind=engine)
# …rest of configuration…
Now you can inject the DB session into views using the request.dbsession attribute.
Testing Your Pyramid Application
Good tests keep your app reliable. Pyramid ships with a testing helper that creates a mock request object:
pip install pytest webtest
Example test for the hello_view:
# tests/test_views.py
from pyramid import testing
def test_hello_view():
request = testing.DummyRequest()
request.matchdict['name'] = 'Tester'
from mypyramidapp.views import hello_view
response = hello_view(request)
assert response.body == b'Hello, Tester!'
Running the Development Server
Use the pserve command with the development.ini file:
pserve development.ini --reload
The --reload flag restarts the server automatically when source files change, making development fast and painless.
Deploying to Production
When you’re ready to go live, follow these steps:
- Choose a WSGI server:
gunicorn,uwsgi, or keep usingwaitressfor simplicity. - Configure environment variables: Set
PYTHONPATH
Leave a Reply