| 212 | |
| 213 | Now let's add some initial content to the “database”. You'll need to stop the CherryPy server to do that. Then, in the terminal, from the tutorial directory, launch the interactive Python shell, and execute the following code: |
| 214 | |
| 215 | {{{ |
| 216 | #!pycon |
| 217 | >>> import pickle |
| 218 | >>> from geddit.model import * |
| 219 | >>> data = pickle.load(open('geddit.db', 'rb')) |
| 220 | >>> data |
| 221 | [] |
| 222 | >>> s1 = Submission(username='joe', url='http://example.org/', title='An example') |
| 223 | >>> s2 = Submission(username='annie', url='http://reddit.com/', title='The real thing') |
| 224 | >>> data.append(s1) |
| 225 | >>> data.append(s2) |
| 226 | >>> s1.add_comment(username='jack', content='Bla bla bla') |
| 227 | >>> s1.comments[0].add_reply(username='joe', content='Bla blabla bla bla bla') |
| 228 | >>> pickle.dump(data, open('geddit.db', 'wb')) |
| 229 | >>> ^D |
| 230 | }}} |
| 231 | |
| 232 | You should now have two submissions in the pickle file, with the first submission having a comment, as well as a reply to that comment. Restart the CherryPy server by running: |
| 233 | |
| 234 | {{{ |
| 235 | $ PYTHONPATH=. python geddit/controller.py geddit.db |
| 236 | }}} |
| 237 | |
| 238 | Now let's change the `Root.index()` method to pass the submissions list to the template: |
| 239 | |
| 240 | {{{ |
| 241 | #!python |
| 242 | @cherrypy.expose |
| 243 | def index(self): |
| 244 | tmpl = loader.load('index.html') |
| 245 | stream = tmpl.generate(submissions=self.data) |
| 246 | return stream.render('html', doctype='html') |
| 247 | }}} |
| 248 | |
| 249 | And finally, we'll modify the `index.html` template so that it displays the submissions in a simple ordered list. While we're at it, let's add a link to submit new items: |
| 250 | |
| 251 | {{{ |
| 252 | #!genshi |
| 253 | <html xmlns="http://www.w3.org/1999/xhtml" |
| 254 | xmlns:py="http://genshi.edgewall.org/"> |
| 255 | <head> |
| 256 | <title>Geddit</title> |
| 257 | </head> |
| 258 | <body> |
| 259 | <h1>Geddit</h1> |
| 260 | |
| 261 | <p><a href="/submit/">Submit new link</a></p> |
| 262 | |
| 263 | <ol py:if="submissions"> |
| 264 | <li py:for="submission in submissions"> |
| 265 | <a href="${submission.url}">${submission.title}</a> |
| 266 | posted by ${submission.username} |
| 267 | at ${submission.time.strftime('%M/%d/%Y %H:%m')} |
| 268 | </li> |
| 269 | </ol> |
| 270 | |
| 271 | </body> |
| 272 | </html> |
| 273 | }}} |
| 274 | |
| 275 | When you reload the page in the browser, you should see a page similar to this: |
| 276 | |
| 277 | [[Image(tutorial01.png)]] |
| 278 | |
| 279 | == Adding a Submission Form == |
| 280 | |
| 281 | In the previous step, we've already added a link to a submission form to the template, but we haven't implemented the logic to handle requests to that link yet. |