The flask version of wrfeed is basically working now.
authorphilipp <philipp@7aebc617-e5e2-0310-91dc-80fb5f6d2477>
Sun, 23 Jul 2017 19:23:44 +0000 (19:23 +0000)
committerphilipp <philipp@7aebc617-e5e2-0310-91dc-80fb5f6d2477>
Sun, 23 Jul 2017 19:23:44 +0000 (19:23 +0000)
git-svn-id: http://www.winterrodeln.org/svn/wrfeed/trunk@2643 7aebc617-e5e2-0310-91dc-80fb5f6d2477

wrfeed/controllers/berichte.py
wrfeed/wrfeed.py

index bbae6ab657a7cb3a1ffcb4c713527b7b215c5a97..10e83af7f7ac1f1649e11463388d86ebad2c3782 100644 (file)
@@ -1,5 +1,3 @@
-#!/usr/bin/python2.7
-# -*- coding: UTF-8 -*-
 """Creates an Atom-Feed for single or multiple winterrodeln sled reports.
 
 Format:
@@ -12,34 +10,25 @@ See:
     http://effbot.org/zone/element.htm
     http://www.winterrodeln.org/trac/wiki/UrlSchema
 """
-import sys
 import datetime
 from xml.etree.ElementTree import Element, SubElement, tostring
-
-from sqlalchemy.engine import create_engine
 from osgeo import ogr
+from flask import url_for
 
-import logging
 
-import webob.exc
-from pylons import request, response, session, config, tmpl_context as c, url
-from pylons.controllers.util import abort, redirect
+class CreateFeedError(RuntimeError):
+    pass
 
-from wrfeed.lib.base import BaseController, render
 
-log = logging.getLogger(__name__)
+class RegionNotFoundError(CreateFeedError):
+    pass
 
 
-def create_feed(page_title=None, page_ids=None, region_name=None):
+def create_feed(conn, limit, page_title=None, page_ids=None, region_name=None):
     """If a page_title is given, only the reports for the given sledrun are shown.
     If a list of page_ids is given, only the reports for the selected pages are shown.
     If a region name (lower case) is given, the reports just for this region are shown.
     Otherwise, all reports are shown."""
-
-    engine = create_engine(config['sqlalchemy.url'])
-    limit = int(config['feedentrylimit'])
-    conn = engine.connect()
-
     select = 'select wrreport.page_id, wrreport.page_title, wrreport.id, date_report, date_entry, `condition`, description, author_name, author_userid, author_username, position_longitude, position_latitude from wrreport left outer join wrsledruncache on wrreport.page_id=wrsledruncache.page_id'
     where = 'where date_invalid > now() and delete_date is null'
     order = 'order by id desc'
@@ -53,8 +42,7 @@ def create_feed(page_title=None, page_ids=None, region_name=None):
         params += [page_title]
     elif not page_ids is None:
         # a list of page_ids is given
-        if len(page_ids) == 0:
-            raise webob.exc.HTTPBadRequest()
+        assert len(page_ids) > 0
         where += ' and ('
         where += " or ".join(['wrreport.page_id=%s' for page_id in page_ids])
         where += ')'
@@ -66,7 +54,7 @@ def create_feed(page_title=None, page_ids=None, region_name=None):
         subresult = conn.execute(subselect, region_name)
         if subresult.rowcount == 0:
             # no region with such a name
-            raise webob.exc.HTTPNotFound()
+            raise RegionNotFoundError(region_name)
         assert subresult.rowcount == 1
         row = subresult.fetchone()
         # (2) now we have the border
@@ -87,13 +75,13 @@ def create_feed(page_title=None, page_ids=None, region_name=None):
     feed_title.text = "Winterrodeln Rodelbahnberichte"
     feed_id = SubElement(feed, "id")
     if not page_title is None:
-        feed_id.text = url(qualified=True, controller='berichte', action='bahn', id=page_title)
+        feed_id.text = url_for('bahn', bahn=page_title, _external=True)
     elif not page_ids is None:
-        feed_id.text = url(qualified=True, controller='berichte', action='bahnen', id="+".join(map(str, page_ids)))
+        feed_id.text = url_for('bahnen', bahnen="+".join(map(str, page_ids)), _external=True)
     elif not region_name is None:
-        feed_id.text = url(qualified=True, controller='berichte', action='region', id=region_name)
+        feed_id.text = url_for('region', region=region_name, _external=True)
     else:
-        feed_id.text = url(qualified=True, controller='berichte', action='alle')
+        feed_id.text = url_for('alle', _external=True)
     feed_updated = SubElement(feed, "updated")
     feed.append(Element("link", rel="self", href=feed_id.text))
 
@@ -155,49 +143,4 @@ def create_feed(page_title=None, page_ids=None, region_name=None):
     if last_updated is None: last_updated = datetime.datetime.now()
     feed_updated.text = last_updated.isoformat() + "+01:00"
 
