def delete_entry(self): entry_id = self.request.matchdict["id_"] entry = DBSession.query(Entry).filter(Entry.id == entry_id).one() DBSession.delete(entry) get_categories.invalidate() get_recent_posts.invalidate() return HTTPFound(location=self.request.route_url('home'))
def test_get_recent_posts(self): from miniblog.models import get_recent_posts, Entry from time import sleep # test with not enough entries DBSession.add(Entry('Title 1', 'Text 1')) self.assertEqual(len(get_recent_posts()), 1) # make sure caching is still in place # sleep(1) # activate this when order test fails DBSession.add(Entry('Title 2', 'Text 2')) self.assertEqual(len(get_recent_posts()), 1) # Invalidate and recount get_recent_posts.invalidate() self.assertEqual(len(get_recent_posts()), 2) # Check order is correct recent = get_recent_posts() first = recent[0].entry_time second = recent[1].entry_time self.assertGreater(first, second) # Check count param: self.assertEqual(len(get_recent_posts(1)), 1) for i in range(3, 9): DBSession.add(Entry('Title {0}'.format(i), 'Text {0}'.format(i))) get_recent_posts.invalidate() self.assertEqual(len(get_recent_posts()), 7)
def add_entry(self): entry_id = self.request.matchdict.get("id_", 0) if entry_id: entry = DBSession.query(Entry).filter(Entry.id == entry_id).one() form_data = MultiDict({'title': entry.title, 'text': entry._text, 'category': entry.category_name}) form_data.update(self.request.session.get("edit_entry_%i_form" % entry.id, {})) else: entry = None form_data = MultiDict(self.request.session.get("add_entry_form", {})) form_data.update(self.request.POST) form = EntryForm(form_data) form.category.choices = [('', ' - None - ')] + [(name[0], name[0]) for name in get_categories()] preview = None if self.request.method == 'POST': if not form.validate(): for field, errors in form.errors.items(): for error in errors: self.request.session.flash('Field "%s" has the following error: "%s"' % (field, error)) if entry: self.request.session["edit_entry_%i_form" % entry.id] = form.data else: self.request.session["add_entry_form"] = form.data return HTTPFound(location=self.request.route_url('add_entry')) if form.submit.data: if "category" in form.data and form.data["category"]: category = DBSession.query(Category)\ .filter(Category.name == form.data["category"]).one() else: category = None if not entry: entry = Entry(form.data["title"], form.data["text"]) entry.category = category if "add_entry_form" in self.request.session: del self.request.session["add_entry_form"] DBSession.add(entry) else: if "edit_entry_%i_form" \ % entry.id in self.request.session: del self.request.session["edit_entry_%i_form" % entry.id] entry._text = form.data["text"] entry.title = form.data["title"] entry.category = category DBSession.flush() get_categories.invalidate() get_recent_posts.invalidate() return HTTPFound(location=self.request.route_url('view_entry', id_=entry.id)) if form.preview.data: preview = entry return {'form': form, 'preview': preview}