diff options
| author | Thibaut Horel <thibaut.horel@gmail.com> | 2015-04-01 19:47:16 -0400 |
|---|---|---|
| committer | Thibaut Horel <thibaut.horel@gmail.com> | 2015-04-01 19:47:16 -0400 |
| commit | d8b62f3356578c6b4244ee9348858c8f3a252e3a (patch) | |
| tree | 055b3e0ff59b4ad2ee8bfd73a6f1f50f04860bd8 /famille.py | |
| parent | 334044d3c9c4814759bcc47228be35c7cfacc888 (diff) | |
| download | famille-flask-d8b62f3356578c6b4244ee9348858c8f3a252e3a.tar.gz | |
PEP8
Diffstat (limited to 'famille.py')
| -rw-r--r-- | famille.py | 94 |
1 files changed, 61 insertions, 33 deletions
@@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- import sqlite3 #all the imports -from flask import Flask, request, session, g, redirect, url_for, render_template, flash +from flask import Flask, request, session, g, redirect,\ + url_for, render_template, flash from functools import wraps import hashlib from pytz import timezone @@ -14,8 +15,11 @@ from email import utils from bs4 import BeautifulSoup from flask_mail import Mail, Message import locale + + locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8') + def rstify(string): w = Writer() result = core.publish_parts(string, writer=w)['fragment'] @@ -26,6 +30,7 @@ app = Flask(__name__) app.config.from_envvar('CONF') mail = Mail(app) + @app.template_filter('shortify') def shortify(string): soup = BeautifulSoup(string) @@ -34,53 +39,61 @@ def shortify(string): except IndexError: return string + @app.template_filter('format_date') def format_date(date_object, format=u"%a %d %b %Y à %Hh%M"): if not date_object: return "" format = format.encode("utf8") - return date_object.replace(tzinfo=timezone('utc')). \ - astimezone(timezone(session['timezone'])).strftime(format).decode("utf8") + return date_object.replace(tzinfo=timezone('utc')).\ + astimezone(timezone(session['timezone'])).\ + strftime(format).decode("utf8") + @app.template_filter('format_ago') def format_ago(date_object, format): if not date_object: return "" format = format.encode("utf8") - readable = date_object.replace(tzinfo=timezone('utc')). \ - astimezone(timezone(session['timezone'])).strftime(format) + readable = date_object.replace(tzinfo=timezone('utc')).\ + astimezone(timezone(session['timezone'])).strftime(format) iso_format = date_object.strftime('%Y-%m-%dT%H:%M:%SZ') - return '<span class=timeago title="{0}">{1}</span>'. \ - format(iso_format, readable).decode("utf8") + return '<span class=timeago title="{0}">{1}</span>'.\ + format(iso_format, readable).decode("utf8") + @app.template_filter('format_rfc2822') def format_rfc2822(date_object): timestamp = time.mktime(date_object.timetuple()) return utils.formatdate(timestamp) + @app.template_filter('pluralize') def pluralize(word, count, plural=None): if count == 0: return "Aucun {0}".format(word) elif count == 1: - return "1 {0}".format(word) + return "1 {0}".format(word) elif plural: - return "{0} {1}".format(count, plural) + return "{0} {1}".format(count, plural) else: return "{0} {1}s".format(count, word) + def query_db(query, args=(), one=False): cur = get_db().execute(query, args) rv = cur.fetchone() if one else cur.fetchall() cur.close() return rv + def connect_db(): conn = sqlite3.connect(app.config['DATABASE'], detect_types=sqlite3.PARSE_DECLTYPES) conn.row_factory = sqlite3.Row return conn + def get_db(): db = getattr(g, 'sqlite_db', None) if db is None: @@ -89,6 +102,7 @@ def get_db(): g.timezone = pytz.common_timezones return db + @app.teardown_appcontext def close_db(error): """Closes the database again at the end of the request.""" @@ -96,6 +110,7 @@ def close_db(error): if db: db.close() + def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): @@ -104,20 +119,24 @@ def login_required(f): return f(*args, **kwargs) return decorated_function + @app.route('/') @app.route('/news/') @login_required def list_news(): - news = query_db("SELECT news.*, users.user_name, count(comments.id) as ncomments FROM news " - "LEFT JOIN users ON news.user_id = users.id " - "LEFT JOIN comments ON news.id=comments.news_id GROUP BY news.id " - "ORDER BY news.date DESC") + news = query_db("SELECT news.*, users.user_name, " + "count(comments.id) as ncomments FROM news " + "LEFT JOIN users ON news.user_id = users.id " + "LEFT JOIN comments ON news.id=comments.news_id " + "GROUP BY news.id ORDER BY news.date DESC") comments = query_db("SELECT * from comments LEFT JOIN users " - "ON comments.user_id = users.id ORDER BY date DESC LIMIT 5") + "ON comments.user_id = users.id " + "ORDER BY date DESC LIMIT 5") users = query_db("SELECT * from users ORDER BY last_seen DESC") return render_template("news/list.html", news=news, comments=comments, users=users) + @app.route('/news/add/', methods=['GET', 'POST']) @login_required def add_news(): @@ -127,7 +146,7 @@ def add_news(): if 'Add' in request.form: db = get_db() cur = db.execute("INSERT INTO news " - "('title', 'content', 'user_id', 'content_cache') " + "('title', 'content', 'user_id','content_cache') " "VALUES (?, ?, ?, ?)", (request.form['title'], content, session['user_id'], content_cache)) @@ -136,26 +155,27 @@ def add_news(): # send email emails = query_db("SELECT email from users where notify=1") - emails = [email["email"] for email in emails] + emails = [email["email"] for email in emails if email["email"]] if emails: message = Message(request.form['title'], sender="news.horel@gmail.com") message.html = content_cache url = url_for('show_news', news_id=news_id, _external=True) - message.html += "<p style='margin-top:2em'>Vous pouvez <a href='{0}'>"\ - "Lire cette nouvelle</a> sur le site de la famille.</p>".\ - format(url) + message.html += ("<p style='margin-top:2em'>Vous pouvez " + "<a href='{0}'>Lire cette nouvelle</a> " + "sur le site de la famille.</p>").format(url) message.recipients = emails mail.send(message) return redirect(url_for('show_news', news_id=news_id)) else: - news = {'content': content,'content_cache': content_cache, + news = {'content': content, 'content_cache': content_cache, 'title': request.form['title']} return render_template("news/news.html", news=news) elif request.method == 'GET': return render_template("news/news.html", news=None) + @app.route('/news/<int:news_id>/', methods=['GET', 'POST']) @login_required def show_news(news_id): @@ -180,6 +200,7 @@ def show_news(news_id): db.commit() return redirect(url_for('show_news', news_id=news_id)) + @app.route('/news/<int:news_id>/edit', methods=['GET', 'POST']) @login_required def edit_news(news_id): @@ -194,22 +215,25 @@ def edit_news(news_id): content_cache = rstify(content) db = get_db() db.execute("UPDATE news SET 'title'=?, 'content'=?, 'content_cache'=? " - "WHERE news.id =?", - (title, content, content_cache, news_id)) + "WHERE news.id =?", + (title, content, content_cache, news_id)) db.commit() return redirect(url_for('show_news', news_id=news_id)) + @app.route('/user/<int:user_id>/') @login_required def view_user(user_id): user = query_db('SELECT * FROM users WHERE id= ?', (user_id,), True) return render_template("user/show.html", user=user) + @app.route('/articles/') @login_required def articles(): return render_template("articles/list.html") + @app.route('/user/edit/', methods=['GET', 'POST']) @login_required def edit_user(): @@ -222,35 +246,36 @@ def edit_user(): result = {} try: if request.form['password'] == request.form['password_confirm']: - result['password'] = hashlib.md5(request.form['password']).hexdigest() + result['password'] = hashlib.md5(request.form['password']).\ + hexdigest() else: error = u"Les deux mots de passe ne coïncident pas" return render_template("user/edit.html", user=request.form, error=error) except KeyError: pass - args = tuple(request.form[key] for key in \ - ['email', 'phone', 'birthday', 'nameday', 'address_line1', \ - 'address_line2', 'address_city_line', 'timezone']) + args = tuple(request.form[key] for key in + ['email', 'phone', 'birthday', 'nameday', 'address_line1', + 'address_line2', 'address_city_line', 'timezone']) args += ("notify" in request.form, session['user_id']) - sqlstr = "UPDATE users SET email= ?, phone=?, birthday=?, nameday=?," \ - "address_line1=?, address_line2=?, address_city_line=?, timezone=?, notify=? " \ - "where id=?" + sqlstr = "UPDATE users SET email= ?, phone=?, birthday=?, nameday=?,"\ + "address_line1=?, address_line2=?, address_city_line=?, "\ + "timezone=?, notify=? where id=?" db = get_db() db.execute(sqlstr, args) db.commit() session["timezone"] = request.form["timezone"] return redirect(url_for('view_user', user_id=session['user_id'])) + @app.route('/login/', methods=['GET', 'POST']) def login(): if 'user_name' in session: return redirect(url_for('list_news')) - error = None if request.method == 'POST': username = request.form['username'] - password = hashlib.md5(request.form['password']).hexdigest(); + password = hashlib.md5(request.form['password']).hexdigest() user = query_db('select * from users where user_name = ?', (username,), True) if user: @@ -260,7 +285,7 @@ def login(): session['timezone'] = user['timezone'] or "UTC" db = get_db() db.execute("UPDATE users SET last_seen=? WHERE id=?", - (datetime.utcnow(),session['user_id'])) + (datetime.utcnow(), session['user_id'])) db.commit() return redirect(url_for('list_news')) else: @@ -271,6 +296,7 @@ def login(): return redirect(url_for('login')) return render_template('login.html') + @app.route('/logout/') @login_required def logout(): @@ -278,11 +304,13 @@ def logout(): session.pop('user_id', None) return redirect(url_for('login')) + @app.route('/rss.xml') def rss(): news = query_db("SELECT * FROM news LEFT JOIN users ON " "news.user_id=users.id ORDER BY news.date desc") return render_template('rss.xml', news=news) -if __name__=="__main__": + +if __name__ == "__main__": app.run() |
