af3c1ff by Arvind at 2013-01-07 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, \
de07eb4 by Arvind at 2013-01-09 15
     render_template, flash, _app_ctx_stack, make_response, jsonify
16
from urllib import unquote_plus
17
import json
c70fe3f by Arvind Khadri at 2013-06-19 18
import conf
af3c1ff by Arvind at 2013-01-07 19
# configuration
20
DATABASE = 'alipiBlog'
21
COLLECTION_NAME = 'posts'
22
DEBUG = True
c70fe3f by Arvind Khadri at 2013-06-19 23
SECRET_KEY = conf.SECRET_KEY
af3c1ff by Arvind at 2013-01-07 24
USERNAME = 'admin'
25
PASSWORD = 'default'
26
DB_PORT = 27017
27
DB_HOST = 'localhost'
df78035 by Arvind Khadri at 2013-06-24 28
URL = "http://localhost:5001"
af3c1ff by Arvind at 2013-01-07 29
# create our little application :)
30
app = Flask(__name__)
31
app.config.from_object(__name__)
32
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
33
34
35
@app.before_request
36
def init_db():
37
    g.connection = Connection(app.config['DB_HOST'], app.config['DB_PORT'])
38
    db = g.connection[app.config['DATABASE']]
39
    g.collection = db[app.config["COLLECTION_NAME"]]
40
41
42
@app.teardown_request
43
def close_db(exception):
44
    g.connection.disconnect()
45
46
de07eb4 by Arvind at 2013-01-09 47
@app.errorhandler(404)
af3c1ff by Arvind at 2013-01-07 48
def page_not_found(e):
49
    return render_template('404.html'), 404
50
51
ce32b69 by Arvind at 2013-01-08 52
@app.errorhandler(500)
347ae26 by Arvind at 2013-01-08 53
def internal_error(e):
54
    return render_template('500.html'), 500
55
af3c1ff by Arvind at 2013-01-07 56
@app.route('/')
57
def show_entries():
58
    res = g.collection.find().sort('_id',direction=-1)
59
    entries = make_list(res)
60
    return render_template('show_entries.html', entries=entries)
61
62
63
@app.route('/add', methods=['POST'])
64
def add_entry():
de07eb4 by Arvind at 2013-01-09 65
    response = make_response()
66
    response.headers['Access-Control-Allow-Origin'] = '*'
67
    data = {}
68
    data_list = []
952ce97 by Arvind Khadri at 2013-05-29 69
    print request.form['data']
1a7990c by Arvind at 2013-04-26 70
    for i in json.loads(request.form['data']):
71
        id = g.collection.insert(i)
de07eb4 by Arvind at 2013-01-09 72
        data['permalink'] = app.config['URL']+'/posts/'+str(ObjectId(id))
1a7990c by Arvind at 2013-04-26 73
        data['id'] = str(ObjectId(id))
de07eb4 by Arvind at 2013-01-09 74
        data_list.append(data)
75
    response.data = json.dumps(data_list)
76
    return response
af3c1ff by Arvind at 2013-01-07 77
78
79
@app.route('/login', methods=['GET', 'POST'])
80
def login():
81
    error = None
82
    if request.method == 'POST':
83
        if request.form['username'] != app.config['USERNAME']:
84
            error = 'Invalid username'
85
        elif request.form['password'] != app.config['PASSWORD']:
86
            error = 'Invalid password'
87
        else:
88
            session['logged_in'] = True
89
            flash('You were logged in')
90
            return redirect(url_for('show_entries'))
91
    return render_template('login.html', error=error)
92
93
1a7990c by Arvind at 2013-04-26 94
@app.route('/query/<post_id>',methods=['GET'])
95
def return_database_entry(post_id):
96
    try:
97
        res = g.collection.find_one({'_id':ObjectId(post_id)})
98
        if(res):
99
            res['blog'] = url_for('show_specific_entry', post_id = str(res['_id']))
100
            del(res['_id'])
101
            return jsonify(res)
102
            # entries = make_list(res)
