flask-rest-wiki / flaskrest.py

from __future__ import with_statement
from sqlite3 import dbapi2 as sqlite3
from contextlib import closing
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash
from docutils.core import publish_parts


def fromhere(path):
    import os
    return os.path.join(os.path.dirname(__file__), path)


# configuration
DATABASE = fromhere('flaskrest.db')
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'

# disable docutils security hazards:
# http://docutils.sourceforge.net/docs/howto/security.html
SAFE_DOCUTILS = dict(file_insertion_enabled=False, raw_enabled=False)

# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)


def connect_db():
    """Returns a new connection to the database."""
    return sqlite3.connect(app.config['DATABASE'])


def init_db():
    """Creates the database tables."""
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql') as f:
            db.cursor().executescript(f.read())
        db.commit()


@app.before_request
def before_request():
    """Make sure we are connected to the database each request."""
    g.db = connect_db()


@app.after_request
def after_request(response):
    """Closes the database again at the end of the request."""
    g.db.close()
    return response


@app.route('/')
def index():
    return redirect(url_for("page", title=''))


@app.route('/save/', defaults={'title': ''}, methods=['POST'])
@app.route('/save/<path:title>/', methods=['POST'])
def save(title):
    print request.method, request.args
    g.db.execute(
        'insert or replace into pages (title, body) values (?, ?)',
        [title, request.form['body']])
    g.db.commit()
    flash('Saved!')
    return redirect(url_for("page", title=title))


@app.route('/edit/', defaults={'title': ''})
@app.route('/edit/<path:title>/', methods=['GET', 'POST'])
def edit(title):
    body = g.db.execute('select body from pages where title = ?',
                        [title]).fetchone()
    return render_template("edit.html",
                           title=title,
                           text=body[0] if body else '')

@app.route('/page/', defaults={'title': ''})
@app.route('/page/<path:title>/')
def page(title):
    body = g.db.execute('select body from pages where title = ?',
                        [title]).fetchone()
    if body:
        htmltext = publish_parts(
            body[0], writer_name='html',
            settings_overrides=SAFE_DOCUTILS)['html_body']
        return render_template("page.html",
                               title=title, htmltext=htmltext)
    else:
        return redirect(url_for('edit', title=title))


if __name__ == '__main__':
    app.run()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.