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 |
import conf |
19 |
# configuration |
20 |
DATABASE = 'alipiBlog' |
21 |
COLLECTION_NAME = 'posts' |
22 |
DEBUG = True |
23 |
SECRET_KEY = conf.SECRET_KEY |
24 |
USERNAME = 'admin' |
25 |
PASSWORD = 'default' |
26 |
DB_PORT = 27017 |
27 |
DB_HOST = 'localhost' |
28 |
URL = "http://localhost:5001" |
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 |
def validateSweet(payload): |
36 |
for i in payload: |
37 |
if len(i['who']) and len(i['what']) and len(i['where']) and len(i['how']): |
38 |
pass |
39 |
else: |
40 |
return False |
41 |
return True |
42 |
|
43 |
@app.before_request |
44 |
def init_db(): |
45 |
g.connection = Connection(app.config['DB_HOST'], app.config['DB_PORT']) |
46 |
db = g.connection[app.config['DATABASE']] |
47 |
g.collection = db[app.config["COLLECTION_NAME"]] |
48 |
|
49 |
|
50 |
@app.teardown_request |
51 |
def close_db(exception): |
52 |
g.connection.disconnect() |
53 |
|
54 |
|
55 |
@app.errorhandler(404) |
56 |
def page_not_found(e): |
57 |
return render_template('404.html'), 404 |
58 |
|
59 |
|
60 |
@app.errorhandler(500) |
61 |
def internal_error(e): |
62 |
return render_template('500.html'), 500 |
63 |
|
64 |
@app.route('/') |
65 |
def show_entries(): |
66 |
res = g.collection.find().sort('_id',direction=-1) |
67 |
entries = make_list(res) |
68 |
return render_template('show_entries.html', entries=entries) |
69 |
|
70 |
|
71 |
@app.route('/add', methods=['POST']) |
72 |
def add_entry(): |
73 |
response = make_response() |
74 |
response.headers['Access-Control-Allow-Origin'] = '*' |
75 |
data = {} |
76 |
data_list = [] |
77 |
try: |
78 |
payload = json.loads(request.form['data']) |
79 |
except: |
80 |
payload = [{'who': request.form['who'], 'what': request.form['what'], |
81 |
'where': request.form['where'], 'how': request.form['how']}] |
82 |
valid = validateSweet(payload) |
83 |
if not valid: |
84 |
response.status_code = 400 |
85 |
response.data = "Bad or Malformed Request. Please check the validity\ |
86 |
of your request" |
87 |
return response |
88 |
print 'swt payload rcvd..' |
89 |
print payload |
90 |
for i in payload: |
91 |
id = g.collection.insert(i) |
92 |
data['permalink'] = app.config['URL'] + '/posts/' + str(ObjectId(id)) |
93 |
data['id'] = str(ObjectId(id)) |
94 |
data_list.append(data) |
95 |
response.data = json.dumps(data_list) |
96 |
print 'swt stored..' |
97 |
return response |
98 |
|
99 |
|
100 |
@app.route('/login', methods=['GET', 'POST']) |
101 |
def login(): |
102 |
error = None |
103 |
if request.method == 'POST': |
104 |
if request.form['username'] != app.config['USERNAME']: |
105 |
error = 'Invalid username' |
106 |
elif request.form['password'] != app.config['PASSWORD']: |
107 |
error = 'Invalid password' |
108 |
else: |
109 |
session['logged_in'] = True |
110 |
flash('You were logged in') |
111 |
return redirect(url_for('show_entries')) |
112 |
return render_template('login.html', error=error) |
113 |
|
114 |
|
115 |
@app.route('/query/<post_id>',methods=['GET']) |
116 |
def return_database_entry(post_id): |
117 |
try: |
118 |
res = g.collection.find_one({'_id':ObjectId(post_id)}) |
119 |
if(res): |
120 |
res['blog'] = url_for('show_specific_entry', post_id = str(res['_id'])) |
121 |
del(res['_id']) |
122 |
return jsonify(res) |
123 |
# entries = make_list(res) |
124 |
# return render_template('show_posts.html', entries=res, str=str) |
125 |
else: |
126 |
abort(404) |
127 |
except InvalidId: |
128 |
abort(404) |
129 |
|
130 |
|
131 |
|
132 |
@app.route('/posts/<post_id>',methods=['GET']) |
133 |
def show_specific_entry(post_id): |
134 |
try: |
135 |
res = g.collection.find({'_id':ObjectId(post_id)}) |
136 |
if(res.count() > 0): |
137 |
#entries = make_list(res) |
138 |
entries = [] |
139 |
for i in res: |
140 |
_id = i['_id'] |
141 |
del(i['_id']) |
142 |
i['id'] = _id |
143 |
entries.append(i) |
144 |
return render_template('show_posts.html', entries=entries, str=str) |
145 |
else: |
146 |
abort(404) |
147 |
except InvalidId: |
148 |
abort(404) |
149 |
|
150 |
|
151 |
@app.route('/posts/delete/', methods=['POST']) |
152 |
def delete_post(): |
153 |
try: |
154 |
g.collection.remove({'_id':ObjectId(request.form['post_id'])}) |
155 |
return jsonify(status='ok') |
156 |
except: |
157 |
abort(500) |
158 |
|
159 |
@app.route('/logout') |
160 |
def logout(): |
161 |
session.pop('logged_in', None) |
162 |
flash('You were logged out') |
163 |
return redirect(url_for('show_entries')) |
164 |
|
165 |
@app.route('/serveUser') |
166 |
def serveUser(): |
167 |
if "logged_in" in session: |
168 |
print session["logged_in"] |
169 |
session['key'] = conf.SECRET_KEY |
170 |
return render_template('user.html') |
171 |
else: |
172 |
return render_template('login.html', error=None) |
173 |
|
174 |
@app.route('/user', methods=['POST', "GET"]) |
175 |
def user(): |
176 |
if request.method == 'POST': |
177 |
response = make_response() |
178 |
db = g.connection[app.config['DATABASE']] |
179 |
collection = db['sweet_users'] |
180 |
collection.insert({'user':request.form["user"],"key":request.form["key"]}) |
181 |
return response |
182 |
elif request.method == 'GET': |
183 |
db = g.connection[app.config['DATABASE']] |
184 |
collection = db['sweet_users'] |
185 |
users = [] |
186 |
for user in collection.find(): |
187 |
users.append(user['user']) |
188 |
return render_template("users.html", users=users) |
189 |
|
190 |
|
191 |
@app.route('/authenticate', methods=['POST','GET']) |
192 |
def authenticate(): |
193 |
if request.method == "POST": |
194 |
response = make_response() |
195 |
db = g.connection[app.config['DATABASE']] |
196 |
collection = db['sweet_users'] |
197 |
for i in collection.find(): |
198 |
if i['user'] == request.form['user'] and i['key'] == request.form['hash']: |
199 |
response.status_code = 200 |
200 |
response.headers['Access-Control-Allow-Origin'] = '*' |
201 |
return response |
202 |
else: |
203 |
response.status_code = 403 |
204 |
response.headers['Access-Control-Allow-Origin'] = '*' |
205 |
return response |
206 |
elif request.method == "GET": |
207 |
return app.send_static_file("sweet-authenticate.js") |
208 |
|
209 |
|
210 |
def make_list(res): |
211 |
entries = [] |
212 |
for row in res: |
213 |
d = row |
214 |
d['id'] = str(row['_id']) |
215 |
# d['text'] = row['text'] |
216 |
# d["title"] = row["title"] |
217 |
# d["user"] = row["user"] |
218 |
entries.append(d) |
219 |
return entries |
220 |
|
221 |
if __name__ == '__main__': |
222 |
app.run(debug=True, port=5001) |