Commit af3c1ff7da92f26dd57e9bc44b126b1bd370d3eb

  • avatar
  • arvind
  • Mon Jan 07 19:45:49 IST 2013
				- Added a <username> field.
				- Posts/tweets have permalink.
swtr.py
(112 / 0)
  
1# -*- coding: utf-8 -*-
2"""
3 swtr
4 ~~~~~~
5
6 http://swtr.us
7
8 :license: BSD, see LICENSE for more details.
9"""
10from __future__ import with_statement
11from pymongo import Connection
12from bson.objectid import ObjectId
13from bson.errors import InvalidId
14from flask import Flask, request, session, g, redirect, url_for, abort, \
15 render_template, flash, _app_ctx_stack
16
17# configuration
18DATABASE = 'alipiBlog'
19COLLECTION_NAME = 'posts'
20DEBUG = True
21SECRET_KEY = 'development key'
22USERNAME = 'admin'
23PASSWORD = 'default'
24DB_PORT = 27017
25DB_HOST = 'localhost'
26
27# create our little application :)
28app = Flask(__name__)
29app.config.from_object(__name__)
30app.config.from_envvar('FLASKR_SETTINGS', silent=True)
31
32
33@app.before_request
34def init_db():
35 g.connection = Connection(app.config['DB_HOST'], app.config['DB_PORT'])
36 db = g.connection[app.config['DATABASE']]
37 g.collection = db[app.config["COLLECTION_NAME"]]
38
39
40@app.teardown_request
41def close_db(exception):
42 g.connection.disconnect()
43
44
45@app.errorhandler(400)
46def page_not_found(e):
47 return render_template('404.html'), 404
48
49
50@app.route('/')
51def show_entries():
52 res = g.collection.find().sort('_id',direction=-1)
53 entries = make_list(res)
54 return render_template('show_entries.html', entries=entries)
55
56
57@app.route('/add', methods=['POST'])
58def add_entry():
59 if not session.get('logged_in'):
60 abort(401)
61 g.collection.insert({'user':request.form['user'],'title':request.form['title'], 'text':request.form['text']})
62 flash('New entry was successfully posted')
63 return redirect(url_for('show_entries'))
64
65
66@app.route('/login', methods=['GET', 'POST'])
67def login():
68 error = None
69 if request.method == 'POST':
70 if request.form['username'] != app.config['USERNAME']:
71 error = 'Invalid username'
72 elif request.form['password'] != app.config['PASSWORD']:
73 error = 'Invalid password'
74 else:
75 session['logged_in'] = True
76 flash('You were logged in')
77 return redirect(url_for('show_entries'))
78 return render_template('login.html', error=error)
79
80
81@app.route('/posts/<post_id>',methods=['GET'])
82def show_specific_entry(post_id):
83 try:
84 res = g.collection.find({'_id':ObjectId(post_id)});
85 if(res.count() > 0):
86 entries = make_list(res)
87 return render_template('show_posts.html', entries=entries)
88 else:
89 abort(400)
90 except InvalidId:
91 abort(400)
92
93
94@app.route('/logout')
95def logout():
96 session.pop('logged_in', None)
97 flash('You were logged out')
98 return redirect(url_for('show_entries'))
99
100def make_list(res):
101 entries = []
102 for row in res:
103 d = dict()
104 d['id'] = str(row['_id'])
105 d['text'] = row['text']
106 d["title"] = row["title"]
107 d["user"] = row["user"]
108 entries.append(d)
109 return entries
110
111if __name__ == '__main__':
112 app.run()
  
11<!doctype html>
2<title>Flaskr</title>
2<title>Swtr</title>
33<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
44<div class=page>
5 <h1>Flaskr</h1>
5 <h1>Swtrr</h1>
66 <div class=metanav>
77 {% if not session.logged_in %}
88 <a href="{{ url_for('login') }}">log in</a>
  
33 {% if session.logged_in %}
44 <form action="{{ url_for('add_entry') }}" method=post class=add-entry>
55 <dl>
6 <dt>Name:
7 <dd><input type=text name=user>
68 <dt>Title:
79 <dd><input type=text size=30 name=title>
810 <dt>Text:
1515 {% endif %}
1616 <ul class=entries>
1717 {% for entry in entries %}
18 <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
18 <li><a href={{ "/posts/"+entry.id }}><h2>{{ entry.title }}</h2></a>@<b>{{ entry.user }}</b>
19 {{ entry.text|safe }}
1920 {% else %}
2021 <li><em>Unbelievable. No entries here so far</em>
2122 {% endfor %}
  
22<body>
33<ul class=entries>
44 {% for entry in entries %}
5 <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
5 <li><h2>{{ entry.title }}</h2>@<b>{{entry.user}}</b>
6 {{ entry.text|safe }}
67 {% endfor %}
78</ul>
89</body>