Id 11685
Id 11685
Id 11685
A short tutorial
Yet another
Bookmark directory
Step 1: Quickstart your application
$ tg-admin quickstart
Enter project name: Bookmarker
Enter package name [bookmarker]:
Do you need Identity (usernames/passwords) in
this project? [no] yes
$ cd Bookmarker
Step 2: Code you data model
# in model.py:
class Bookmark(SQLObject):
# meta data
created = DateTimeCol(default=datetime.now)
owner = ForeignKey('User', notNull=True)
Step 2 (cont.): Data model - Tags
Tag properties:
● Label (text, one-line)
● Name (text, one-line)
● Creation time (timestamp)
● Owner (one-to-many: Tag)
● Bookmarks (many-to-many: Bookmark)
Step2 (cont.):
Data model - Tag objects
# still in model.py:
class Tag(SQLObject):
bookmarks = RelatedJoin('Bookmark',
orderBy='-created')
# meta data
owner = ForeignKey('User', notNull=True)
created = DateTimeCol(default=datetime.now)
Step 3: Create the database
$ tg-admin toolbox
[...]
HTTP INFO Serving HTTP on http://localhost:7654/
[...]
/bookmarks/<id>/add
● /bookmarks/<id>/delete Delete bookmark
● /bookmarks/<id>/update Update bookmark
Step 5 (cont.): URL mapping
● Example:
http://mysite.com/bookmarks/edit/1
● Question: which part of the URL is the method
name and which are the parameters?
Step 5 (cont.):
URL mapping à la CherryPy
# in controllers.py:
class BookmarkController(controller.Controller):
@expose()
def edit(self, id):
return “The given ID is %s” % id
class Root(controller.RootController):
bookmarks = BookmarkController()
URL: http://mysite/bookmarks/edit/1
class BookmarksController(controllers.Controller):
@expose(template='.templates.bookmarks.list')
def index(self):
bookmarks = Bookmark.select()
return dict(entries=bookmarks)
list = index
Step 6 (cont.): Controller methods
Show bookmark details / edit form
# still in controllers.py:
class BookmarksController(...):
...
@expose(template='.templates.bookmarks.edit')
def view(self, id, *params, **kw):
try:
bookmark = Bookmark.get(id)
except SQLObjectNotFound:
flash('Bookmark not found.')
redirect('/')
return dict(entry=bookmark)
Step 6 (cont.): Controller methods
Update/Create bookmark
@expose()
def update(self, id, *params, **kw):
try:
bookmark = Bookmark.get(id)
except SQLObjectNotFound:
bookmark = Bookmark(
title = kw.get('title'),
url = kw.get('url'),
description = kw.get('description'))
else:
bookmark.set(
title = kw.get('title'), url=...)
# TODO: handle tags specially
redirect('/bookmarks/')
Step 6 (cont.): Controller methods
Delete bookmark
@expose()
def delete(self, id, *params, **kw):
try:
Bookmark.delete(id)
except SQLObjectNotFound:
flash('Bookmark not found.')
else:
flash('Bookmark deleted.')
redirect('/bookmarks')
Step 7: Edit templates
List of bookmarks
<!-- templates/list.kid -->
<textarea name="description">
${entry.description}
</textarea>
easy_install <egg-file>
Questions?
http://chrisarndt.de/talks/rupy/
Appendix
Easy controllers with FastData
class Root(controllers.RootController):