1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
3 # This file is part of Cookbook.
5 # Cookbook is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation, either version 3 of the License, or (at your
8 # option) any later version.
10 # Cookbook is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Cookbook. If not, see <http://www.gnu.org/licenses/>.
18 """Serve cookbooks over HTTP.
24 from xml.sax import saxutils
27 from jinja2 import Environment, FileSystemLoader
30 class Server (object):
31 """Cookbook web interface."""
33 def __init__(self, cookbook, template_root):
34 self.cookbook = cookbook
35 self.cookbook.make_index()
36 self.env = Environment(loader=FileSystemLoader(template_root))
39 #self.cookbook.save('new-recipe')
43 def index(self, tag=None):
46 Recipes can be filtered by tag.
48 if isinstance(tag, types.StringTypes):
50 template = self.env.get_template('recipes.html')
51 return template.render(cookbook=self.cookbook,
52 recipes=list(self.cookbook.tagged(tag)),
56 def recipe(self, name=None):
57 """Single recipe page.
60 recipe = random.choice(self.cookbook)
62 if type(name) == types.StringType:
63 name = unicode(name, encoding='utf-8')
64 recipe = self.cookbook.index[name]
65 template = self.env.get_template('recipe.html')
66 return template.render(cookbook=self.cookbook, recipe=recipe)
69 def add_tag(self, name, tag):
70 """Add a tag to a single recipe."""
71 if type(name) == types.StringType:
72 name = unicode(name, encoding='utf-8')
73 recipe = self.cookbook.index[name]
74 if recipe.tags == None:
76 if tag not in recipe.tags:
77 recipe.tags.append(tag)
78 with open(recipe.path, 'w') as f:
80 raise cherrypy.HTTPRedirect(
81 'recipe?name=%s' % recipe.clean_name(), status=302)
84 def remove_tag(self, name, tag):
85 """Remove a tag from a single recipe."""
86 if type(name) == types.StringType:
87 name = unicode(name, encoding='utf-8')
88 recipe = self.cookbook.index[name]
89 if recipe.tags == None:
91 if tag in recipe.tags:
92 recipe.tags.remove(tag)
93 with open(recipe.path, 'w') as f:
95 raise cherrypy.HTTPRedirect(
96 'recipe?name=%s' % recipe.clean_name(), status=302)