103
            # return render_template('show_posts.html', entries=res, str=str)
104
        else:
105
            abort(404)
106
    except InvalidId:
107
        abort(404)
108
109
110
af3c1ff by Arvind at 2013-01-07 111
@app.route('/posts/<post_id>',methods=['GET'])
112
def show_specific_entry(post_id):
113
    try:
1a7990c by Arvind at 2013-04-26 114
        res = g.collection.find({'_id':ObjectId(post_id)})
115
        print res
af3c1ff by Arvind at 2013-01-07 116
        if(res.count() > 0):
1a7990c by Arvind at 2013-04-26 117
            #entries = make_list(res)
118
            return render_template('show_posts.html', entries=res, str=str)
af3c1ff by Arvind at 2013-01-07 119
        else:
de07eb4 by Arvind at 2013-01-09 120
            abort(404)
af3c1ff by Arvind at 2013-01-07 121
    except InvalidId:
de07eb4 by Arvind at 2013-01-09 122
        abort(404)
af3c1ff by Arvind at 2013-01-07 123
124
347ae26 by Arvind at 2013-01-08 125
@app.route('/posts/delete/', methods=['POST'])
126
def delete_post():
127
    try:
128
        g.collection.remove({'_id':ObjectId(request.form['post_id'])})
129
    except:
130
        abort(500)
131
af3c1ff by Arvind at 2013-01-07 132
@app.route('/logout')
133
def logout():
134
    session.pop('logged_in', None)
135
    flash('You were logged out')
136
    return redirect(url_for('show_entries'))
137
c70fe3f by Arvind Khadri at 2013-06-19 138
@app.route('/serveUser')
139
def serveUser():
df78035 by Arvind Khadri at 2013-06-24 140
    if "logged_in" in session:
141
        print session["logged_in"]
142
        session['key'] = conf.SECRET_KEY
143
        return render_template('user.html')
144
    else:
145
        return render_template('login.html', error=None)
c70fe3f by Arvind Khadri at 2013-06-19 146
147
@app.route('/user', methods=['POST', "GET"])
148
def user():
149
    if request.method == 'POST':
150
        response = make_response()
151
        db = g.connection[app.config['DATABASE']]
152
        collection = db['sweet_users']
153
        collection.insert({'user':request.form["user"],"key":request.form["key"]})
154
        return response
155
    elif request.method == 'GET':
156
        db = g.connection[app.config['DATABASE']]
157
        collection = db['sweet_users']
158
        users = []
159
        for user in collection.find():
160
            users.append(user['user'])
161
        return render_template("users.html", users=users)
162
163
df78035 by Arvind Khadri at 2013-06-24 164
@app.route('/authenticate', methods=['POST','GET'])
165
def authenticate():
166
    if request.method == "POST":
167
        response = make_response()
168
        db = g.connection[app.config['DATABASE']]
169
        collection = db['sweet_users']
170
        for i in collection.find():
171
            if i['user'] == request.form['user'] and i['key'] == request.form['hash']:
172
                response.status_code = 200
173
                response.headers['Access-Control-Allow-Origin'] = '*'
174
                return response
175
            else:
176
                response.status_code = 403
177
                response.headers['Access-Control-Allow-Origin'] = '*'
178
                return response
179
    elif request.method == "GET":
180
        return app.send_static_file("sweet-authenticate.js")
181
182
af3c1ff by Arvind at 2013-01-07 183
def make_list(res):
184
    entries = []
185
    for row in res:
1a7990c by Arvind at 2013-04-26 186
        d = row
af3c1ff by Arvind at 2013-01-07 187
        d['id'] = str(row['_id'])
1a7990c by Arvind at 2013-04-26 188
        # d['text'] = row['text']
189
        # d["title"] = row["title"]
190
        # d["user"] = row["user"]
af3c1ff by Arvind at 2013-01-07 191
        entries.append(d)
192
    return entries
193
194
if __name__ == '__main__':
1a7990c by Arvind at 2013-04-26 195
    app.run(debug=True, port=5001)