36.4. BASIC LAYOUT
36.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. Our application uses __init__.py as both a package marker, as well as to contain application configuration code.
When you run the application using the pserve command using the development.ini generated config file, the application configuration points at a Setuptools entry point described as egg:tutorial. In our application, because the application’s setup.py file says so, this entry point happens to be the main function within the file named __init__.py:
1 |
from pyramid.config import Configurator |
2 |
from pyramid_zodbconn import get_connection |
3 |
from .models import appmaker |
4 |
|
5 |
def root_factory(request): |
6 |
conn = get_connection(request) |
7return appmaker(conn.root())
8
9 def main(global_config, **settings):
10""" This function returns a Pyramid WSGI application.
11"""
12config = Configurator(root_factory=root_factory, settings=settings)
13config.add_static_view(’static’, ’static’, cache_max_age=3600)
14config.scan()
15return config.make_wsgi_app()
1.Lines 1-3. Perform some dependency imports.
2.Lines 5-7 Define a root factory for our Pyramid application.
3.Line 12. We construct a Configurator with a root factory and the settings keywords parsed by PasteDeploy. The root factory is named root_factory.
4.Line 13. Register a ‘static view’ which answers requests which start with with URL path /static using the pyramid.config.Configurator.add_static_view method(). This statement registers a view that will serve up static assets, such as CSS and image files, for us, in this case, at http://localhost:6543/static/ and below. The first argument is the “name” static, which indicates that the URL path prefix of the view will be /static. the The second argument of this tag is the “path”, which is a relative asset specification, so it finds the resources it should serve within the static directory inside the tutorial package. The scaffold could have alternately used an absolute asset specification as the path (tutorial:static) but it does not.