class DB(object):
    engine = None
    db_session = None

    def __init__(self, dbstring):
        self.engine = create_engine(dbstring, convert_unicode=True)
        self.db_session = scoped_session(sessionmaker(autocommit=False,
                                                 autoflush=False,
                                                 bind=self.engine))
        Base.query = self.db_session.query_property()

    def get_session(self):
        return self.db_session class User(Base,ImposterBase):
    __tablename__ = tn('users')

    id = Column(Integer, primary_key=True)
    username = Column(String(64), nullable=False, unique=True)
    password = Column(String(256), nullable=False)

    __public_columns__ = [ username ]

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def __unicode__(self):
        return self.username

    def __repr__(self):
        return '<User %r>' % self.username class Tag(Base,ImposterBase):
    __tablename__ = tn('tags')

    id = Column(Integer, primary_key=True)
    value = Column(String(64), nullable=False, unique=True)
    count = Column(Integer, default=0)

    __public_columns__ = [ value, count ]

    def __init__(self, value):
        self.value = value

    def __unicode__(self):
        return self.value

    def __repr__(self):
        return '<Tag %r>' % self.value class Format(Base,ImposterBase):
    __tablename__ = tn('formats')
    id = Column(Integer, primary_key=True)
    value = Column(String(32), nullable=False, unique=True)

    __public_columns__ = [ value ]

    def __init__(self, value):
        self.value = value

    def __unicode__(self):
        return self.value

    def __repr__(self):
        return '<Format %r>' % self.value class Status(Base,ImposterBase):
    __tablename__ = tn('status')

    id = Column(Integer, primary_key=True)
    value = Column(String(32), unique=True)

    __public_columns__ = [ value ]

    def __init__(self, value):
        self.value = value

    def __unicode__(self):
        return self.value

    def __repr__(self):
        return '<Status %r>' % self.value class Post(Base,ImposterBase):
    __tablename__ = tn('posts')

    id = Column(Integer, primary_key=True)
    title = Column(String(200), nullable=False)
    slug = Column(String(128), nullable=False)
    summary = Column(Text, nullable=True)
    content = Column(Text, nullable=False)
    status_id = Column(Integer, ForeignKey(Status.id), nullable=False)
    user_id = Column(Integer, ForeignKey(User.id), nullable=False)
    format_id = Column(Integer, ForeignKey(Format.id), nullable=False)

    createdate = Column(DateTime, nullable=False)
    pubdate = Column(DateTime, nullable=True)
    lastmoddate = Column(DateTime, nullable=False)

    status = relationship(Status, backref='posts')
    user = relationship(User, backref='posts')
    tags = relationship('Tag', secondary=post_tags, backref='posts')
    format = relationship(Format, backref='posts')

    summary_html = Column(Text, nullable=True)
    content_html = Column(Text, nullable=True)

    __public_columns__ = [ title, slug, summary_html, content_html, pubdate, lastmoddate, tags ]

    def __init__(self, title=None, summary=None, content=None, createdate=None, pubdate=None, lastmoddate=None):
        self.title = title
        self.summary = summary
        self.content = content
        self.createdate = createdate
        self.pubdate = pubdate
        self.lastmoddate = lastmoddate

    def compile(self, repl=None):
        input_summary = self.summary
        input_content = self.content
        if repl is not None:
            input_summary = multi_replace(input_summary, repl)
            input_content = multi_replace(input_content, repl)

        self.summary_html = markup_to_html(self.format, input_summary)
        self.content_html = markup_to_html(self.format, input_content)

    def __repr__(self):
        return '<Post %s>' % self.title

    @property
    def year(self):
        return self.pubdate.year

    @property
    def month(self):
        return '%02d' % self.pubdate.month

    @property
    def day(self):
        return '%02d' % self.pubdate.day class Page(Base):
    __tablename__ = tn('pages')

    id = Column(Integer, primary_key=True)
    title = Column(String(200), unique=True, nullable=False)
    slug = Column(String(128), unique=True, nullable=False)
    content = Column(Text, nullable=False)
    status_id = Column(Integer, ForeignKey(Status.id), nullable=False)
    user_id = Column(Integer, ForeignKey(User.id), nullable=False)
    format_id = Column(Integer, ForeignKey(Format.id), nullable=False)
    content_html = Column(Text, nullable=True)

    createdate = Column(DateTime, nullable=False)
    pubdate = Column(DateTime, nullable=True)
    lastmoddate = Column(DateTime, nullable=False)

    status = relationship(Status, backref='pages')
    user = relationship(User, backref='pages')
    format = relationship(Format, backref='pages')

    __public_columns__ = [ title, slug, content_html, pubdate, lastmoddate ]

    def __init__(self, title=None, content=None, createdate=None, pubdate=None, lastmoddate=None):
        self.title = title
        self.content = content
        self.createdate = createdate
        self.pubdate = pubdate
        self.lastmoddate = lastmoddate

    def compile(self, repl=None):
        input_content = self.content
        if repl is not None:
            input_content = multi_replace(input_content, repl)

        self.content_html = markup_to_html(self.format, input_content)

    def __repr__(self):
        return '<Page %s>' % self.title def filter_public():
    """Make sure we only can retrieve Post objects marked as public"""
    return and_(Post.status_id==Status.id,
                Status.value=='public',
                Post.user_id==User.id,
                Post.pubdate <= datetime.now()
               ) class PostForm(Form):
    """Form for the Post objects from Imposter.models"""
    title = TextField('Title', validators=\
                      [Required(message='Title is required.')])
    tags = TagListField('Tags', validators=\
                        [Required(message='Tags are required')])
    pubdate = DateTimeField('Publication date', format='%Y-%m-%d %H:%M',
                            validators=\
                            [Required(message='Wrong date or date format.')])
    format = FormatField('Format', choices=[('markdown','Markdown'),
                                            ('rest', 'ReStructuredText')],
                         validators=\
                         [Required(message='Please pick a format')])
    status = StatusField('Status', choices=[('draft','Draft'),
                                            ('private','Private'),
                                            ('public','Public')],
                         validators=\
                         [Required(message='Please pick a status')])
    summary = TextAreaField('Summary', validators=\
                            [Required('Summary is required.')])
    content = TextAreaField('Content', validators=\
                            [Required('Content is required.')]) class PageForm(Form):
    """Form for the Page objects from Imposter.models"""
    title = TextField('Title', validators=\
                      [Required(message='Title is required.')])
    pubdate = DateTimeField('Publication date', format='%Y-%m-%d %H:%M',
                            validators=\
                            [Required(message='Wrong date or date format.')])
    format = FormatField('Format', choices=[('markdown','Markdown'),
                                            ('rest', 'ReStructuredText')],
                         validators=\
                         [Required(message='Please pick a format')])
    status = StatusField('Status', choices=[('draft','Draft'),
                                            ('private','Private'),
                                            ('public','Public')],
                         validators=\
                         [Required(message='Please pick a status')])
    content = TextAreaField('Content', validators=\
                            [Required('Content is required.')]) class LoginForm(Form):
    username = TextField('Username', validators=[Required(message='Username is required.')])
    password = PasswordField('Password', validators=[Required(message='Password is required.')])
from flask import Flask, request, session, abort, redirect, url_for, flash
from functools import wraps
from database import DB
from models import User, Tag, Format, Status, Post, Page
from datetime import datetime
from sqlalchemy.sql import and_
from flaskjk import Viewer, Paginator, validate_password, slugify
from frontend import filter_public
from forms import PostForm, PageForm, LoginForm
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Description {{{
"""
    imposter.admin
    ~~~~~~~~~~~~~~

    Admin interface for the Imposter weblog app

    :copyright: (c) 2010-2011 by Jochem Kossen.
    :license: BSD, see LICENSE.txt for more details.
"""
# }}}

# Imports {{{
from __future__ import with_statement
# }}}

# Initialization {{{
app = Flask(__name__, static_path=None)
app.config.from_pyfile('config_admin.py')
app.config.from_envvar('IMPOSTER_ADMIN_CONFIG', silent=True)
db_session = DB(app.config['DATABASE']).get_session()
viewer = Viewer(app, 'admin')

# base query used in all frontend retrieve queries

public_posts_base = db_session.query(Post, Status, User).filter(filter_public())