-    feed_xml =  '<?xml version="1.0" encoding="utf-8"?>\n' + tostring(feed)
-    conn.close()
-    return feed_xml
-
-
-
-class BerichteController(BaseController):
-
-    def alle(self):
-        """Handles URLs like
-        http://127.0.0.1:5000/berichte/alle
-        http://www.winterrodeln.org/feed/berichte/alle
-        """
-        response.content_type = 'application/atom+xml'
-        return create_feed()
-
-
-    def bahn(self, id):
-        """Handles URLs like
-        http://127.0.0.1:5000/berichte/bahn/kemater_alm
-        http://www.winterrodeln.org/feed/berichte/bahn/kemater_alm
-        """
-        response.content_type = 'application/atom+xml'
-        return create_feed(page_title=id)
-
-
-    def bahnen(self, id):
-        """Handles URLs like
-        http://127.0.0.1:5000/berichte/bahnen/5+280+251
-        http://www.winterrodeln.org/feed/berichte/bahnen/5+280+251
-        """
-        page_ids = id.split('+')
-        try:
-            page_ids = [int(page_id) for page_id in page_ids]
-        except ValueError:
-            abort(400) # bad request
-        response.content_type = 'application/atom+xml'
-        return create_feed(page_ids=page_ids)
-
-    def region(self, id):
-        """Handles URLs like
-        http://www.winterrodeln.org/feed/berichte/region/osttirol
-        """
-        response.content_type = 'application/atom+xml'
-        return create_feed(region_name=id)
-
+    return b'<?xml version="1.0" encoding="utf-8"?>\n' + tostring(feed)
index a1a3a801bc33209e6904745db5d481ad5c5f5528..cdf0ba751fe593f129a6bdaa0f36962f1c7acb75 100644 (file)
@@ -1,9 +1,75 @@
 # http://flask.pocoo.org/
-# FLASK_APP=wrfeed.py python3 -m flask run
-from flask import Flask, send_from_directory
+# FLASK_APP=wrfeed.py FLASK_DEBUG=1 WRFEED_SETTINGS=development.cfg python3 -m flask run -p 5002
+# FLASK_APP=wrfeed.py WRFEED_SETTINGS=production.cfg python3 -m flask run
+from sqlalchemy.engine import create_engine
+from flask import Flask, send_from_directory, abort, g, jsonify
+from controllers.berichte import create_feed
+
+
 app = Flask(__name__)
+app.config.from_envvar('WRFEED_SETTINGS')
+
+
+def get_db():
+    """Opens a new database connection if there is none yet for the
+    current application context.
+    """
+    if not hasattr(g, 'db'):
+        g.db_engine = create_engine(app.config['DATABASE_URI'])
+        g.db = g.db_engine.connect()
+    return g.db
+
+
+@app.teardown_appcontext
+def close_db(error):
+    """Closes the database again at the end of the request."""
+    if hasattr(g, 'db'):
+        g.db.close()
 
 
 @app.route("/")
 def hello():
     return send_from_directory('public', 'index.html')  # actually, this is no template
+
+
+@app.route("/berichte/alle")
+def alle():
+    """Handles URLs like
+    http://127.0.0.1:5000/berichte/alle
+    http://www.winterrodeln.org/feed/berichte/alle
+    """
+    return app.response_class(create_feed(get_db(), app.config['FEEDENTRYLIMIT']), mimetype='application/atom+xml')
+
+
+@app.route("/berichte/bahn/<bahn>")
+def bahn(bahn):
+    """Handles URLs like
+    http://127.0.0.1:5000/berichte/bahn/kemater_alm
+    http://www.winterrodeln.org/feed/berichte/bahn/kemater_alm
+    """
+    return app.response_class(create_feed(get_db(), app.config['FEEDENTRYLIMIT'], page_title=bahn),
+                              mimetype='application/atom+xml')
+
+
+@app.route("/berichte/bahnen/<bahnen>")
+def bahnen(bahnen):
+    """Handles URLs like
+    http://127.0.0.1:5000/berichte/bahnen/5+280+251
+    http://www.winterrodeln.org/feed/berichte/bahnen/5+280+251
+    """
+    page_ids = bahnen.split('+')
+    try:
+        page_ids = [int(page_id) for page_id in page_ids]
+    except ValueError:
+        abort(400) # bad request
+    return app.response_class(create_feed(get_db(), app.config['FEEDENTRYLIMIT'], page_ids=page_ids),
+                              mimetype='application/atom+xml')
+
+
+@app.route("/berichte/region/<region>")
+def region(region):
+    """Handles URLs like
+    http://www.winterrodeln.org/feed/berichte/region/osttirol
+    """
+    return app.response_class(create_feed(get_db(), app.config['FEEDENTRYLIMIT'], region_name=region),
+                              mimetype='application/atom+xml')