Learning Python Network Programming

(Sean Pound) #1

Applications for the Web


There isn't a "right" approach; it's best to experiment with a few and see what works
best for you. Where a framework has its own engine though, like Django, or is tightly
integrated with an existing engine, like Flask, you'll usually have a smoother run
sticking with what they supply, if you can.


Adding some style


At the moment, our pages look a little plain. Let's add some style. We'll do this by
including a static CSS document, but the same approach can be used to include
images and other static content. The code for this section can be found in the
3-style folder in this chapter's source code.


First create a new static folder in your project folder, and in there create a new text
file called style.css. Save the following to it:


body { font-family: Sans-Serif; background: white; }
h1 { color: #38b; }
pre { margin: 0px; font-size: 1.2em; }
.menuitem { float: left; margin: 1px 1px 0px 0px; }
.link { width: 100px; padding: 5px 25px; background: #eee; }
.link a { text-decoration: none; color: #555; }
.link a:hover { font-weight: bold; color: #38b; }

Next update the section of your base.html file to look like this:


<head>
<title>Python Builtins Docstrings</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.
css') }}"/>
</head>

Note the third and forth lines in the preceding code—that is the tag—should
be a single line in your code. Try your web application in the browser again and
notice that it looks (hopefully) a little more up to date.


Here we've just added a stylesheet to our boilerplate HTML in base.html, adding
a tag pointing to our static/style.css file. We use Flask's url_for()
function for this. The url_for() function returns paths to named parts of our URL
space. In this case, it's the special static folder, which by default Flask looks for in
the root of our web application. Another thing we can use url_for() for is to get the
paths of our view functions, for example, url_for('index') would return /.

Free download pdf