Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merged the concepts of pages and posts. Pages are now just a grouping…

… of posts.
  • Loading branch information...
commit cafdc6f3cd0d2be03ecebf9e49a9d8c8878cc1ae 1 parent 9c776fb
@pflarr authored
View
1  TODO
@@ -3,6 +3,5 @@ Fix internal links
Add a basic theme.css
Add a default logo
Add a default site.css
-Enforce user permissions
Make it pretty.
View
46 basic_site/__init__.py
@@ -28,34 +28,46 @@ def main(global_config, **settings):
authorization_policy=authz_policy)
config.add_static_view('static', 'basic_site:static')
config.add_route('home', '')
- config.add_view('basic_site.views.home',
- route_name='home',
+ config.add_view('basic_site.views.posts',
+ route_name='home', permission='view',
renderer='basic_site:templates/main.mako')
+ config.add_route('posts', r'p/{page:[a-zA-Z0-9_ -]+}/{skip:\d*}')
+ config.add_view('basic_site.views.posts', route_name='posts',
+ renderer='basic_site:templates/main.mako',
+ permission='view')
config.add_route('post',r'post/{id:\d+(\.\d+)?}')
config.add_view('basic_site.views.post', route_name='post',
- renderer='basic_site:templates/post.mako')
- config.add_route('page',r'page/{name:[a-z0-9_ -]+(\.\d+)?}')
- config.add_view('basic_site.views.page', route_name='page',
- renderer='basic_site:templates/page.mako')
- config.add_route('add', 'add/{ptype:(page|post)}')
- config.add_route('edit', 'edit/{ptype:(page|post)}/{id}')
+ renderer='basic_site:templates/post.mako',
+ permission='view')
+ config.add_route('new_page', 'new_page')
+ config.add_view('basic_site.views.new_page', route_name='new_page',
+ renderer='basic_site:templates/new_page.mako',
+ permission='edit')
+ config.add_route('add', 'add/{page:[a-zA-Z0-9_ -]+}')
config.add_view('basic_site.views.edit', route_name='add',
- renderer='basic_site:templates/edit.mako')
+ renderer='basic_site:templates/edit.mako',
+ permission='edit')
+ config.add_route('edit', 'edit/{id:\d+}')
config.add_view('basic_site.views.edit', route_name='edit',
- renderer='basic_site:templates/edit.mako')
- config.add_route('restore', 'restore/{ptype:(page|post)}/'
- '{id:[a-z0-9_ -]+)/{skip:\d+}')
- config.add_view('basic_site.views.restore', route_name='restore')
+ renderer='basic_site:templates/edit.mako',
+ permission='edit')
+ config.add_route('restore', 'restore/{id:[a-z0-9_ -]+)/{version:\d+}')
+ config.add_view('basic_site.views.restore', route_name='restore',
+ permission='edit')
config.add_route('users', 'users')
config.add_view('basic_site.views.users', route_name='users',
- renderer='basic_site:templates/users.mako')
+ renderer='basic_site:templates/users.mako',
+ permission='edit')
config.add_route('file_rev', 'file/{rev}/{name}')
config.add_route('file', 'file/{name}')
- config.add_view('basic_site.views.file', route_name='file')
- config.add_view('basic_site.views.file', route_name='file_rev')
+ config.add_view('basic_site.views.file', route_name='file',
+ permission='view')
+ config.add_view('basic_site.views.file', route_name='file_rev',
+ permission='view')
config.add_route('files', 'files/')
config.add_view('basic_site.views.files', route_name='files',
- renderer='basic_site:templates/files.mako')
+ renderer='basic_site:templates/files.mako',
+ permission='edit')
config.add_route('logout', 'logout/')
config.add_view('basic_site.views.logout', route_name='logout')
return config.make_wsgi_app()
View
90 basic_site/models.py
@@ -2,6 +2,7 @@
from creole.html_emitter import HtmlEmitter
import datetime
+import re
from sqlalchemy import create_engine, Column, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
@@ -34,6 +35,12 @@ def initialize_sql(engine):
if not admin:
admin = User('admin', DEFAULT_ADMIN_PW, True, 'Admin')
session.add(admin)
+
+ msg = "The default admin password is: '%s'. CHANGE IT! Until it "\
+ "is changed, anyone can log in as an admin." % DEFAULT_ADMIN_PW
+ post = Post('admin', 'Home', 'CHANGE THE DEFAULT PASSWORD!', msg,
+ sticky=True)
+ session.add(post)
session.flush()
transaction.commit()
@@ -69,19 +76,26 @@ def change_pw(self, new):
self.pw_hash = manager.encodePassword(new)
class Post(Base):
+ PAGE_RE_STR = r'[a-zA-Z0-9_ -]{1,30}'
+ PAGE_RE = re.compile('^%s$' % PAGE_RE_STR)
__tablename__ = 'posts'
- id = Column(Integer(), primary_key=True)
+ id = Column(Integer, primary_key=True)
+ page = Column(String(30))
title = Column(String(30), nullable=False)
created = Column(DateTime(), nullable=False)
creator = Column(String(10), nullable=False)
sticky = Column(Boolean(), nullable=False)
content = Column(String(), nullable=False)
- def __init__(self, creator, title, content, sticky=False, created=None):
+ def __init__(self, creator, page, title, content,
+ sticky=False, created=None):
if created:
self.created = created
else:
self.created = datetime.datetime.utcnow()
+ if not self.PAGE_RE.match(page):
+ raise ValueError("Invalid Page Name")
+ self.page = page
self.creator = creator
self.sticky = sticky
self.title = title[:30]
@@ -107,6 +121,7 @@ def render(self):
class Post_History(Base):
__tablename__ = 'post_history'
hist_id = Column(Integer(), primary_key=True)
+ page = Column(String(30), nullable=False)
id = Column(Integer(), nullable=False)
changed_on = Column(DateTime(), nullable=False)
changed_by = Column(String(10), ForeignKey(User.uid), nullable=False)
@@ -126,7 +141,7 @@ def __init__(self, editor_uid, post):
self.changed_by = editor_uid
self.changed_on = datetime.datetime.utcnow()
- def restore(self, user):
+ def restore(self, user, current):
"""Restore this history item's content. Returns an item to add to
the db/session."""
if current:
@@ -140,75 +155,6 @@ def render(self):
doc = Parser(self.content).parse()
return BS_Emitter(doc).emit()
-
-class Page(Base):
- __tablename__ = 'pages'
- id = Column(Integer(), primary_key=True)
- name = Column(String(15), unique=True)
- created = Column(DateTime(), nullable=False)
- creator = Column(String(10), nullable=False)
- content = Column(String(), nullable=False)
-
- allowed_chars = 'abcdefghijklmnopqrstuvwxyz0123456789 _-'
- def __init__(self, creator, name, content, created=None):
- if created:
- self.created = created
- else:
- self.created = datetime.datetime.utcnow()
-
- self.name = ''.join([c if c.lower() in self.allowed_chars else '_'
- for c in name[:15]])
- self.creator = creator
- self.content = content
-
- def edit(self, user, name, content, created=None):
- """Edit this page, and return the history table entry."""
- hist = Page_History(user, self)
- self.name = name
- self.content = content
- if created:
- self.created = datetime.datetime.utcnow()
- else:
- self.created = created
- return hist
-
- def render(self):
- doc = Parser(self.content).parse()
- return BS_Emitter(doc).emit()
-
-class Page_History(Base):
- __tablename__ = 'page_history'
- hist_id = Column(Integer(), primary_key=True)
- id = Column(Integer(), nullable=False)
- name = Column(String(15), nullable=False)
- changed_on = Column(DateTime(), nullable=False)
- changed_by = Column(String(10), ForeignKey(User.uid), nullable=False)
- created = Column(DateTime(), nullable=False)
- creator = Column(String(10), nullable=False)
- content = Column(String(), nullable=False)
-
- def __init__(self, editor_uid, page):
- self.id = page.id
- self.name = page.name
- self.created = page.created
- self.creator = page.creator
- self.content = page.content
- self.changed_by = editor_uid
- self.changed_on = datetime.datetime.utcnow()
-
- def restore(self, user, current):
- """Restore this history item's content, returns a list of rows to
- add to the session."""
-
- if current:
- return current.edit(user, self.name, self.content, self.created)
- else:
- return Page(user, self.name, self.content, self.created)
-
- def render(self):
- doc = Parser(self.content).parse()
- return BS_Emitter(doc).emit()
-
class File(Base):
__tablename__ = 'files';
id = Column(Integer, primary_key=True)
View
9 basic_site/security.py
@@ -7,7 +7,6 @@
import sqlalchemy.orm
-
def groupfinder(uid, request):
"""There are only two groups: 'editor' and 'admin'. The only difference
is that only administrators can add users and edit certain files
@@ -15,11 +14,9 @@ def groupfinder(uid, request):
if not uid:
return None
session = DBSession()
- try:
- user = session.query(User)\
- .filter(User.uid == uid)\
- .one()
- except sqlalchemy.orm.exc.NoResultFound:
+ user = session.query(User).get(uid)
+
+ if not user:
return None
groups = ['group:editors']
View
33 basic_site/static/base.css
@@ -1,13 +1,20 @@
div.head {
border: 1px solid blue;
+ margin-bottom: 10px;
+ padding: 5px;
}
div.login {
float: right;
+ clear: left;
font-size: small;
margin-bottom: 6px;
}
+div.login form {
+ margin: 0px;
+}
+
div.login input {
border: 1px black solid;
font-size: small;
@@ -18,10 +25,12 @@ div.login button {
font-size: small;
}
-div.head div.message {
+div.message {
font-weight: bold;
- float: right;
- clear: right;
+ border: 1px red solid;
+ background: white;
+ margin-bottom: 6px;
+ padding: 5px;
}
div.pages {
@@ -52,13 +61,27 @@ div.main {
}
div.content {
- margin-left: 210px;
- padding: 10px;
+ margin-left: 215px;
border: 1px solid red;
}
+div.content > div {
+ padding: 10px;
+ margin-bottom: 6px;
+}
+
div.post {
margin-bottom: 5px;
border: 1px solid blue;
}
+table {
+ border-collapse: collapse;
+}
+
+table td, table th {
+ padding: 3px;
+ padding-right: 6px;
+ padding-bottom: 1px;
+}
+
View
47 basic_site/templates/edit.mako
@@ -2,11 +2,7 @@
% if data:
<DIV class="post">
- % if ptype=="post":
- <H2 class="preview">Preview: ${data.title}</H2>
- % elif ptype=="page":
- <H2 class="preview">Preview: ${data.name}</H2>
- % endif
+ <H2 class="preview">Preview: ${data.title}</H2>
${data.render()|n}
<DIV class="post_footer">
<SPAN class="creator">${data.creator|h}</SPAN>
@@ -15,30 +11,23 @@
</DIV>
% endif
<DIV id="instructions">
-
+Insert wiki syntax instructions here.
+</DIV>
+
+<DIV>
+ <FORM action="${request.route_url(mode, page=page, id=id)}"
+ method="post">
+ <LABEL for="title">Post Title:</LABEL>
+ <INPUT name="title" type="text" size="30" maxlength="30"
+ value="${data.title if data else ''|h}"><BR/>
+ <LABEL for="content">Post content:</LABEL><BR/>
+ <%
+ content = data.content if data else ''
+ %>
+ <TEXTAREA name="content" rows="20" cols="80">${content}</TEXTAREA><BR>
+ <BUTTON type="submit" name="action" value="submit">Submit</BUTTON>
+ <BUTTON type="submit" name="action" value="preview">Preview</BUTTON>
+ </FORM>
</DIV>
-
-<FORM action="${request.route_url(mode,ptype=ptype,id=id)}"
- method="post">
-% if ptype == 'post':
- <LABEL for="title">Post Title:</LABEL>
- <INPUT name="title" type="text" size="30" maxlength="30"
- value="${data.title if data else ''|h}"><BR/>
-% elif ptype == 'page':
- <LABEL for="name">Page Name:</LABEL>
- <INPUT name="name" type="text" size="15" maxlength="15"
- value="${data.name if data else ''}"><BR/>
-% endif
-% if (mode,ptype) == ('edit','page'):
- <INPUT name="old_name" type="hidden" value="${data.name}">
-% endif
- <LABEL for="content">${ptype.capitalize()} content:</LABEL><BR/>
-<%
- content = data.content if data else ''
-%>
- <TEXTAREA name="content" rows="20" cols="80">${content}</TEXTAREA><BR>
- <BUTTON type="submit" name="action" value="submit">Submit</BUTTON>
- <BUTTON type="submit" name="action" value="preview">Preview</BUTTON>
-</FORM>
<%include file="foot.mako" />
View
50 basic_site/templates/files.mako
@@ -1,31 +1,33 @@
<%include file="head.mako" />
-<FORM method="POST" action="${request.route_url('files')}"
- enctype="multipart/form-data">
- <INPUT type="file" name="data">
- <BUTTON type="submit">Submit File</BUTTON>
-<FORM>
+<DIV>
+ <FORM method="POST" action="${request.route_url('files')}"
+ enctype="multipart/form-data">
+ <INPUT type="file" name="data">
+ <BUTTON type="submit">Submit File</BUTTON>
+ </FORM>
-<%
- names = files.keys()
- names.sort()
-%>
-
-<TABLE>
- <TR><TH>Name<TH>Added By<TH>Added
-% for name in names:
- % for i in range(len(files[name])):
- <%
- file = files[name][i]
- href = request.route_url('file_rev', name=file.name, rev=i)
- f_class = 'class=old_file' if i > 0 else ''
+ <%
+ names = files.keys()
+ names.sort()
%>
- <TR ${f_class|n}>
- <TD><A href="${href}">${file.name|h}</A>
- <TD>${file.submitter|h}
- <TD>${file.changed.strftime('%Y-%m-%d %H:%M:%S')|h}
+
+ <TABLE>
+ <TR><TH>Name<TH>Added By<TH>Added
+ % for name in names:
+ % for i in range(len(files[name])):
+ <%
+ file = files[name][i]
+ href = request.route_url('file_rev', name=file.name, rev=i)
+ f_class = 'class=old_file' if i > 0 else ''
+ %>
+ <TR ${f_class|n}>
+ <TD><A href="${href}">${file.name|h}</A>
+ <TD>${file.submitter|h}
+ <TD>${file.changed.strftime('%Y-%m-%d %H:%M:%S')|h}
+ % endfor
% endfor
-% endfor
-</TABLE>
+ </TABLE>
+<DIV>
<%include file="foot.mako" />
View
24 basic_site/templates/head.mako
@@ -8,23 +8,23 @@
<LINK type="text/css" rel="stylesheet"
href="${request.route_url('file', name='site.css')}">
</HEAD>
-<DIV class="head">
- <IMG src="${request.route_url('file',name='logo.png')}">
- <DIV class="login">
+<DIV class="login">
% if user == None:
<FORM action='' method="POST">
<LABEL target="user">User</LABEL>
- <INPUT type="text" name="user">
+ <INPUT type="text" size=10 name="user">
<LABEL target="passwd">Password</LABEL>
- <INPUT type="password" name="passwd">
+ <INPUT type="password" size=10 name="passwd">
<BUTTON type="submit">Login</BUTTON>
</FORM>
% else:
Logged in as <STRONG>${user.uid}</STRONG>
(<A href="${request.route_url('logout')}">logout</A>)
% endif
- </DIV>
+</DIV>
+<DIV class="head">
+ <IMG src="${request.route_url('file',name='logo.png')}">
</DIV>
% if msg:
@@ -50,13 +50,13 @@
<A href="${request.route_url('users')}">Users</A>
<LI ${cur_class('*Files')|n}>
<A href="${request.route_url('files')}">Files</A>
- <LI ${cur_class('add page')|n}>
- <A href="${request.route_url('add', ptype='page')}"
- >Add New Page</A>
+ <LI ${cur_class('*New Page')|n}>
+ <A href="${request.route_url('new_page')}">Add New Page</A>
% endif
- % for page in menu_pages:
- <LI ${cur_class(page.name)|n}>
- <A href="${request.route_url('page', name=page.name)}">${page.name}</A>
+ % for post in menu_pages:
+ <LI ${cur_class(post.page)|n}>
+ <A href="${request.route_url('posts',page=post.page, skip=0)}"
+ >${post.page}</A>
% endfor
</UL>
View
4 basic_site/templates/main.mako
@@ -2,12 +2,12 @@
% if user:
-<DIV><A href="${request.route_url('add', ptype='post')}"
+<DIV><A href="${request.route_url('add', page=page_name)}"
>Add a new Post</A></DIV>
% endif
% for post in posts:
<%
- edit_url = request.route_url('edit', ptype='post', id=post.id)
+ edit_url = request.route_url('edit', page=post.page, id=post.id)
%>
<DIV class="post">
<H2>${post.title}</H2>
View
15 basic_site/templates/new_page.mako
@@ -0,0 +1,15 @@
+<%include file="head.mako" />
+
+<!-- All this whole thing does is redirect you to the appropriate edit
+ post page. -->
+<DIV>
+ <P>Enter the name of your new page. You'll need to add a post to the page before it will appear.</P>
+ <FORM action="${request.route_url('new_page')}" method="GET">
+ <LABEL for="page">Page Name:</LABEL>
+ <INPUT name="page" type="text" size="15" maxlength="15"
+ value="">
+ <BUTTON type="submit">Submit</BUTTON>
+ </FORM>
+</DIV>
+
+<%include file="foot.mako" />
View
2  basic_site/templates/post.mako
@@ -1,7 +1,7 @@
<%include file="head.mako" />
<%
route_url = request.route_url
- edit_url = route_url('edit', ptype='post', id=post.id)
+ edit_url = route_url('edit', id=post.id)
if prior is not None:
prior_url = route_url('post', id='%s.%d' % (post.id, prior))
if next >= 0:
View
313 basic_site/views.py
@@ -1,6 +1,5 @@
from basic_site.models import DBSession, DEFAULT_ADMIN_PW
-from basic_site.models import Page, Post, File, User
-from basic_site.models import Page_History, Post_History
+from basic_site.models import Post, Post_History, File, User
from basic_site.security import groupfinder, login
import mimetypes
@@ -24,11 +23,6 @@ def get_context(request):
if user is None and msg is None:
session = DBSession()
admin = session.query(User).get('admin')
- if admin.check_pw(DEFAULT_ADMIN_PW):
- user = admin
- msg = "The default admin password is: '%s'. CHANGE IT! Until it "\
- "is changed, all visitors are automatically admin." % \
- DEFAULT_ADMIN_PW
context['user'] = user
# Get any messages passed in the query
@@ -37,27 +31,32 @@ def get_context(request):
context['msg'].append(msg)
session = DBSession()
- menu_pages = session.query(Page.id, Page.name)\
- .order_by(Page.name)\
+ menu_pages = session.query(Post.page)\
+ .filter(Post.page != 'Home')\
+ .order_by(Post.page)\
+ .group_by(Post.page)\
.all()
context['menu_pages'] = menu_pages
return context
-def home(request):
+def posts(request):
dbsession = DBSession()
context = get_context(request)
skip = request.matchdict.get('skip', 0)
+ if skip == '': skip = 0
+ page = request.matchdict.get('page', 'Home')
posts = dbsession.query(Post)\
+ .filter(Post.page == page)\
.order_by(Post.created)\
.offset(skip)\
.limit(5)\
.all()
context['posts'] = posts
- context['page_name'] = '*Main'
+ context['page_name'] = page
context['page_subtitle'] = ''
return context
@@ -68,29 +67,31 @@ def post(request):
context = get_context(request)
id = request.matchdict['id']
+ page = request.matchdict['page']
if '.' in id:
- id, skip = id.split('.', 1)
+ id, version = id.split('.', 1)
else:
- skip = None
+ version = None
+
try:
id = int(id)
- if skip: skip = int(skip)
+ if version: version = int(version)
except ValueError:
raise except_response(404)
- if skip is not None:
+ if version is not None:
try:
post = session.query(Post_History)\
.filter(Post_History.id == id)\
+ .filter(Post_History.page == page)\
.order_by(expression.desc(Post_History.changed_on))\
.limit(1)\
- .offset(skip)\
+ .offset(version)\
.one()
except sqlalchemy.orm.exc.NoResultFound:
raise except_response(404)
- context['page_name'] = 'View Post History'
context['page_subtitle'] = 'Post %d History, rev %d' % (id, skip+1)
else:
post = session.query(Post).get(id)
@@ -98,163 +99,106 @@ def post(request):
if not post:
raise NotFound('No such post: %d' % id)
- context['page_name'] = 'View Post'
context['page_subtitle'] = 'Post %d' % id
+ context['page_name'] = page
+
hist_count = session.query(Post_History)\
.filter(Post_History.id == id)\
.count()
- if skip is None and hist_count:
+ if version is None and hist_count:
context['prior'] = 0
- elif skip is not None and (skip+1) <= (hist_count-1):
- context['prior'] = skip+1
+ elif version is not None and (version+1) <= (hist_count-1):
+ context['prior'] = version+1
else:
context['prior'] = None
- context['next'] = context['next'] = skip - 1 if skip is not None else None
+
+ if version is not None:
+ context['next'] = context['next'] = version - 1
+
context['post'] = post
return context
-def page(request):
- dbsession = DBSession()
- context = get_context(request)
+def new_page(request):
+ """Presents a form where the user can enter a new page name. When submitted
+ with a page name, it redirects them to the add post form for that page."""
+ if 'page' in request.params:
+ page = request.params.getone('page')
+ return HTTPFound(location=request.route_url('add', page=page))
- name = request.matchdict['name']
- is_hist = False
- if '.' in name:
- name, skip = name.split('.', 1)
- is_hist = True
- try:
- skip = int(skip)
- except ValueError:
- raise except_response(404)
-
- try:
- page = dbsession.query(Page)\
- .filter(Page.name == name)\
- .one()
- except sqlalchemy.orm.exc.NoResultFound:
- return exception_response(404)
-
- hist_count = dbsession.query(Page_History)\
- .filter(Page.id == page.id)\
- .count()
-
- if is_hist:
- try:
- hist_page = dbsession.query(Page_History)\
- .filter(Page_History.id == page.id)\
- .order_by(Page_History.changed_on)\
- .limit(1)\
- .offset(skip)\
- .one()
- except sqlalchemy.orm.exc.NoResultFound:
- return exception_response(404)
-
- context['page'] = hist_page
- context['page_name'] = page.name
- context['page_subtitle'] = '%s Revision - %d' % (page.name, skip + 1)
- context['prior'] = skip + 1 if skip <= (hist_count - 2) else None
- context['next'] = skip - 1
- context['msg'].append('Hist count: %d' % hist_count)
- else:
- context['page'] = page
- context['page_name'] = page.name
- context['page_subtitle'] = '- %s' % page.name
- context['prior'] = 0 if hist_count else None
- context['next'] = None
-
+ context = get_context(request)
+ context['page_name'] = "*New Page"
+ context['page_subtitle'] = ""
return context
def edit(request):
- """ Handle the edit view and submission of pages and posts."""
+ """Handle the edit view and submission of pages and posts."""
context = get_context(request)
- for v in request.POST:
- print v, request.POST[v]
-
- ptype = request.matchdict['ptype']
mode = request.matched_route.name
- id = request.matchdict.get('id')
+ id = request.matchdict.get('id', None)
+ page = request.matchdict.get('page', None)
- context['page_name'] = '%s %s' % (mode, ptype)
+ context['page_name'] = '*%s' % mode
context['page_subtitle'] = ''
- context.update({'ptype': ptype, 'mode': mode})
-
- if mode == 'add':
- context['data'] = None
+ context.update({'mode': mode})
context['id'] = id
-
+ context['page'] = page
+ context['data'] = None
+
if 'action' in request.POST:
action = request.POST.getone('action')
else:
action = None
- if action is None and mode == 'add':
- return context
-
- if action == 'submit':
+ if action == 'preview':
+ if 'title' in request.POST:
+ title = request.POST.getone('title')
+ else:
+ title = ''
+ context['msg'].append("You might want to title your post.")
+ if 'content' in request.POST:
+ content = request.POST.getone('content')
+ else:
+ content = ''
+ context['msg'].append('No content given')
+ sticky = 'sticky' in request.POST
+ post = Post(context['user'].uid, page, title, content, sticky)
+ context['data'] = post
+ context['preview'] = True
+ elif action == 'submit':
# Call the submit content view if we want to actually change something.
return submit_content(request)
- if action is None:
+ if mode == 'edit' and action is None:
# We aren't changing anything, just display the one we in intend
# to change.
session = DBSession()
- tables = {('page', 'edit'): Page, ('page', 'revert'): Page_History,
- ('post', 'edit'): Post, ('post', 'revert'): Post_History}
- table = tables[(ptype, mode)]
+ if mode == 'edit':
+ table = Post
+ else:
+ table = Post_History
q = session.query(table)
+ q = q.filter(table.page == page)
data = None
if mode == 'edit': q = q.filter(table.id == id)
else: q= q.filter(table.hist_id == id)
+
try:
data = q.one()
except:
- raise NotFound("No such %s to edit: %s" % (ptype, id))
+ raise NotFound("No such post to edit: %s" % id)
context['data'] = data
context['preview'] = False
- elif action == 'preview' and ptype == 'post':
- if 'title' in request.POST:
- title = request.POST.getone('title')
- else:
- title = ''
- context['msg'].append("You might want to title your post.")
- if 'content' in request.POST:
- content = request.POST.getone('content')
- else:
- content = ''
- context['msg'].append('No content given')
- sticky = 'sticky' in request.POST
- post = Post(context['user'].uid, title, content, sticky)
- context['data'] = post
- context['preview'] = True
-
- elif action == 'preview' and ptype == 'page':
- if 'name' in request.POST:
- name = request.POST.getone('name')
- else:
- name = ''
- context['msg'].append('You must give your page a name!')
- if 'content' in request.POST:
- content = request.POST.getone('content')
- else:
- content = ''
- context['msg'].append('No content given')
-
- page = Page(context['user'].uid, name, content)
- context['data'] = page
- context['preview'] = True
-
return context
-
def get_required_params(params, args=[], kwargs=[]):
"""Get the required parameters, and return an args and kwargs
dictionary."""
@@ -271,47 +215,32 @@ def get_required_params(params, args=[], kwargs=[]):
return out_args, out_kw
def submit_content(request):
- """Handles page/post editing, adding, and restoration. The process is
-almost identical for pages and posts, so it's a unified view callable. It
-expects a 'ptypes' matchdict entry so that it can tell the difference
-though. """
+ """Handles actually submitting new post content."""
session = DBSession()
context = get_context(request)
uid = context['user'].uid
- ptype = request.matchdict['ptype']
- if ptype == 'page':
- table = Page
- hist_table = Page_History
- fields = ['name', 'content']
- else:
- table = Post
- hist_table = Post_History
- fields = ['title', 'content']
-
mode = request.matched_route.name
-
- args,_ = get_required_params(request.params, fields)
- if ptype == 'post':
- args.append( request.params.has_key('sticky') )
-
+
+ title = request.params.get('title')
+ content = request.params.get('content')
+ sticky = request.params.has_key('sticky')
+ page = request.matchdict['page']
if mode == 'edit':
# Handle the editing of existing posts.
id = request.matchdict['id']
- entry = session.query(table).get(id)
+ entry = session.query(Post).get(id)
if not entry:
- raise NotFound("No such %s to edit: %d" % (ptype, id))
+ raise NotFound("No such post to edit: %s, %d" % (page, id))
- args = [uid] + args
- hist = entry.edit(*args)
+ hist = entry.edit(uid, title, content, sticky)
session.add(hist)
- msg = '%s edited succesfully.' % ptype.capitalize()
+ msg = 'Post edited succesfully.'
elif mode == 'add':
- args = [uid] + args
- entry = table(*args)
+ entry = Post(uid, page, title, content, sticky)
session.add(entry)
- msg = '%s added successfully.' % ptype.capitalize()
+ msg = 'Post added successfully.'
else:
msg = "Invalid mode: %s" % mode
@@ -320,70 +249,53 @@ def submit_content(request):
context['msg'].append(msg)
msgs = [('msg', m) for m in context['msg']]
- if ptype == 'post':
- return HTTPFound(location=request.route_url('post', id=entry.id,
- _query=msgs))
- elif ptype == 'page':
- return HTTPFound(location=request.route_url('page', name=entry.name,
- _query=msgs))
+ return HTTPFound(location=request.route_url('post', id=entry.id,
+ page=page, _query=msgs))
def restore(request):
+ """Restore a Post_History entry as the current version."""
session = DBSession()
context = get_context(request)
uid = context['user'].uid
- ptype = request.matchdict['ptype']
- if ptype == 'page':
- table, hist_table = Page, Page_History
- else:
- table, hist_table = Post, Post_History
-
id = request.matchdict['id']
- skip = request.matchdickt['skip']
+ page = request.matchdict['page']
+ version = request.matchdickt['version']
try:
- entry = session.query(hist_table)\
- .filter(hist_table.id == id)\
- .order_by(expression.desc(hist_table.changed_on))\
+ entry = session.query(Post_History)\
+ .filter(Post_History.id == id)\
+ .filter(Post_History.page == page)\
+ .order_by(expression.desc(Post_History.changed_on))\
.limit(1)\
- .offset(skip)\
+ .offset(version)\
.one()
except sqlalchemy.orm.exc.NoResultFound:
return exception_response(404)
- current = session.query(table).get(id)
+ current = session.query(Post).get(id)
additions = entry.restore(context['user'], current)
session.addall(additions)
- context['msg'].append('%s restored succesfully.' % ptype.capitalize())
+ context['msg'].append('Post restored succesfully.')
msgs = [('msg', m) for m in context['msg']]
- if ptype == 'post':
- return HTTPFound(location=request.route_url('post', id=entry.id,
- _query=msgs))
- elif ptype == 'page':
- return HTTPFound(location=request.route_url('page', name=entry.name,
- _query=msgs))
- return
+ return HTTPFound(location=request.route_url('post', id=entry.id, page=page,
+ _query=msgs))
def delete(request):
session = DBSession()
context = get_context(request)
-
- ptype = request.matchdict['ptype']
- if ptype == 'post':
- table = Post
- hist_table = Post_History
- else:
- table = Page
- hist_table = Page_History
-
- entry = session.query(table).get(request.matchdict['id'])
- title = entry.title if ptype == 'post' else entry.name
- hist = hist_table(entry)
- session.delete(entry)
-
- context['msg'].append("Deleted %s: %s" % (ptype, title))
+
+ id = request.matchdict['id']
+ page = request.matchdict['page']
+ post = session.query(Post).get(id)
+ title = post.title
+ hist = Post_History(context['uid'], post)
+ session.delete(post)
+ session.add(hist)
+
+ context['msg'].append("Deleted Post: %s" % title)
return context
def history(request):
@@ -391,23 +303,22 @@ def history(request):
context = get_context(request)
- ptype = request.matchdict('ptype')
- name = request.matchdict('id')
+ id = request.matchdict('id')
+ page = request.matchdict('page')
+
+#XXX has a skip attribute that isn't used. Investigate.
if 'skip' in request.params:
skip = request.params.getone('skip')
else:
skip = 0
- table = Page_History if ptype == 'page' else Post_History
-
- q = session.query(table)\
- .order_by(table.changed_on)
- if name != '*' and ptype == 'page': q = q.filter(table.name == id)
- if name != '*' and ptype == 'post': q = q.filter(table.name == id)
+ q = session.query(Post)\
+ .filter(Post.id == id)\
+ .filter(Post.page == page)\
+ .order_by(Post.changed_on)
context['count'] = q.count()
context['skip'] = skip
- context['ptype'] = ptype
context['id'] = id
if skip:
Please sign in to comment.
Something went wrong with that request. Please try again.