rascunho

ref: 0.0.3

rascunho/blueprints/basic.py


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from flask import Blueprint, render_template, request, abort, Response, redirect, url_for
from rascunho.database import db
from rascunho.types.document import Document
from hashlib import sha1

basic = Blueprint('basic', __name__)

@basic.route("/", methods = ['GET', 'POST'])
def index():
    if request.method == "GET":
        doc = Document.query.filter(Document.frontmatter==True).first()
        return render_template('index.html', doc = doc)
    else:
        return create(request.form)

@basic.route("/<sha>", methods = ['GET'])
def show(sha):
    doc = Document.query.filter(Document.sha == sha).one_or_none()

    if not doc:
        abort(404)

    return render_template('preview.html', doc = doc)

@basic.route("/<sha>/raw", methods = ['GET'])
def raw(sha):
    doc = Document.query.filter(Document.sha == sha).one_or_none()

    if not doc:
        abort(404)

    return Response(doc.content, mimetype="text/plain")

def create(params):
    doc = None
    content = params['text']

    if not content:
        abort(422)

    sha = sha1()
    sha.update(content.encode())
    sha.update(request.remote_addr.encode())

    existing_doc = Document.query.filter(Document.sha == sha.hexdigest()).one_or_none()

    if existing_doc:
        doc = existing_doc
    else:
        doc = Document()

    doc.sha = sha.hexdigest()
    doc.content = content

    db.add(doc)
    db.commit()
    db.flush()

    return redirect(url_for('basic.show', sha = doc.sha))