- •Front Matter
- •Copyright, Trademarks, and Attributions
- •Attributions
- •Print Production
- •Contacting The Publisher
- •HTML Version and Source Code
- •Typographical Conventions
- •Author Introduction
- •Audience
- •Book Content
- •The Genesis of repoze.bfg
- •The Genesis of Pyramid
- •Thanks
- •Pyramid Introduction
- •What Makes Pyramid Unique
- •URL generation
- •Debug Toolbar
- •Debugging settings
- •Class-based and function-based views
- •Extensible templating
- •Rendered views can return dictionaries
- •Event system
- •Built-in internationalization
- •HTTP caching
- •Sessions
- •Speed
- •Exception views
- •No singletons
- •View predicates and many views per route
- •Transaction management
- •Flexible authentication and authorization
- •Traversal
- •Tweens
- •View response adapters
- •Testing
- •Support
- •Documentation
- •What Is The Pylons Project?
- •Pyramid and Other Web Frameworks
- •Installing Pyramid
- •Before You Install
- •Installing Pyramid on a UNIX System
- •Installing the virtualenv Package
- •Creating the Virtual Python Environment
- •Installing Pyramid Into the Virtual Python Environment
- •Installing Pyramid on a Windows System
- •What Gets Installed
- •Application Configuration
- •Summary
- •Creating Your First Pyramid Application
- •Hello World
- •Imports
- •View Callable Declarations
- •WSGI Application Creation
- •WSGI Application Serving
- •Conclusion
- •References
- •Creating a Pyramid Project
- •Scaffolds Included with Pyramid
- •Creating the Project
- •Installing your Newly Created Project for Development
- •Running The Tests For Your Application
- •Running The Project Application
- •Reloading Code
- •Viewing the Application
- •The Debug Toolbar
- •The Project Structure
- •The MyProject Project
- •development.ini
- •production.ini
- •MANIFEST.in
- •setup.py
- •setup.cfg
- •The myproject Package
- •__init__.py
- •views.py
- •static
- •templates/mytemplate.pt
- •tests.py
- •Modifying Package Structure
- •Using the Interactive Shell
- •What Is This pserve Thing
- •Using an Alternate WSGI Server
- •Startup
- •The Startup Process
- •Deployment Settings
- •Request Processing
- •URL Dispatch
- •High-Level Operational Overview
- •Route Pattern Syntax
- •Route Declaration Ordering
- •Route Matching
- •The Matchdict
- •The Matched Route
- •Routing Examples
- •Example 1
- •Example 2
- •Example 3
- •Matching the Root URL
- •Generating Route URLs
- •Static Routes
- •Debugging Route Matching
- •Using a Route Prefix to Compose Applications
- •Custom Route Predicates
- •Route Factories
- •Using Pyramid Security With URL Dispatch
- •Route View Callable Registration and Lookup Details
- •References
- •Views
- •View Callables
- •View Callable Responses
- •Using Special Exceptions In View Callables
- •HTTP Exceptions
- •How Pyramid Uses HTTP Exceptions
- •Custom Exception Views
- •Using a View Callable to Do an HTTP Redirect
- •Handling Form Submissions in View Callables (Unicode and Character Set Issues)
- •Alternate View Callable Argument/Calling Conventions
- •Renderers
- •Writing View Callables Which Use a Renderer
- •Built-In Renderers
- •string: String Renderer
- •json: JSON Renderer
- •JSONP Renderer
- •*.pt or *.txt: Chameleon Template Renderers
- •*.mak or *.mako: Mako Template Renderer
- •Varying Attributes of Rendered Responses
- •Deprecated Mechanism to Vary Attributes of Rendered Responses
- •Adding and Changing Renderers
- •Adding a New Renderer
- •Changing an Existing Renderer
- •Overriding A Renderer At Runtime
- •Templates
- •Using Templates Directly
- •System Values Used During Rendering
- •Chameleon ZPT Templates
- •A Sample ZPT Template
- •Using ZPT Macros in Pyramid
- •Templating with Chameleon Text Templates
- •Side Effects of Rendering a Chameleon Template
- •Debugging Templates
- •Chameleon Template Internationalization
- •Templating With Mako Templates
- •A Sample Mako Template
- •Automatically Reloading Templates
- •Available Add-On Template System Bindings
- •View Configuration
- •Mapping a Resource or URL Pattern to a View Callable
- •@view_defaults Class Decorator
- •NotFound Errors
- •Debugging View Configuration
- •Static Assets
- •Serving Static Assets
- •Generating Static Asset URLs
- •Advanced: Serving Static Assets Using a View Callable
- •Root-Relative Custom Static View (URL Dispatch Only)
- •Overriding Assets
- •The override_asset API
- •Request and Response Objects
- •Request
- •Special Attributes Added to the Request by Pyramid
- •URLs
- •Methods
- •Unicode
- •Multidict
- •Dealing With A JSON-Encoded Request Body
- •Cleaning Up After a Request
- •More Details
- •Response
- •Headers
- •Instantiating the Response
- •Exception Responses
- •More Details
- •Sessions
- •Using The Default Session Factory
- •Using a Session Object
- •Using Alternate Session Factories
- •Creating Your Own Session Factory
- •Flash Messages
- •Using the session.flash Method
- •Using the session.pop_flash Method
- •Using the session.peek_flash Method
- •Preventing Cross-Site Request Forgery Attacks
- •Using the session.get_csrf_token Method
- •Using the session.new_csrf_token Method
- •Using Events
- •An Example
- •Reloading Templates
- •Reloading Assets
- •Debugging Authorization
- •Debugging Not Found Errors
- •Debugging Route Matching
- •Preventing HTTP Caching
- •Debugging All
- •Reloading All
- •Default Locale Name
- •Including Packages
- •pyramid.includes vs. pyramid.config.Configurator.include()
- •Mako Template Render Settings
- •Mako Directories
- •Mako Module Directory
- •Mako Input Encoding
- •Mako Error Handler
- •Mako Default Filters
- •Mako Import
- •Mako Preprocessor
- •Examples
- •Understanding the Distinction Between reload_templates and reload_assets
- •Adding A Custom Setting
- •Logging
- •Sending Logging Messages
- •Filtering log messages
- •Logging Exceptions
- •PasteDeploy Configuration Files
- •PasteDeploy
- •Entry Points and PasteDeploy .ini Files
- •[DEFAULTS] Section of a PasteDeploy .ini File
- •Command-Line Pyramid
- •Displaying Matching Views for a Given URL
- •The Interactive Shell
- •Extending the Shell
- •IPython or bpython
- •Displaying All Application Routes
- •Invoking a Request
- •Writing a Script
- •Changing the Request
- •Cleanup
- •Setting Up Logging
- •Making Your Script into a Console Script
- •Internationalization and Localization
- •Creating a Translation String
- •Using The TranslationString Class
- •Using the TranslationStringFactory Class
- •Working With gettext Translation Files
- •Installing Babel and Lingua
- •Extracting Messages from Code and Templates
- •Initializing a Message Catalog File
- •Updating a Catalog File
- •Compiling a Message Catalog File
- •Using a Localizer
- •Performing a Translation
- •Performing a Pluralization
- •Obtaining the Locale Name for a Request
- •Performing Date Formatting and Currency Formatting
- •Chameleon Template Support for Translation Strings
- •Mako Pyramid I18N Support
- •Localization-Related Deployment Settings
- •Activating Translation
- •Adding a Translation Directory
- •Setting the Locale
- •Locale Negotiators
- •The Default Locale Negotiator
- •Using a Custom Locale Negotiator
- •Virtual Hosting
- •Virtual Root Support
- •Further Documentation and Examples
- •Test Set Up and Tear Down
- •What?
- •Using the Configurator and pyramid.testing APIs in Unit Tests
- •Creating Integration Tests
- •Creating Functional Tests
- •Resources
- •Location-Aware Resources
- •Generating The URL Of A Resource
- •Overriding Resource URL Generation
- •Generating the Path To a Resource
- •Finding a Resource by Path
- •Obtaining the Lineage of a Resource
- •Determining if a Resource is In The Lineage of Another Resource
- •Finding the Root Resource
- •Resources Which Implement Interfaces
- •Finding a Resource With a Class or Interface in Lineage
- •Pyramid API Functions That Act Against Resources
- •Much Ado About Traversal
- •URL Dispatch
- •Historical Refresher
- •Traversal (aka Resource Location)
- •View Lookup
- •Use Cases
- •Traversal
- •Traversal Details
- •The Resource Tree
- •The Traversal Algorithm
- •A Description of The Traversal Algorithm
- •Traversal Algorithm Examples
- •References
- •Security
- •Enabling an Authorization Policy
- •Enabling an Authorization Policy Imperatively
- •Protecting Views with Permissions
- •Setting a Default Permission
- •Assigning ACLs to your Resource Objects
- •Elements of an ACL
- •Special Principal Names
- •Special Permissions
- •Special ACEs
- •ACL Inheritance and Location-Awareness
- •Changing the Forbidden View
- •Debugging View Authorization Failures
- •Debugging Imperative Authorization Failures
- •Creating Your Own Authentication Policy
- •Creating Your Own Authorization Policy
- •Combining Traversal and URL Dispatch
- •A Review of Non-Hybrid Applications
- •URL Dispatch Only
- •Traversal Only
- •Hybrid Applications
- •The Root Object for a Route Match
- •Using *traverse In a Route Pattern
- •Using *subpath in a Route Pattern
- •Corner Cases
- •Registering a Default View for a Route That Has a view Attribute
- •Using Hooks
- •Changing the Not Found View
- •Changing the Forbidden View
- •Changing the Request Factory
- •Using The Before Render Event
- •Adding Renderer Globals (Deprecated)
- •Using Response Callbacks
- •Using Finished Callbacks
- •Changing the Traverser
- •Changing How pyramid.request.Request.resource_url() Generates a URL
- •Changing How Pyramid Treats View Responses
- •Using a View Mapper
- •Creating a Tween Factory
- •Registering an Implicit Tween Factory
- •Suggesting Implicit Tween Ordering
- •Explicit Tween Ordering
- •Displaying Tween Ordering
- •Pyramid Configuration Introspection
- •Using the Introspector
- •Introspectable Objects
- •Pyramid Introspection Categories
- •Introspection in the Toolbar
- •Disabling Introspection
- •Rules for Building An Extensible Application
- •Fundamental Plugpoints
- •Extending an Existing Application
- •Extending the Application
- •Overriding Views
- •Overriding Routes
- •Overriding Assets
- •Advanced Configuration
- •Two-Phase Configuration
- •Using config.action in a Directive
- •Adding Configuration Introspection
- •Introspectable Relationships
- •Thread Locals
- •Why and How Pyramid Uses Thread Local Variables
- •Using the Zope Component Architecture in Pyramid
- •Using the ZCA Global API in a Pyramid Application
- •Disusing the Global ZCA API
- •Enabling the ZCA Global API by Using hook_zca
- •Enabling the ZCA Global API by Using The ZCA Global Registry
- •Background
- •Design
- •Overall
- •Models
- •Views
- •Security
- •Summary
- •Installation
- •Preparation
- •Make a Project
- •Run the Tests
- •Expose Test Coverage Information
- •Start the Application
- •Visit the Application in a Browser
- •Decisions the zodb Scaffold Has Made For You
- •Basic Layout
- •Resources and Models with models.py
- •Views With views.py
- •Defining the Domain Model
- •Delete the Database
- •Edit models.py
- •Look at the Result of Our Edits to models.py
- •View the Application in a Browser
- •Defining Views
- •Declaring Dependencies in Our setup.py File
- •Adding View Functions
- •Viewing the Result of all Our Edits to views.py
- •Adding Templates
- •Viewing the Application in a Browser
- •Adding Authorization
- •Add Authentication and Authorization Policies
- •Add security.py
- •Give Our Root Resource an ACL
- •Add Login and Logout Views
- •Change Existing Views
- •Add permission Declarations to our view_config Decorators
- •Add the login.pt Template
- •Change view.pt and edit.pt
- •See Our Changes To views.py and our Templates
- •View the Application in a Browser
- •Adding Tests
- •Test the Models
- •Test the Views
- •Functional tests
- •View the results of all our edits to tests.py
- •Run the Tests
- •Distributing Your Application
- •SQLAlchemy + URL Dispatch Wiki Tutorial
- •Background
- •Design
- •Overall
- •Models
- •Views
- •Security
- •Summary
- •Installation
- •Preparation
- •Making a Project
- •Running the Tests
- •Exposing Test Coverage Information
- •Initializing the Database
- •Starting the Application
- •Decisions the alchemy Scaffold Has Made For You
- •Basic Layout
- •View Declarations via views.py
- •Content Models with models.py
- •Making Edits to models.py
- •Changing scripts/initializedb.py
- •Reinitializing the Database
- •Viewing the Application in a Browser
- •Defining Views
- •Declaring Dependencies in Our setup.py File
- •Running setup.py develop
- •Changing the views.py File
- •Adding Templates
- •Adding Routes to __init__.py
- •Viewing the Application in a Browser
- •Adding Authorization
- •Adding A Root Factory
- •Add an Authorization Policy and an Authentication Policy
- •Adding an authentication policy callback
- •Adding Login and Logout Views
- •Changing Existing Views
- •Adding the login.pt Template
- •Seeing Our Changes To views.py and our Templates
- •Viewing the Application in a Browser
- •Adding Tests
- •Testing the Models
- •Testing the Views
- •Functional tests
- •Viewing the results of all our edits to tests.py
- •Running the Tests
- •Distributing Your Application
- •Converting a repoze.bfg Application to Pyramid
- •Running a Pyramid Application under mod_wsgi
- •pyramid.authorization
- •pyramid.authentication
- •Authentication Policies
- •Helper Classes
- •pyramid.chameleon_text
- •pyramid.chameleon_zpt
- •pyramid.config
- •pyramid.events
- •Functions
- •Event Types
- •pyramid.exceptions
- •pyramid.httpexceptions
- •HTTP Exceptions
- •pyramid.i18n
- •pyramid.interfaces
- •Event-Related Interfaces
- •Other Interfaces
- •pyramid.location
- •pyramid.paster
- •pyramid.registry
- •pyramid.renderers
- •pyramid.request
- •pyramid.response
- •Functions
- •pyramid.scripting
- •pyramid.security
- •Authentication API Functions
- •Authorization API Functions
- •Constants
- •Return Values
- •pyramid.settings
- •pyramid.testing
- •pyramid.threadlocal
- •pyramid.traversal
- •pyramid.url
- •pyramid.view
- •pyramid.wsgi
- •Glossary
37.4. BASIC LAYOUT
37.4 Basic Layout
The starter files generated by the alchemy scaffold are very basic, but they provide a good orientation for the high-level patterns common to most url dispatch -based Pyramid projects.
The source code for this tutorial stage can be browsed at http://github.com/Pylons/pyramid/tree/1.3- branch/docs/tutorials/wiki2/src/basiclayout/.
37.4.1 Application Configuration with __init__.py
A directory on disk can be turned into a Python package by containing an __init__.py file. Even if empty, this marks a directory as a Python package. We use __init__.py both as a marker indicating the directory it’s contained within is a package, and to contain configuration code.
Open tutorial/tutorial/__init__.py. It should already contain the following:
1 |
from pyramid.config import Configurator |
2 |
from sqlalchemy import engine_from_config |
3 |
|
4 |
from .models import DBSession |
5 |
|
6 |
def main(global_config, **settings): |
7""" This function returns a Pyramid WSGI application.
8"""
9engine = engine_from_config(settings, ’sqlalchemy.’)
10DBSession.configure(bind=engine)
11config = Configurator(settings=settings)
12config.add_static_view(’static’, ’static’, cache_max_age=3600)
13config.add_route(’home’, ’/’)
14config.scan()
15return config.make_wsgi_app()
Let’s go over this piece-by-piece. First, we need some imports to support later code:
1
2
3
4
from pyramid.config import Configurator from sqlalchemy import engine_from_config
from .models import DBSession
__init__.py defines a function named main. Here is the entirety of the main function we’ve defined in our __init__.py:
449
37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL
1 def main(global_config, **settings):
2""" This function returns a Pyramid WSGI application.
3"""
4engine = engine_from_config(settings, ’sqlalchemy.’)
5DBSession.configure(bind=engine)
6config = Configurator(settings=settings)
7 config.add_static_view(’static’, ’static’, cache_max_age=3600)
8config.add_route(’home’, ’/’)
9config.scan()
10 return config.make_wsgi_app()
When you invoke the pserve development.ini command, the main function above is executed. It accepts some settings and returns a WSGI application. (See Startup for more about pserve.)
The main function first creates a SQLAlchemy database engine using engine_from_config from the sqlalchemy. prefixed settings in the development.ini file’s [app:main] section. This will be a URI (something like sqlite://):
1engine = engine_from_config(settings, ’sqlalchemy.’)
main then initializes our SQL database using SQLAlchemy, passing it the engine:
DBSession.configure(bind=engine)
The next step of main is to construct a Configurator object:
config = Configurator(settings=settings)
settings is passed to the Configurator as a keyword argument with the dictionary values passed as the **settings argument. This will be a dictionary of settings parsed from the .ini file, which contains deployment-related values such as pyramid.reload_templates, db_string, etc.
main now calls pyramid.config.Configurator.add_static_view() with two arguments: static (the name), and static (the path):
config.add_static_view(’static’, ’static’, cache_max_age=3600)
450
37.4. BASIC LAYOUT
This registers a static resource view which will match any URL that starts with the prefix /static (by virtue of the first argument to add_static view). This will serve up static resources for us from within the static directory of our tutorial package, in this case, via http://localhost:6543/static/ and below (by virtue of the second argument to add_static_view). With this declaration, we’re saying that any URL that starts with /static should go to the static view; any remainder of its path (e.g. the /foo in /static/foo) will be used to compose a path to a static file resource, such as a CSS file.
Using the configurator main also registers a route configuration via the pyramid.config.Configurator.add_route() method that will be used when the URL is /:
config.add_route(’home’, ’/’)
Since this route has a pattern equalling / it is the route that will be matched when the URL / is visted, e.g. http://localhost:6543/.
main next calls the scan method of the configurator, which will recursively scan our tutorial package, looking for @view_config (and other special) decorators. When it finds a @view_config decorator, a view configuration will be registered, which will allow one of our application URLs to be mapped to some code.
config.scan()
Finally, main is finished configuring things, so it uses the pyramid.config.Configurator.make_wsgi_app() method to return a WSGI application:
return config.make_wsgi_app()
37.4.2 View Declarations via views.py
Mapping a route to code that will be executed when a match for the route’s pattern occurs is done by registering a view configuration. Our application uses the pyramid.view.view_config() decorator to map view callables to each route, thereby mapping URL patterns to code.
Open tutorial/tutorial/views.py. It should already contain the following:
451
37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL
1 from pyramid.view import view_config
2
3 from .models import (
4DBSession,
5MyModel,
6)
7
8 @view_config(route_name=’home’, renderer=’templates/mytemplate.pt’) 9 def my_view(request):
10one = DBSession.query(MyModel).filter(MyModel.name==’one’).first()
11return {’one’:one, ’project’:’tutorial’}
The important part here is that the @view_config decorator associates the function it decorates (my_view) with a view configuration, consisting of:
•a route_name (home)
•a renderer, which is a template from the templates subdirectory of the package.
When the pattern associated with the home view is matched during a request, my_view() will be executed. my_view() returns a dictionary; the renderer will use the templates/mytemplate.pt template to create a response based on the values in the dictionary.
Note that my_view() accepts a single argument named request. This is the standard call signature for a Pyramid view callable.
Remember in our __init__.py when we executed the pyramid.config.Configurator.scan() method, i.e. config.scan()? The purpose of calling the scan method was to find and process this @view_config decorator in order to create a view configuration within our application. Without being processed by scan, the decorator effectively does nothing. @view_config is inert without being detected via a scan.
37.4.3 Content Models with models.py
In a SQLAlchemy-based application, a model object is an object composed by querying the SQL database. The models.py file is where the alchemy scaffold put the classes that implement our models.
Open tutorial/tutorial/models.py. It should already contain the following:
452
37.4. BASIC LAYOUT
1 from sqlalchemy import (
2Column,
3Integer,
4Text,
5)
6
7 from sqlalchemy.ext.declarative import declarative_base
8
9 from sqlalchemy.orm import (
10scoped_session,
11sessionmaker,
12)
13
14 from zope.sqlalchemy import ZopeTransactionExtension
15
16DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
17Base = declarative_base()
18
19class MyModel(Base):
20__tablename__ = ’models’
21id = Column(Integer, primary_key=True)
22name = Column(Text, unique=True)
23value = Column(Integer)
24
25def __init__(self, name, value):
26self.name = name
27self.value = value
Let’s examine this in detail. First, we need some imports to support later code:
1 from sqlalchemy import (
2Column,
3Integer,
4Text,
5)
6
7 from sqlalchemy.ext.declarative import declarative_base
8
9 from sqlalchemy.orm import (
10scoped_session,
11sessionmaker,
12)
13
14 from zope.sqlalchemy import ZopeTransactionExtension
453
37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL
Next we set up a SQLAlchemy “DBSession” object:
1 DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
scoped_session and sessionmaker are standard SQLAlchemy helpers. scoped_session allows us to access our database connection globally. sessionmaker creates a database session object. We pass to sessionmaker the extension=ZopeTransactionExtension() extension option in order to allow the system to automatically manage datbase transactions. With ZopeTransactionExtension activated, our application will automatically issue a transaction commit after every request unless an exception is raised, in which case the transaction will be aborted.
We also need to create a declarative Base object to use as a base class for our model:
Base = declarative_base()
Our model classes will inherit from this Base class so they can be associated with our particular database connection.
To give a simple example of a model class, we define one named MyModel:
1 class MyModel(Base):
2__tablename__ = ’models’
3 id = Column(Integer, primary_key=True) 4 name = Column(Text, unique=True)
5value = Column(Integer)
6
7 def __init__(self, name, value):
8self.name = name
9self.value = value
Our example model has an __init__ that takes a two arguments (name, and value). It stores these values as self.name and self.value within the __init__ function itself. The MyModel class also has a __tablename__ attribute. This informs SQLAlchemy which table to use to store the data representing instances of this class.
That’s about all there is to it to models, views, and initialization code in our stock application.
37.5 Defining the Domain Model
The first change we’ll make to our stock pcreate-generated application will be to define a domain model constructor representing a wiki page. We’ll do this inside our models.py file.
The source code for this tutorial stage can be browsed at http://github.com/Pylons/pyramid/tree/1.3- branch/docs/tutorials/wiki2/src/models/.
454