diff options
author | François Schmidts <francois.schmidts@gmail.com> | 2015-01-17 16:50:38 +0100 |
---|---|---|
committer | François Schmidts <francois.schmidts@gmail.com> | 2015-03-03 22:22:14 +0100 |
commit | 2849c82255b4b889c7342a0a8fa8a4aecfbe599d (patch) | |
tree | 3ad31fd3a0e84bc3f40367cf4963cf8db8c65d06 | |
parent | adding news fields and migrations scripts (diff) | |
download | newspipe-2849c82255b4b889c7342a0a8fa8a4aecfbe599d.tar.gz newspipe-2849c82255b4b889c7342a0a8fa8a4aecfbe599d.tar.bz2 newspipe-2849c82255b4b889c7342a0a8fa8a4aecfbe599d.zip |
a first big refacto of the existing arch
-rw-r--r-- | bootstrap.py | 23 | ||||
-rwxr-xr-x | db_create.py | 10 | ||||
-rwxr-xr-x | manager.py | 8 | ||||
-rw-r--r-- | pyaggr3g470r/__init__.py | 49 | ||||
-rw-r--r-- | pyaggr3g470r/controllers/__init__.py | 5 | ||||
-rw-r--r-- | pyaggr3g470r/controllers/abstract.py | 47 | ||||
-rw-r--r-- | pyaggr3g470r/controllers/article.py | 20 | ||||
-rw-r--r-- | pyaggr3g470r/controllers/feed.py | 6 | ||||
-rw-r--r-- | pyaggr3g470r/decorators.py | 23 | ||||
-rw-r--r-- | pyaggr3g470r/lib/exceptions.py | 13 | ||||
-rw-r--r-- | pyaggr3g470r/models/__init__.py | 3 | ||||
-rw-r--r-- | pyaggr3g470r/notifications.py | 5 | ||||
-rwxr-xr-x | pyaggr3g470r/utils.py | 9 | ||||
-rw-r--r-- | pyaggr3g470r/views/__init__.py | 3 | ||||
-rw-r--r-- | pyaggr3g470r/views/api/article.py | 40 | ||||
-rw-r--r-- | pyaggr3g470r/views/api/common.py | 47 | ||||
-rw-r--r-- | pyaggr3g470r/views/api/feed.py | 32 | ||||
-rw-r--r-- | pyaggr3g470r/views/article.py | 53 | ||||
-rw-r--r-- | pyaggr3g470r/views/feed.py | 50 | ||||
-rw-r--r-- | pyaggr3g470r/views/views.py | 278 | ||||
-rwxr-xr-x | runserver.py | 40 |
21 files changed, 423 insertions, 341 deletions
diff --git a/bootstrap.py b/bootstrap.py index d13d4799..bb1d1278 100644 --- a/bootstrap.py +++ b/bootstrap.py @@ -1,5 +1,6 @@ # required imports and code exection for basic functionning +import os import sys if 'threading' in sys.modules: raise Exception('threading module loaded before patching!') @@ -11,8 +12,6 @@ if not (conf.WEBSERVER_DEBUG or conf.ON_HEROKU): gevent.monkey.patch_thread() - - def set_logging(log_path, log_level=logging.INFO, log_format='%(asctime)s %(levelname)s %(message)s'): logger = logging.getLogger('pyaggr3g470r') @@ -23,3 +22,23 @@ def set_logging(log_path, log_level=logging.INFO, logger.setLevel(log_level) set_logging(conf.LOG_PATH) + +from flask import Flask +from flask.ext.sqlalchemy import SQLAlchemy + +# Create Flask application +application = Flask(__name__, static_folder='pyaggr3g470r/static', + template_folder='pyaggr3g470r/templates') +application.debug = conf.WEBSERVER_DEBUG + +# Create dummy secrey key so we can use sessions +application.config['SECRET_KEY'] = getattr(conf, 'WEBSERVER_SECRET', None) +if not application.config['SECRET_KEY']: + application.config['SECRET_KEY'] = os.urandom(12) +application.config['SQLALCHEMY_DATABASE_URI'] = conf.SQLALCHEMY_DATABASE_URI + +application.config['RECAPTCHA_USE_SSL'] = True +application.config['RECAPTCHA_PUBLIC_KEY'] = conf.RECAPTCHA_PUBLIC_KEY +application.config['RECAPTCHA_PRIVATE_KEY'] = conf.RECAPTCHA_PRIVATE_KEY + +db = SQLAlchemy(application) diff --git a/db_create.py b/db_create.py index 8e743515..c10e4d43 100755 --- a/db_create.py +++ b/db_create.py @@ -10,8 +10,8 @@ __license__ = "AGPLv3" import os import bootstrap +from flask import g -from pyaggr3g470r import db from pyaggr3g470r.models import User, Role from werkzeug import generate_password_hash @@ -64,8 +64,8 @@ def db_DropEverything(db): trans.commit() -db_DropEverything(db) -db.create_all() +db_DropEverything(g.db) +g.db.create_all() role_admin = Role(name="admin") role_user = Role(name="user") @@ -76,5 +76,5 @@ user1 = User(nickname="admin", activation_key="") user1.roles.extend([role_admin, role_user]) -db.session.add(user1) -db.session.commit() +g.db.session.add(user1) +g.db.session.commit() @@ -1,14 +1,12 @@ #!/usr/bin/env python - +from bootstrap import application, db from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand -from pyaggr3g470r import app, db - -Migrate(app, db) +Migrate(application, db) -manager = Manager(app) +manager = Manager(application) manager.add_command('db', MigrateCommand) diff --git a/pyaggr3g470r/__init__.py b/pyaggr3g470r/__init__.py index 0138b4d3..e69de29b 100644 --- a/pyaggr3g470r/__init__.py +++ b/pyaggr3g470r/__init__.py @@ -1,49 +0,0 @@ -#! /usr/bin/env python -# -*- coding: utf-8 -*- - -import os -from flask import Flask -from flask.ext.sqlalchemy import SQLAlchemy -from flask.ext.babel import Babel -from flask.ext.babel import format_datetime - -import conf - -# Create Flask application -app = Flask(__name__) -app.debug = conf.WEBSERVER_DEBUG - -# Create dummy secrey key so we can use sessions -app.config['SECRET_KEY'] = getattr(conf, 'WEBSERVER_SECRET', None) -if not app.config['SECRET_KEY']: - app.config['SECRET_KEY'] = os.urandom(12) -app.config['SQLALCHEMY_DATABASE_URI'] = conf.SQLALCHEMY_DATABASE_URI -db = SQLAlchemy(app) - -app.config['RECAPTCHA_USE_SSL'] = True -app.config['RECAPTCHA_PUBLIC_KEY'] = conf.RECAPTCHA_PUBLIC_KEY -app.config['RECAPTCHA_PRIVATE_KEY'] = conf.RECAPTCHA_PRIVATE_KEY - - -if conf.ON_HEROKU: - from flask_sslify import SSLify - sslify = SSLify(app) - -ALLOWED_EXTENSIONS = set(['xml', 'opml', 'json']) - -def allowed_file(filename): - """ - Check if the uploaded file is allowed. - """ - return '.' in filename and \ - filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS - -babel = Babel(app) - -app.jinja_env.filters['datetime'] = format_datetime - -# Views -from flask.ext.restful import Api -api = Api(app) - -from pyaggr3g470r import views diff --git a/pyaggr3g470r/controllers/__init__.py b/pyaggr3g470r/controllers/__init__.py new file mode 100644 index 00000000..029cbf43 --- /dev/null +++ b/pyaggr3g470r/controllers/__init__.py @@ -0,0 +1,5 @@ +from .feed import FeedController +from .article import ArticleController + + +__all__ = ['FeedController', 'ArticleController'] diff --git a/pyaggr3g470r/controllers/abstract.py b/pyaggr3g470r/controllers/abstract.py new file mode 100644 index 00000000..fe437b09 --- /dev/null +++ b/pyaggr3g470r/controllers/abstract.py @@ -0,0 +1,47 @@ +from flask import g +from pyaggr3g470r.lib.exceptions import Forbidden, NotFound + + +class AbstractController(object): + _db_cls = None + + def __init__(self, user_id): + self.user_id = user_id + + def _get(self, **filters): + if self.user_id: + filters['user_id'] = self.user_id + db_filters = [getattr(self._db_cls, key) == value + for key, value in filters.iteritems()] + return self._db_cls.query.filter(*db_filters).first() + + def get(self, **filters): + obj = self._get(**filters).first() + if not obj: + raise NotFound({'message': 'No %r (%r)' + % (self._db_cls.__class__.__name__, filters)}) + if obj.user_id != self.user_id: + raise Forbidden({'message': 'No authorized to access %r (%r)' + % (self._db_cls.__class__.__name__, filters)}) + return obj + + def create(self, **attrs): + obj = self._db_cls(**attrs) + g.db.session.commit() + return obj + + def read(self, **filters): + return self._get(**filters) + + def update(self, obj_id, **attrs): + obj = self.get(id=obj_id) + for key, values in attrs.iteritems(): + setattr(obj, key, values) + g.db.session.commit() + return obj + + def delete(self, obj_id): + obj = self.get(id=obj_id) + g.db.session.delete(obj) + g.db.session.commit() + return obj diff --git a/pyaggr3g470r/controllers/article.py b/pyaggr3g470r/controllers/article.py new file mode 100644 index 00000000..cfaf386d --- /dev/null +++ b/pyaggr3g470r/controllers/article.py @@ -0,0 +1,20 @@ +import conf +from .abstract import AbstractController +from pyaggr3g470r.models import Article + + +class ArticleController(AbstractController): + _db_cls = Article + + def read(self, obj_id): + article = super(ArticleController, self).read(obj_id) + if not article.readed: + self.update(obj_id, readed=True) + return article + + def delete(self, obj_id): + obj = super(ArticleController, self).delete(obj_id) + if not conf.ON_HEROKU: + import pyaggr3g470r.search as fastsearch + fastsearch.delete_article(self.user_id, obj.feed_id, obj_id) + return obj diff --git a/pyaggr3g470r/controllers/feed.py b/pyaggr3g470r/controllers/feed.py new file mode 100644 index 00000000..5ada1a48 --- /dev/null +++ b/pyaggr3g470r/controllers/feed.py @@ -0,0 +1,6 @@ +from .abstract import AbstractController +from pyaggr3g470r.models import Feed + + +class FeedController(AbstractController): + _db_cls = Feed diff --git a/pyaggr3g470r/decorators.py b/pyaggr3g470r/decorators.py index 3e808793..a13dacac 100644 --- a/pyaggr3g470r/decorators.py +++ b/pyaggr3g470r/decorators.py @@ -5,8 +5,11 @@ from threading import Thread from functools import wraps from flask import g, redirect, url_for, flash +from flask.ext.babel import gettext +from flask.ext.login import login_required from pyaggr3g470r.models import Feed +from pyaggr3g470r.lib.exceptions import PyAggError def async(f): @@ -37,3 +40,23 @@ def feed_access_required(func): else: return func(*args, **kwargs) return decorated + + +def handle_pyagg_error(func): + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except PyAggError, error: + flash(gettext(error.default_message), 'warning') + return redirect(url_for('home')) + return wrapper + + +def pyagg_default_decorator(func): + @login_required + @handle_pyagg_error + @wraps(func) + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper diff --git a/pyaggr3g470r/lib/exceptions.py b/pyaggr3g470r/lib/exceptions.py new file mode 100644 index 00000000..30c71a5c --- /dev/null +++ b/pyaggr3g470r/lib/exceptions.py @@ -0,0 +1,13 @@ +class PyAggError(Exception): + status_code = None + default_message = '' + + +class Forbidden(PyAggError): + status_code = 403 + default_message = 'You do not have the rights to access that resource' + + +class NotFound(PyAggError): + status_code = 404 + default_message = 'Resource was not found' diff --git a/pyaggr3g470r/models/__init__.py b/pyaggr3g470r/models/__init__.py index 906d1f8c..f01eb3a3 100644 --- a/pyaggr3g470r/models/__init__.py +++ b/pyaggr3g470r/models/__init__.py @@ -30,11 +30,12 @@ import re import json import random, hashlib from datetime import datetime +from flask import g from sqlalchemy import asc, desc from werkzeug import generate_password_hash, check_password_hash from flask.ext.login import UserMixin -from pyaggr3g470r import db +db = g.db class User(db.Model, UserMixin): diff --git a/pyaggr3g470r/notifications.py b/pyaggr3g470r/notifications.py index 8b6ff0c9..e351573c 100644 --- a/pyaggr3g470r/notifications.py +++ b/pyaggr3g470r/notifications.py @@ -19,10 +19,11 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. +import conf from pyaggr3g470r import utils -from pyaggr3g470r import conf from pyaggr3g470r import emails + def information_message(subject, plaintext): """ Send an information message to the users of the platform. @@ -68,4 +69,4 @@ def new_article_notification(user, feed, article): html = """<html>\n<head>\n<title>%s</title>\n</head>\n<body>\n%s\n</body>\n</html>""" % \ (feed.title + ": " + article.title, article.content) plaintext = utils.clear_string(html) - emails.send(to=user.email, bcc=conf.NOTIFICATION_EMAIL, subject=subject, plaintext=plaintext, html=html)
\ No newline at end of file + emails.send(to=user.email, bcc=conf.NOTIFICATION_EMAIL, subject=subject, plaintext=plaintext, html=html) diff --git a/pyaggr3g470r/utils.py b/pyaggr3g470r/utils.py index c6264106..01bcd36c 100755 --- a/pyaggr3g470r/utils.py +++ b/pyaggr3g470r/utils.py @@ -52,9 +52,10 @@ from collections import Counter from contextlib import contextmanager import conf -from pyaggr3g470r import db +from flask import g from pyaggr3g470r.models import User, Feed, Article + # regular expression to check URL url_finders = [ re.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|(((news|telnet|nttp|file|http|ftp|https)://)|(www|ftp)[-A-Za-z0-9]*\\.)[-A-Za-z0-9\\.]+)(:[0-9]*)?/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]*[^]'\\.}>\\),\\\"]"), \ @@ -136,7 +137,7 @@ def import_opml(email, opml_content): return nb nb = read(subscriptions) - db.session.commit() + g.db.session.commit() return nb def import_json(email, json_content): @@ -159,7 +160,7 @@ def import_json(email, json_content): enabled=feed["enabled"]) user.feeds.append(new_feed) nb_feeds += 1 - db.session.commit() + g.db.session.commit() # Create articles for feed in json_account["result"]: @@ -179,7 +180,7 @@ def import_json(email, json_content): user_feed.articles.append(new_article) nb_articles += 1 - db.session.commit() + g.db.session.commit() return nb_feeds, nb_articles diff --git a/pyaggr3g470r/views/__init__.py b/pyaggr3g470r/views/__init__.py index ad71048a..029dcb7d 100644 --- a/pyaggr3g470r/views/__init__.py +++ b/pyaggr3g470r/views/__init__.py @@ -1,2 +1,5 @@ from .views import * from .api import * + +from .article import article_bp, articles_bp +from .feed import feed_bp, feeds_bp diff --git a/pyaggr3g470r/views/api/article.py b/pyaggr3g470r/views/api/article.py index c509b0a8..3642cda9 100644 --- a/pyaggr3g470r/views/api/article.py +++ b/pyaggr3g470r/views/api/article.py @@ -1,15 +1,11 @@ import re import dateutil.parser -import conf -if not conf.ON_HEROKU: - import pyaggr3g470r.search as fastsearch - from flask import request, g from flask.ext.restful import Resource, reqparse -from pyaggr3g470r import api, db from pyaggr3g470r.models import Article, Feed +from pyaggr3g470r.controllers import ArticleController from pyaggr3g470r.views.api.common import authenticate, to_response, \ PyAggResource @@ -77,7 +73,7 @@ class ArticleListAPI(Resource): feed = Feed.query.filter(Feed.id == article_dict["feed_id"], Feed.user_id == g.user.id).first() feed.articles.append(article) try: - db.session.commit() + g.db.session.commit() return {"message": "ok"}, 201 except: return {"message": "Impossible to create the article."}, 500 @@ -86,7 +82,8 @@ class ArticleListAPI(Resource): class ArticleAPI(PyAggResource): "Defines a RESTful API for Article elements." method_decorators = [authenticate, to_response] - db_cls = Article + controller_cls = ArticleController + editable_attrs = ['like', 'readed'] def __init__(self): self.reqparse = reqparse.RequestParser() @@ -94,32 +91,7 @@ class ArticleAPI(PyAggResource): self.reqparse.add_argument('readed', type=bool, location= 'json') super(ArticleAPI, self).__init__() - def get(self, id): - article = self._get_or_raise(id) - if not article.readed: - article.readed = True - db.session.commit() - return {'result': [article.dump()]} - - def put(self, id): - """ Update an article. It is only possible to update the status - ('like' and 'readed') of an article.""" - args = self.reqparse.parse_args() - article = self._get_or_raise(id) - if 'like' in args: - article.like = args['like'] - if 'readed' in args: - article.readed = args['readed'] - db.session.commit() - - try: - fastsearch.delete_article(g.user.id, article.feed_id, article.id) - except: - pass - return {"message": "ok"} - -api.add_resource(ArticleListAPI, '/api/v1.0/articles', - endpoint='articles.json') -api.add_resource(ArticleAPI, '/api/v1.0/articles/<int:id>', +g.api.add_resource(ArticleListAPI, '/articles', endpoint='articles.json') +g.api.add_resource(ArticleAPI, '/articles/<int:obj_id>', endpoint='article.json') diff --git a/pyaggr3g470r/views/api/common.py b/pyaggr3g470r/views/api/common.py index 872c4ae1..a116b9c3 100644 --- a/pyaggr3g470r/views/api/common.py +++ b/pyaggr3g470r/views/api/common.py @@ -2,12 +2,8 @@ from functools import wraps from flask import request, g, session, Response, jsonify from flask.ext.restful import Resource -from pyaggr3g470r import db from pyaggr3g470r.models import User - - -class HttpError(Exception): - pass +from pyaggr3g470r.lib.exceptions import PyAggError def authenticate(func): @@ -43,8 +39,10 @@ def to_response(func): def wrapper(*args, **kwargs): try: res = func(*args, **kwargs) - except HttpError, error: - return Response(*error.args) + except PyAggError, error: + response = jsonify(**error.message) + response.status_code = error.status_code + return response if isinstance(res, tuple): response = jsonify(**res[0]) if len(res) > 1: @@ -55,25 +53,24 @@ def to_response(func): class PyAggResource(Resource): - db_cls = None + method_decorators = [authenticate, to_response] + controller_cls = None + editable_attrs = [] + + def __init__(self, *args, **kwargs): + self.controller = self.controller_cls(g.user.id) + super(PyAggResource, self).__init__(*args, **kwargs) - def _get_or_raise(self, obj_id=None): - if obj_id is None: - raise HttpError({'message': 'No id given'}, 400) - obj = self.db_cls.query.filter(self.db_cls.id == obj_id).first() - if obj is None: - raise HttpError({'message': 'Article not found'}, 404) - if obj.user_id != g.user.id: - raise HttpError({'message': "Unauthorized for %s." - % self.db_cls.__class__.__name__}, 403) - return obj + def get(self, obj_id=None): + return {'result': [self.controller.read(id=obj_id).dump()]} - def get(self, id=None): - return {'result': [self._get_or_raise(id).dump()]} + def put(self, obj_id=None): + args = self.reqparse.parse_args() + new_values = {key: args[key] for key in + set(args).intersection(self.editable_attrs)} + self.controller.update(obj_id, **new_values) + return {"message": "ok"} - def delete(self, id): - """Delete a feed.""" - feed = self._get_or_raise(id) - db.session.delete(feed) - db.session.commit() + def delete(self, obj_id=None): + self.controller.delete(obj_id) return {"message": "ok"}, 204 diff --git a/pyaggr3g470r/views/api/feed.py b/pyaggr3g470r/views/api/feed.py index e5937128..346898b5 100644 --- a/pyaggr3g470r/views/api/feed.py +++ b/pyaggr3g470r/views/api/feed.py @@ -1,7 +1,7 @@ from flask import g from flask.ext.restful import Resource, reqparse -from pyaggr3g470r import api, db +from pyaggr3g470r.controllers import FeedController from pyaggr3g470r.models import Feed from pyaggr3g470r.views.api.common import authenticate, to_response, \ @@ -62,7 +62,7 @@ class FeedListAPI(Resource): enabled=feed_dict["enabled"]) g.user.feeds.append(new_feed) try: - db.session.commit() + g.db.session.commit() return {"message": "ok"} except: return {'message': 'Impossible to create the feed.'}, 500 @@ -70,8 +70,9 @@ class FeedListAPI(Resource): class FeedAPI(PyAggResource): "Defines a RESTful API for Feed elements." - method_decorators = [authenticate, to_response] - db_cls = Feed + controller_cls = FeedController + editable_attrs = ['title', 'description', 'link', 'site_link', + 'email_notification', 'enabled'] def __init__(self): self.reqparse = reqparse.RequestParser() @@ -85,25 +86,6 @@ class FeedAPI(PyAggResource): self.reqparse.add_argument('enabled', type=bool ,location='json') super(FeedAPI, self).__init__() - def put(self, id): - "Update a feed" - args = self.reqparse.parse_args() - feed = self.get_feed_or_raise(id) - if 'title' in args: - feed.title = args['title'] - if 'description' in args: - feed.description = args['description'] - if 'link' in args: - feed.link = args['link'] - if 'site_link' in args: - feed.site_link = args['site_link'] - if 'email_notification' in args: - feed.email_notification = args['email_notification'] - if 'enabled' in args: - feed.enabled = args['enabled'] - db.session.commit() - return {"message": "ok"} - -api.add_resource(FeedListAPI, '/api/v1.0/feeds', endpoint = 'feeds.json') -api.add_resource(FeedAPI, '/api/v1.0/feeds/<int:id>', endpoint = 'feed.json') +g.api.add_resource(FeedListAPI, '/feeds', endpoint='feeds.json') +g.api.add_resource(FeedAPI, '/feeds/<int:obj_id>', endpoint='feed.json') diff --git a/pyaggr3g470r/views/article.py b/pyaggr3g470r/views/article.py new file mode 100644 index 00000000..21858a33 --- /dev/null +++ b/pyaggr3g470r/views/article.py @@ -0,0 +1,53 @@ +from flask import Blueprint, g, render_template, redirect +from sqlalchemy import desc + +from pyaggr3g470r import controllers, utils +from pyaggr3g470r.decorators import pyagg_default_decorator + +articles_bp = Blueprint('articles', __name__, url_prefix='/articles') +article_bp = Blueprint('article', __name__, url_prefix='/article') + + +@articles_bp.route('/<feed_id>', methods=['GET']) +@articles_bp.route('/<feed_id>/<int:nb_articles>', methods=['GET']) +@pyagg_default_decorator +def articles(feed_id=None, nb_articles=-1): + """List articles of a feed. The administrator of the platform is able to + access to this view for every users.""" + feed = controllers.FeedController(g.user.id).get(id=feed_id) + feed.articles = controllers.ArticleController(g.user.id)\ + .read(feed_id=feed.id)\ + .order_by(desc("Article.date")) + if len(feed.articles.all()) <= nb_articles: + nb_articles = -1 + if nb_articles == -1: + feed.articles = feed.article.limit(nb_articles) + return render_template('articles.html', feed=feed, nb_articles=nb_articles) + + +@article_bp.route('/redirect/<int:article_id>', methods=['GET']) +@pyagg_default_decorator +def redirect_to_article(article_id): + article = controllers.ArticleController(g.user.id).get(id=article_id) + return redirect(article.link) + + +@article_bp.route('/<int:article_id>', methods=['GET']) +@pyagg_default_decorator +def article(article_id=None): + """ + Presents the content of an article. + """ + article = controllers.ArticleController(g.user.id).get(id=article_id) + previous_article = article.previous_article() + if previous_article is None: + previous_article = article.source.articles[0] + next_article = article.next_article() + if next_article is None: + next_article = article.source.articles[-1] + + return render_template('article.html', + head_title=utils.clear_string(article.title), + article=article, + previous_article=previous_article, + next_article=next_article) diff --git a/pyaggr3g470r/views/feed.py b/pyaggr3g470r/views/feed.py new file mode 100644 index 00000000..fa9dc23d --- /dev/null +++ b/pyaggr3g470r/views/feed.py @@ -0,0 +1,50 @@ +from datetime import datetime +from flask import Blueprint, g, render_template + +from pyaggr3g470r import controllers, utils +from pyaggr3g470r.decorators import pyagg_default_decorator, \ + feed_access_required + +feeds_bp = Blueprint('feeds', __name__, url_prefix='/feeds') +feed_bp = Blueprint('feed', __name__, url_prefix='/feed') + +@feeds_bp.route('/', methods=['GET']) +def feeds(): + "Lists the subscribed feeds in a table." + return render_template('feeds.html', + feeds=controllers.FeedController(g.user.id).read()) + + +@feed_bp.route('/<int:feed_id>', methods=['GET']) +@pyagg_default_decorator +@feed_access_required +def feed(feed_id=None): + "Presents detailed information about a feed." + feed = controllers.FeedController(g.user.id).get(id=feed_id) + word_size = 6 + articles = controllers.ArticleController(g.user.id)\ + .read(feed_id=feed_id).all() + nb_articles = controllers.ArticleController(g.user.id).read().count() + top_words = utils.top_words(articles, n=50, size=int(word_size)) + tag_cloud = utils.tag_cloud(top_words) + + today = datetime.datetime.now() + try: + last_article = articles[0].date + first_article = articles[-1].date + delta = last_article - first_article + average = round(float(len(articles)) / abs(delta.days), 2) + except: + last_article = datetime.datetime.fromtimestamp(0) + first_article = datetime.datetime.fromtimestamp(0) + delta = last_article - first_article + average = 0 + elapsed = today - last_article + + return render_template('feed.html', + head_title=utils.clear_string(feed.title), + feed=feed, tag_cloud=tag_cloud, + first_post_date=first_article, + end_post_date=last_article, + nb_articles=nb_articles, + average=average, delta=delta, elapsed=elapsed) diff --git a/pyaggr3g470r/views/views.py b/pyaggr3g470r/views/views.py index 0a50d8d0..6e467fb0 100644 --- a/pyaggr3g470r/views/views.py +++ b/pyaggr3g470r/views/views.py @@ -28,9 +28,12 @@ __license__ = "AGPLv3" import os import json +import string +import random +import hashlib import datetime from collections import namedtuple -from flask import abort, render_template, request, flash, session, Response, \ +from flask import render_template, request, flash, session, Response, \ url_for, redirect, g, current_app, make_response, jsonify from flask.ext.login import LoginManager, login_user, logout_user, \ login_required, current_user, AnonymousUserMixin @@ -38,13 +41,12 @@ from flask.ext.principal import Principal, Identity, AnonymousIdentity, \ identity_changed, identity_loaded, Permission,\ RoleNeed, UserNeed from flask.ext.babel import gettext -from sqlalchemy import desc, func, or_ +from sqlalchemy import func, or_ from sqlalchemy.exc import IntegrityError from werkzeug import generate_password_hash import conf from pyaggr3g470r import utils, notifications, export, duplicate -from pyaggr3g470r import app, db, allowed_file, babel from pyaggr3g470r.models import User, Feed, Article, Role from pyaggr3g470r.decorators import feed_access_required from pyaggr3g470r.forms import SignupForm, SigninForm, AddFeedForm, \ @@ -53,17 +55,17 @@ if not conf.ON_HEROKU: import pyaggr3g470r.search as fastsearch -Principal(app) +Principal(g.app) # Create a permission with a single Need, in this case a RoleNeed. admin_permission = Permission(RoleNeed('admin')) login_manager = LoginManager() -login_manager.init_app(app) +login_manager.init_app(g.app) # # Management of the user's session. # -@identity_loaded.connect_via(app) +@identity_loaded.connect_via(g.app) def on_identity_loaded(sender, identity): # Set the identity user object identity.user = current_user @@ -78,13 +80,13 @@ def on_identity_loaded(sender, identity): for role in current_user.roles: identity.provides.add(RoleNeed(role.name)) -@app.before_request +@g.app.before_request def before_request(): g.user = current_user if g.user.is_authenticated(): g.user.last_seen = datetime.datetime.utcnow() - db.session.add(g.user) - db.session.commit() + g.db.session.add(g.user) + g.db.session.commit() @login_manager.user_loader def load_user(email): @@ -95,21 +97,21 @@ def load_user(email): # # Custom error pages. # -@app.errorhandler(401) +@g.app.errorhandler(401) def authentication_required(e): flash(gettext('Authentication required.'), 'info') return redirect(url_for('login')) -@app.errorhandler(403) +@g.app.errorhandler(403) def authentication_failed(e): flash(gettext('Forbidden.'), 'danger') return redirect(url_for('home')) -@app.errorhandler(404) +@g.app.errorhandler(404) def page_not_found(e): return render_template('errors/404.html'), 404 -@app.errorhandler(500) +@g.app.errorhandler(500) def internal_server_error(e): return render_template('errors/500.html'), 500 @@ -119,7 +121,7 @@ def redirect_url(default='home'): request.referrer or \ url_for(default) -@babel.localeselector +@g.babel.localeselector def get_locale(): """ Called before each request to give us a chance to choose @@ -127,7 +129,7 @@ def get_locale(): """ return request.accept_languages.best_match(conf.LANGUAGES.keys()) -@babel.timezoneselector +@g.babel.timezoneselector def get_timezone(): try: return conf.TIME_ZONE[get_locale()] @@ -137,7 +139,7 @@ def get_timezone(): # # Views. # -@app.route('/login', methods=['GET', 'POST']) +@g.app.route('/login', methods=['GET', 'POST']) def login(): """ Log in view. @@ -158,7 +160,7 @@ def login(): return redirect(url_for('home')) return render_template('login.html', form=form) -@app.route('/api/csrf', methods=['GET']) +@g.app.route('/api/csrf', methods=['GET']) def get_csrf(): try: data = json.loads(request.data) @@ -170,11 +172,11 @@ def get_csrf(): return Response(status=401) user = User.query.filter(User.email == email).first() if not user: - return Reponse(status=404) + return Response(status=404) if not user.check_password(password): - return Reponse(status=401) + return Response(status=401) if not user.activation_key == "": - return Reponse(status=403) + return Response(status=403) login_user(user) g.user = user session['email'] = email @@ -183,7 +185,7 @@ def get_csrf(): return 'ok', 200 -@app.route('/logout') +@g.app.route('/logout') @login_required def logout(): """ @@ -204,7 +206,7 @@ def logout(): flash(gettext("Logged out successfully."), 'success') return redirect(url_for('login')) -@app.route('/signup', methods=['GET', 'POST']) +@g.app.route('/signup', methods=['GET', 'POST']) def signup(): """ Signup page. @@ -223,9 +225,9 @@ def signup(): email=form.email.data, pwdhash=generate_password_hash(form.password.data)) user.roles = [role_user] - db.session.add(user) + g.db.session.add(user) try: - db.session.commit() + g.db.session.commit() except IntegrityError: flash(gettext('Email already used.'), 'warning') return render_template('signup.html', form=form) @@ -242,7 +244,7 @@ def signup(): return render_template('signup.html', form=form) -@app.route('/') +@g.app.route('/') @login_required def home(): """ @@ -263,7 +265,7 @@ def home(): if limit != 'all': limit = int(limit) articles = articles.limit(limit) - unread = db.session.query(Article.feed_id, func.count(Article.id))\ + unread = g.db.session.query(Article.feed_id, func.count(Article.id))\ .filter(Article.readed == False, Article.user_id == g.user.id)\ .group_by(Article.feed_id).all() def gen_url(filter_=filter_, limit=limit, feed=feed_id): @@ -273,20 +275,8 @@ def home(): unread=dict(unread), articles=articles.all()) -@app.route('/article/redirect/<int:article_id>', methods=['GET']) -@login_required -def redirect_to_article(article_id): - article = Article.query.filter(Article.id == article_id, - Article.user_id == g.user.id).first() - if article is None: - abort(404) - article.readed = True - db.session.commit() - return redirect(article.link) - - -@app.route('/fetch', methods=['GET']) -@app.route('/fetch/<int:feed_id>', methods=['GET']) +@g.app.route('/fetch', methods=['GET']) +@g.app.route('/fetch/<int:feed_id>', methods=['GET']) @login_required def fetch(feed_id=None): """ @@ -297,82 +287,17 @@ def fetch(feed_id=None): flash(gettext("Downloading articles..."), 'info') return redirect(redirect_url()) -@app.route('/about', methods=['GET']) +@g.app.route('/about', methods=['GET']) def about(): """ 'About' page. """ return render_template('about.html') -@app.route('/feeds', methods=['GET']) -@login_required -def feeds(): - """ - Lists the subscribed feeds in a table. - """ - user = User.query.filter(User.email == g.user.email).first() - return render_template('feeds.html', feeds=user.feeds) - -@app.route('/feed/<int:feed_id>', methods=['GET']) -@login_required -@feed_access_required -def feed(feed_id=None): - """ - Presents detailed information about a feed. - """ - feed = Feed.query.filter(Feed.id == feed_id).first() - word_size = 6 - articles = feed.articles.all() - nb_articles = len(Article.query.filter(Article.user_id == g.user.id).all()) - top_words = utils.top_words(articles, n=50, size=int(word_size)) - tag_cloud = utils.tag_cloud(top_words) - - today = datetime.datetime.now() - try: - last_article = articles[0].date - first_article = articles[-1].date - delta = last_article - first_article - average = round(float(len(articles)) / abs(delta.days), 2) - except: - last_article = datetime.datetime.fromtimestamp(0) - first_article = datetime.datetime.fromtimestamp(0) - delta = last_article - first_article - average = 0 - elapsed = today - last_article - - return render_template('feed.html', head_title=utils.clear_string(feed.title), feed=feed, tag_cloud=tag_cloud, \ - first_post_date=first_article, end_post_date=last_article , nb_articles=nb_articles, \ - average=average, delta=delta, elapsed=elapsed) - -@app.route('/article/<int:article_id>', methods=['GET']) -@login_required -def article(article_id=None): - """ - Presents the content of an article. - """ - article = Article.query.filter(Article.user_id == g.user.id, Article.id == article_id).first() - if article is not None: - if not article.readed: - article.readed = True - db.session.commit() - - previous_article = article.previous_article() - if previous_article is None: - previous_article = article.source.articles[0] - next_article = article.next_article() - if next_article is None: - next_article = article.source.articles[-1] - - return render_template('article.html', head_title=utils.clear_string(article.title), - article=article, - previous_article=previous_article, next_article=next_article) - flash(gettext("This article do not exist."), 'warning') - return redirect(url_for('home')) - -@app.route('/mark_as/<string:new_value>', methods=['GET']) -@app.route('/mark_as/<string:new_value>/feed/<int:feed_id>', methods=['GET']) -@app.route('/mark_as/<string:new_value>/article/<int:article_id>', methods=['GET']) +@g.app.route('/mark_as/<string:new_value>', methods=['GET']) +@g.app.route('/mark_as/<string:new_value>/feed/<int:feed_id>', methods=['GET']) +@g.app.route('/mark_as/<string:new_value>/article/<int:article_id>', methods=['GET']) @login_required @feed_access_required def mark_as(new_value='read', feed_id=None, article_id=None): @@ -391,12 +316,12 @@ def mark_as(new_value='read', feed_id=None, article_id=None): message = 'All article marked as %s.' articles.filter(Article.readed == (not readed)).update({"readed": readed}) flash(gettext(message % new_value), 'info') - db.session.commit() + g.db.session.commit() if readed: return redirect(redirect_url()) return redirect(url_for('home')) -@app.route('/like/<int:article_id>', methods=['GET']) +@g.app.route('/like/<int:article_id>', methods=['GET']) @login_required def like(article_id=None): """ @@ -406,10 +331,10 @@ def like(article_id=None): update({ "like": not Article.query.filter(Article.id == article_id).first().like }) - db.session.commit() + g.db.session.commit() return redirect(redirect_url()) -@app.route('/delete/<int:article_id>', methods=['GET']) +@g.app.route('/delete/<int:article_id>', methods=['GET']) @login_required def delete(article_id=None): """ @@ -417,8 +342,8 @@ def delete(article_id=None): """ article = Article.query.filter(Article.id == article_id).first() if article is not None and article.source.subscriber.id == g.user.id: - db.session.delete(article) - db.session.commit() + g.db.session.delete(article) + g.db.session.commit() try: fastsearch.delete_article(g.user.id, article.feed_id, article.id) except: @@ -429,26 +354,8 @@ def delete(article_id=None): flash(gettext('This article do not exist.'), 'danger') return redirect(url_for('home')) -@app.route('/articles/<feed_id>', methods=['GET']) -@app.route('/articles/<feed_id>/<int:nb_articles>', methods=['GET']) -@login_required -@feed_access_required -def articles(feed_id=None, nb_articles=-1): - """ - List articles of a feed. - The administrator of the platform is able to access to this view for every users. - """ - feed = Feed.query.filter(Feed.id == feed_id).first() - new_feed = feed - if len(feed.articles.all()) <= nb_articles: - nb_articles = -1 - if nb_articles == -1: - nb_articles = int(1e9) - new_feed.articles = Article.query.filter(Article.user_id == g.user.id, \ - Article.feed_id == feed.id).order_by(desc("Article.date")).limit(nb_articles) - return render_template('articles.html', feed=new_feed, nb_articles=nb_articles) - -@app.route('/favorites', methods=['GET']) + +@g.app.route('/favorites', methods=['GET']) @login_required def favorites(): """ @@ -463,8 +370,8 @@ def favorites(): nb_favorites += len(articles) return render_template('favorites.html', feeds=result, nb_favorites=nb_favorites) -@app.route('/unread/<int:feed_id>', methods=['GET']) -@app.route('/unread', methods=['GET']) +@g.app.route('/unread/<int:feed_id>', methods=['GET']) +@g.app.route('/unread', methods=['GET']) @login_required def unread(feed_id=None): """ @@ -482,7 +389,7 @@ def unread(feed_id=None): nb_unread += len(articles) return render_template('unread.html', feeds=result, nb_unread=nb_unread) -@app.route('/inactives', methods=['GET']) +@g.app.route('/inactives', methods=['GET']) @login_required def inactives(): """ @@ -502,7 +409,7 @@ def inactives(): inactives.append((feed, elapsed)) return render_template('inactives.html', inactives=inactives, nb_days=nb_days) -@app.route('/duplicates/<int:feed_id>', methods=['GET']) +@g.app.route('/duplicates/<int:feed_id>', methods=['GET']) @login_required def duplicates(feed_id=None): """ @@ -513,7 +420,7 @@ def duplicates(feed_id=None): duplicates = duplicate.compare_documents(feed) return render_template('duplicates.html', duplicates=duplicates, feed=feed) -@app.route('/index_database', methods=['GET']) +@g.app.route('/index_database', methods=['GET']) @login_required def index_database(): """ @@ -530,7 +437,7 @@ def index_database(): flash(gettext('Option not available on Heroku.'), 'success') return redirect(url_for('home')) -@app.route('/export', methods=['GET']) +@g.app.route('/export', methods=['GET']) @login_required def export_articles(): """ @@ -562,7 +469,7 @@ def export_articles(): return redirect(redirect_url()) return response -@app.route('/export_opml', methods=['GET']) +@g.app.route('/export_opml', methods=['GET']) @login_required def export_opml(): """ @@ -574,7 +481,7 @@ def export_opml(): response.headers['Content-Disposition'] = 'attachment; filename=feeds.opml' return response -@app.route('/search', methods=['GET']) +@g.app.route('/search', methods=['GET']) @login_required def search(): """ @@ -607,7 +514,7 @@ def search(): break return render_template('search.html', feeds=result, nb_articles=nb_articles, query=query) -@app.route('/management', methods=['GET', 'POST']) +@g.app.route('/management', methods=['GET', 'POST']) @login_required def management(): """ @@ -617,7 +524,7 @@ def management(): if None != request.files.get('opmlfile', None): # Import an OPML file data = request.files.get('opmlfile', None) - if not allowed_file(data.filename): + if not g.allowed_file(data.filename): flash(gettext('File not allowed.'), 'danger') else: try: @@ -630,7 +537,7 @@ def management(): elif None != request.files.get('jsonfile', None): # Import an account data = request.files.get('jsonfile', None) - if not allowed_file(data.filename): + if not g.allowed_file(data.filename): flash(gettext('File not allowed.'), 'danger') else: try: @@ -650,15 +557,15 @@ def management(): nb_feeds=nb_feeds, nb_articles=nb_articles, nb_unread_articles=nb_unread_articles, not_on_heroku = not conf.ON_HEROKU) -@app.route('/history', methods=['GET']) +@g.app.route('/history', methods=['GET']) @login_required def history(): - user = User.query.filter(User.id == g.user.id).first() + #user = User.query.filter(User.id == g.user.id).first() return render_template('history.html') -@app.route('/bookmarklet', methods=['GET']) -@app.route('/create_feed', methods=['GET', 'POST']) -@app.route('/edit_feed/<int:feed_id>', methods=['GET', 'POST']) +@g.app.route('/bookmarklet', methods=['GET']) +@g.app.route('/create_feed', methods=['GET', 'POST']) +@g.app.route('/edit_feed/<int:feed_id>', methods=['GET', 'POST']) @login_required @feed_access_required def edit_feed(feed_id=None): @@ -674,19 +581,19 @@ def edit_feed(feed_id=None): if feed_id is not None: # Edit an existing feed form.populate_obj(feed) - db.session.commit() + g.db.session.commit() flash(gettext('Feed successfully updated.'), 'success') return redirect('/edit_feed/' + str(feed_id)) else: # Create a new feed - existing_feed = [feed for feed in g.user.feeds if feed.link == form.link.data] + existing_feed = [f for f in g.user.feeds if feed.link == form.link.data] if len(existing_feed) == 0: new_feed = Feed(title=form.title.data, description="", link=form.link.data, \ site_link=form.site_link.data, email_notification=form.email_notification.data, \ enabled=form.enabled.data) g.user.feeds.append(new_feed) #user.feeds = sorted(user.feeds, key=lambda t: t.title.lower()) - db.session.commit() + g.db.session.commit() flash(gettext('Feed successfully created.'), 'success') utils.fetch(g.user.id, Feed.query.filter(Feed.link == form.link.data).first().id) @@ -705,10 +612,10 @@ def edit_feed(feed_id=None): # Enable the user to add a feed with a bookmarklet if None is not request.args.get('url', None): - existing_feed = [feed for feed in g.user.feeds if feed.link == request.args.get('url', None)] + existing_feed = [f for f in g.user.feeds if feed.link == request.args.get('url', None)] if len(existing_feed) == 0: g.user.feeds.append(Feed(link=request.args.get('url', None))) - db.session.commit() + g.db.session.commit() return jsonify({"message":"ok"}) return jsonify({"message":"Feed already in the database."}) @@ -716,7 +623,7 @@ def edit_feed(feed_id=None): return render_template('edit_feed.html', action=gettext("Add a feed"), form=form, \ not_on_heroku = not conf.ON_HEROKU) -@app.route('/delete_feed/<feed_id>', methods=['GET']) +@g.app.route('/delete_feed/<feed_id>', methods=['GET']) @login_required @feed_access_required def delete_feed(feed_id=None): @@ -724,12 +631,12 @@ def delete_feed(feed_id=None): Delete a feed with all associated articles. """ feed = Feed.query.filter(Feed.id == feed_id).first() - db.session.delete(feed) - db.session.commit() + g.db.session.delete(feed) + g.db.session.commit() flash(gettext('Feed') + ' ' + feed.title + ' ' + gettext('successfully deleted.'), 'success') return redirect(redirect_url()) -@app.route('/profile', methods=['GET', 'POST']) +@g.app.route('/profile', methods=['GET', 'POST']) @login_required def profile(): """ @@ -743,7 +650,7 @@ def profile(): form.populate_obj(user) if form.password.data != "": user.set_password(form.password.data) - db.session.commit() + g.db.session.commit() flash(gettext('User') + ' ' + user.nickname + ' ' + gettext('successfully updated.'), 'success') return redirect(url_for('profile')) else: @@ -753,7 +660,7 @@ def profile(): form = ProfileForm(obj=user) return render_template('profile.html', user=user, form=form) -@app.route('/delete_account', methods=['GET']) +@g.app.route('/delete_account', methods=['GET']) @login_required def delete_account(): """ @@ -761,14 +668,14 @@ def delete_account(): """ user = User.query.filter(User.email == g.user.email).first() if user is not None: - db.session.delete(user) - db.session.commit() + g.db.session.delete(user) + g.db.session.commit() flash(gettext('Your account has been deleted.'), 'success') else: flash(gettext('This user does not exist.'), 'danger') return redirect(url_for('login')) -@app.route('/expire_articles', methods=['GET']) +@g.app.route('/expire_articles', methods=['GET']) @login_required def expire_articles(): """ @@ -778,12 +685,12 @@ def expire_articles(): weeks_ago = current_time - datetime.timedelta(weeks=int(request.args.get('weeks', 10))) articles_to_delete = Article.query.filter(User.email == g.user.email, or_(Article.date < weeks_ago, Article.retrieved_date < weeks_ago)) for article in articles_to_delete: - db.session.delete(article) + g.db.session.delete(article) flash(gettext('Articles deleted.'), 'info') - db.session.commit() + g.db.session.commit() return redirect(redirect_url()) -@app.route('/confirm_account/<string:activation_key>', methods=['GET']) +@g.app.route('/confirm_account/<string:activation_key>', methods=['GET']) def confirm_account(activation_key=None): """ Confirm the account of a user. @@ -792,20 +699,18 @@ def confirm_account(activation_key=None): user = User.query.filter(User.activation_key == activation_key).first() if user is not None: user.activation_key = "" - db.session.commit() + g.db.session.commit() flash(gettext('Your account has been confirmed.'), 'success') else: flash(gettext('Impossible to confirm this account.'), 'danger') return redirect(url_for('login')) -@app.route('/recover', methods=['GET', 'POST']) +@g.app.route('/recover', methods=['GET', 'POST']) def recover(): """ Enables the user to recover its account when he has forgotten its password. """ - import string - import random form = RecoverPasswordForm() if request.method == 'POST': @@ -814,7 +719,7 @@ def recover(): characters = string.ascii_letters + string.digits password = "".join(random.choice(characters) for x in range(random.randint(8, 16))) user.set_password(password) - db.session.commit() + g.db.session.commit() # Send the confirmation email try: @@ -832,7 +737,7 @@ def recover(): # # Views dedicated to administration tasks. # -@app.route('/admin/dashboard', methods=['GET', 'POST']) +@g.app.route('/admin/dashboard', methods=['GET', 'POST']) @login_required @admin_permission.require(http_exception=403) def dashboard(): @@ -851,8 +756,8 @@ def dashboard(): users = User.query.all() return render_template('admin/dashboard.html', users=users, current_user=g.user, form=form) -@app.route('/admin/create_user', methods=['GET', 'POST']) -@app.route('/admin/edit_user/<int:user_id>', methods=['GET', 'POST']) +@g.app.route('/admin/create_user', methods=['GET', 'POST']) +@g.app.route('/admin/edit_user/<int:user_id>', methods=['GET', 'POST']) @login_required @admin_permission.require(http_exception=403) def create_user(user_id=None): @@ -870,7 +775,7 @@ def create_user(user_id=None): form.populate_obj(user) if form.password.data != "": user.set_password(form.password.data) - db.session.commit() + g.db.session.commit() flash(gettext('User') + ' ' + user.nickname + ' ' + gettext('successfully updated.'), 'success') else: # Create a new user @@ -879,8 +784,8 @@ def create_user(user_id=None): pwdhash=generate_password_hash(form.password.data)) user.roles.extend([role_user]) user.activation_key = "" - db.session.add(user) - db.session.commit() + g.db.session.add(user) + g.db.session.commit() flash(gettext('User') + ' ' + user.nickname + ' ' + gettext('successfully created.'), 'success') return redirect("/admin/edit_user/"+str(user.id)) else: @@ -896,7 +801,7 @@ def create_user(user_id=None): message = gettext('Add a new user') return render_template('/admin/create_user.html', form=form, message=message) -@app.route('/admin/user/<int:user_id>', methods=['GET']) +@g.app.route('/admin/user/<int:user_id>', methods=['GET']) @login_required @admin_permission.require(http_exception=403) def user(user_id=None): @@ -910,7 +815,7 @@ def user(user_id=None): flash(gettext('This user does not exist.'), 'danger') return redirect(redirect_url()) -@app.route('/admin/delete_user/<int:user_id>', methods=['GET']) +@g.app.route('/admin/delete_user/<int:user_id>', methods=['GET']) @login_required @admin_permission.require(http_exception=403) def delete_user(user_id=None): @@ -919,15 +824,15 @@ def delete_user(user_id=None): """ user = User.query.filter(User.id == user_id).first() if user is not None: - db.session.delete(user) - db.session.commit() + g.db.session.delete(user) + g.db.session.commit() flash(gettext('User') + ' ' + user.nickname + ' ' + gettext('successfully deleted.'), 'success') else: flash(gettext('This user does not exist.'), 'danger') return redirect(redirect_url()) -@app.route('/admin/enable_user/<int:user_id>', methods=['GET']) -@app.route('/admin/disable_user/<int:user_id>', methods=['GET']) +@g.app.route('/admin/enable_user/<int:user_id>', methods=['GET']) +@g.app.route('/admin/disable_user/<int:user_id>', methods=['GET']) @login_required @admin_permission.require() def disable_user(user_id=None): @@ -947,10 +852,9 @@ def disable_user(user_id=None): flash(gettext('Problem while sending activation email') + ': ' + str(e), 'danger') else: - import random, hashlib user.activation_key = hashlib.sha512(str(random.getrandbits(256)).encode("utf-8")).hexdigest()[:86] flash(gettext('Account of the user') + ' ' + user.nickname + ' ' + gettext('successfully disabled.'), 'success') - db.session.commit() + g.db.session.commit() else: flash(gettext('This user does not exist.'), 'danger') return redirect(redirect_url()) diff --git a/runserver.py b/runserver.py index 8ae7282a..8d163cd6 100755 --- a/runserver.py +++ b/runserver.py @@ -19,8 +19,44 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. -from bootstrap import conf -from pyaggr3g470r import app as application +from bootstrap import conf, application, db +from flask.ext.babel import Babel +from flask.ext.babel import format_datetime + +if conf.ON_HEROKU: + from flask_sslify import SSLify + SSLify(application) + +ALLOWED_EXTENSIONS = set(['xml', 'opml', 'json']) + +def allowed_file(filename): + """ + Check if the uploaded file is allowed. + """ + return '.' in filename and \ + filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS + +babel = Babel(application) + +application.jinja_env.filters['datetime'] = format_datetime + +# Views +from flask.ext.restful import Api +from flask import g + +with application.app_context(): + g.api = Api(application, prefix='/api/v1.0') + g.babel = babel + g.allowed_file = allowed_file + g.db = db + g.app = application + + from pyaggr3g470r import views + application.register_blueprint(views.articles_bp) + application.register_blueprint(views.article_bp) + application.register_blueprint(views.feeds_bp) + application.register_blueprint(views.feed_bp) + if __name__ == '__main__': application.run(host=conf.WEBSERVER_HOST, |