1
# -*- coding: utf-8 -*-
2
"""
3
    swtr
4
    ~~~~~~
5
6
    http://swtr.us
7
8
    :license: BSD, see LICENSE for more details.
9
"""
10
from __future__ import with_statement
11
from pymongo import Connection
12
from bson.objectid import ObjectId
13
from bson.errors import InvalidId
14
from flask import Flask, request, session, g, redirect, url_for, abort, \
15
     render_template, flash, _app_ctx_stack, make_response, jsonify
16
from urllib import unquote_plus
17
import json
18
# configuration
19
DATABASE = 'alipiBlog'
20
COLLECTION_NAME = 'posts'
21
DEBUG = True
22
SECRET_KEY = 'development key'
23
USERNAME = 'admin'
24
PASSWORD = 'default'
25
DB_PORT = 27017
26
DB_HOST = 'localhost'
27
URL = "http://localhost:5000"
28
# create our little application :)
29
app = Flask(__name__)
30
app.config.from_object(__name__)
31
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
32
33
34
@app.before_request
35
def init_db():
36
    g.connection = Connection(app.config['DB_HOST'], app.config['DB_PORT'])
37
    db = g.connection[app.config['DATABASE']]
38
    g.collection = db[app.config["COLLECTION_NAME"]]
39
40
41
@app.teardown_request
42
def close_db(exception):
43
    g.connection.disconnect()
44
45
46
@app.errorhandler(404)
47
def page_not_found(e):
48
    return render_template('404.html'), 404
49
50
51
@app.errorhandler(500)
52
def internal_error(e):
53
    return render_template('500.html'), 500
54
55
@app.route('/')
56
def show_entries():
57
    res = g.collection.find().sort('_id',direction=-1)
58
    entries = make_list(res)
59
    return render_template('show_entries.html', entries=entries)
60
61
62
@app.route('/add', methods=['POST'])
63
def add_entry():
64
    response = make_response()
65
    response.headers['Access-Control-Allow-Origin'] = '*'
66
    data = {}
67
    data_list = []
68
    escaped_form_data = json.loads(unquote_plus(request.form['data']))
69
    for i in escaped_form_data:
70
        id = g.collection.insert({'user':i['user'],'title':i['title'], 'text':i['text'],'top':i['top'],'bottom':i['bottom'],'left':i['left'],'right':i['right']})
71
        data['permalink'] = app.config['URL']+'/posts/'+str(ObjectId(id))
72
        data_list.append(data)
73
    response.data = json.dumps(data_list)
74
    return response
75
76
77
@app.route('/login', methods=['GET', 'POST'])
78
def login():
79
    error = None
80
    if request.method == 'POST':
81
        if request.form['username'] != app.config['USERNAME']:
82
            error = 'Invalid username'
83
        elif request.form['password'] != app.config['PASSWORD']:
84
            error = 'Invalid password'
85
        else:
86
            session['logged_in'] = True
87
            flash('You were logged in')
88
            return redirect(url_for('show_entries'))
89
    return render_template('login.html', error=error)
90
91
92
@app.route('/posts/<post_id>',methods=['GET'])
93
def show_specific_entry(post_id):
94
    try:
95
        res = g.collection.find({'_id':ObjectId(post_id)});
96
        if(res.count() > 0):
97
            entries = make_list(res)
98
            return render_template('show_posts.html', entries=entries, str=str)
99
        else:
100
            abort(404)
101
    except InvalidId:
102
        abort(404)
103
104
105
@app.route('/posts/delete/', methods=['POST'])
106
def delete_post():
107
    try:
108
        g.collection.remove({'_id':ObjectId(request.form['post_id'])})
109
    except:
110
        abort(500)
111
112
@app.route('/logout')
113
def logout():
114
    session.pop('logged_in', None)
115
    flash('You were logged out')
116
    return redirect(url_for('show_entries'))
117
118
def make_list(res):
119
    entries = []
120
    for row in res:
121
        d = dict()
122
        d['id'] = str(row['_id'])
123
        d['text'] = row['text']
124
        d["title"] = row["title"]
125
        d["user"] = row["user"]
126
        entries.append(d)
127
    return entries
128
129
if __name__ == '__main__':
130
    app.run()