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:5000"
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
43
@app.teardown_request
44
def close_db(exception):
45
    g.connection.disconnect()
46
47
48
@app.errorhandler(404)
49
def page_not_found(e):
50
    return render_template('404.html'), 404
51
52
53
@app.errorhandler(500)
54
def internal_error(e):
55
    return render_template('500.html'), 500
56
57
@app.route('/')
58
def show_entries():
59
    res = g.collection.find().sort('_id',direction=-1)
60
    entries = make_list(res)
61
    return render_template('show_entries.html', entries=entries)
62
63
64
@app.route('/add', methods=['POST'])
65
def add_entry():
66
    response = make_response()
67
    response.headers['Access-Control-Allow-Origin'] = '*'
68
    data = {}
69
    data_list = []
70
    print request.form['data']
71
    for i in json.loads(request.form['data']):
72
        id = g.collection.insert(i)
73
        data['permalink'] = app.config['URL']+'/posts/'+str(ObjectId(id))
74
        data['id'] = str(ObjectId(id))
75
        data_list.append(data)
76
    response.data = json.dumps(data_list)
77
    return response
78
79
80
@app.route('/login', methods=['GET', 'POST'])
81
def login():
82
    error = None
83
    if request.method == 'POST':
84
        if request.form['username'] != app.config['USERNAME']:
85
            error = 'Invalid username'
86
        elif request.form['password'] != app.config['PASSWORD']:
87
            error = 'Invalid password'
88
        else:
89
            session['logged_in'] = True
90
            flash('You were logged in')
91
            return redirect(url_for('show_entries'))
92
    return render_template('login.html', error=error)
93
94
95
@app.route('/query/<post_id>',methods=['GET'])
96
def return_database_entry(post_id):
97
    try:
98
        res = g.collection.find_one({'_id':ObjectId(post_id)})
99
        if(res):
100
            res['blog'] = url_for('show_specific_entry', post_id = str(res['_id']))
101
            del(res['_id'])
102
            return jsonify(res)
103
            # entries = make_list(res)
104
            # return render_template('show_posts.html', entries=res, str=str)
105
        else:
106
            abort(404)
107
    except InvalidId:
108
        abort(404)
109
110
111
112
@app.route('/posts/<post_id>',methods=['GET'])
113
def show_specific_entry(post_id):
114
    try:
115
        res = g.collection.find({'_id':ObjectId(post_id)})
116
        print res
117
        if(res.count() > 0):
118
            #entries = make_list(res)
119
            return render_template('show_posts.html', entries=res, str=str)
120
        else:
121
            abort(404)
122
    except InvalidId:
123
        abort(404)
124
125
126
@app.route('/posts/delete/', methods=['POST'])
127
def delete_post():
128
    try:
129
        g.collection.remove({'_id':ObjectId(request.form['post_id'])})
130
    except:
131
        abort(500)
132
133
@app.route('/logout')
134
def logout():
135
    session.pop('logged_in', None)
136
    flash('You were logged out')
137
    return redirect(url_for('show_entries'))
138
139
@app.route('/serveUser')
140
def serveUser():
141
    session['key'] = conf.SECRET_KEY
142
    return render_template('user.html')
143
144
145
@app.route('/user', methods=['POST', "GET"])
146
def user():
147
    if request.method == 'POST':
148
        response = make_response()
149
        db = g.connection[app.config['DATABASE']]
150
        collection = db['sweet_users']
151
        collection.insert({'user':request.form["user"],"key":request.form["key"]})
152
        return response
153
    elif request.method == 'GET':
154
        db = g.connection[app.config['DATABASE']]
155
        collection = db['sweet_users']
156
        users = []
157
        for user in collection.find():
158
            users.append(user['user'])
159
        return render_template("users.html", users=users)
160
161
162
def make_list(res):
163
    entries = []
164
    for row in res:
165
        d = row
166
        d['id'] = str(row['_id'])
167
        # d['text'] = row['text']
168
        # d["title"] = row["title"]
169
        # d["user"] = row["user"]
170
        entries.append(d)
171
    return entries
172
173
if __name__ == '__main__':
174
    app.run(debug=True, port=5001)