13: CSS/JS/Images Files With Static Assets
Of course the Web is more than just markup. You need static assets: CSS, JS, and images. Let's point our web app at a directory where Pyramid will serve some static assets.
- Publish a directory of static assets at a URL.
- Use Pyramid to help generate URLs to files in that directory.
First we copy the results of the
$ cd ..; cp -r view_classes static_assets; cd static_assets $ $VENV/bin/pip install -e .
We add a call
We can add a CSS link in the
<head>of our template at
Add a CSS file at
Make sure we haven't broken any existing code by running the tests:
$ $VENV/bin/py.test tutorial/tests.py -q .... 4 passed in 0.50 seconds
Run your Pyramid application with:
$ $VENV/bin/pserve development.ini --reload
Open http://localhost:6543/ in your browser and note the new font.
We changed our WSGI application to map requests under
http://localhost:6543/static/ to files and directories inside a
directory inside our
tutorial package. This directory contained
We linked to the CSS in our template. We could have hard-coded this link to
/static/app.css. But what if the site is later moved under
/somesite/static/? Or perhaps the web developer changes the arrangement on
disk? Pyramid gives a helper that provides flexibility on URL generation:
This matches the
path='tutorial:static' in our
registration. By using
request.static_url to generate the full URL to the
static assets, you both ensure you stay in sync with the configuration and gain
refactoring flexibility later.
- There is also a
request.static_pathAPI. How does this differ from