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.
21 from __future__ import with_statement
27 from xml.sax import saxutils
30 from jinja2 import Environment, FileSystemLoader
33 class Server (object):
34 """Cookbook web interface."""
36 def __init__(self, cookbook, template_root):
37 self.cookbook = cookbook
38 self.cookbook.make_index()
39 self.env = Environment(loader=FileSystemLoader(template_root))
40 self.tag_regexp = re.compile('[a-zA-Z./ ].*') # allowed characters
43 #self.cookbook.save('new-recipe')
47 def index(self, tag=None):
50 Recipes can be filtered by tag.
52 if isinstance(tag, types.StringTypes):
54 template = self.env.get_template('recipes.html')
55 return template.render(cookbook=self.cookbook,
56 recipes=list(self.cookbook.tagged(tag)),
60 def recipe(self, name=None):
61 """Single recipe page.
64 recipe = random.choice(self.cookbook)
66 if type(name) == types.StringType:
67 name = unicode(name, encoding='utf-8')
68 recipe = self.cookbook.index[name]
69 template = self.env.get_template('recipe.html')
70 return template.render(cookbook=self.cookbook, recipe=recipe)
73 def add_tag(self, name, tag):
74 """Add a tag to a single recipe."""
75 if type(name) == types.StringType:
76 name = unicode(name, encoding='utf-8')
77 recipe = self.cookbook.index[name]
78 if recipe.tags == None:
80 tag = self._clean_tag(tag)
83 if tag not in recipe.tags:
84 recipe.tags.append(tag)
85 with open(recipe.path, 'w') as f:
87 raise cherrypy.HTTPRedirect(
88 'recipe?name=%s' % recipe.clean_name(), status=302)
91 def remove_tag(self, name, tag):
92 """Remove a tag from a single recipe."""
93 if type(name) == types.StringType:
94 name = unicode(name, encoding='utf-8')
95 recipe = self.cookbook.index[name]
96 if recipe.tags == None:
98 tag = self._clean_tag(tag)
101 if tag in recipe.tags:
102 recipe.tags.remove(tag)
103 with open(recipe.path, 'w') as f:
105 raise cherrypy.HTTPRedirect(
106 'recipe?name=%s' % recipe.clean_name(), status=302)
108 def _clean_tag(self, tag):
110 m = self.tag_regexp.match(tag)