cdf0ba751fe593f129a6bdaa0f36962f1c7acb75
[philipp/winterrodeln/wrfeed.git] / wrfeed / wrfeed.py
1 # http://flask.pocoo.org/
2 # FLASK_APP=wrfeed.py FLASK_DEBUG=1 WRFEED_SETTINGS=development.cfg python3 -m flask run -p 5002
3 # FLASK_APP=wrfeed.py WRFEED_SETTINGS=production.cfg python3 -m flask run
4 from sqlalchemy.engine import create_engine
5 from flask import Flask, send_from_directory, abort, g, jsonify
6 from controllers.berichte import create_feed
7
8
9 app = Flask(__name__)
10 app.config.from_envvar('WRFEED_SETTINGS')
11
12
13 def get_db():
14     """Opens a new database connection if there is none yet for the
15     current application context.
16     """
17     if not hasattr(g, 'db'):
18         g.db_engine = create_engine(app.config['DATABASE_URI'])
19         g.db = g.db_engine.connect()
20     return g.db
21
22
23 @app.teardown_appcontext
24 def close_db(error):
25     """Closes the database again at the end of the request."""
26     if hasattr(g, 'db'):
27         g.db.close()
28
29
30 @app.route("/")
31 def hello():
32     return send_from_directory('public', 'index.html')  # actually, this is no template
33
34
35 @app.route("/berichte/alle")
36 def alle():
37     """Handles URLs like
38     http://127.0.0.1:5000/berichte/alle
39     http://www.winterrodeln.org/feed/berichte/alle
40     """
41     return app.response_class(create_feed(get_db(), app.config['FEEDENTRYLIMIT']), mimetype='application/atom+xml')
42
43
44 @app.route("/berichte/bahn/<bahn>")
45 def bahn(bahn):
46     """Handles URLs like
47     http://127.0.0.1:5000/berichte/bahn/kemater_alm
48     http://www.winterrodeln.org/feed/berichte/bahn/kemater_alm
49     """
50     return app.response_class(create_feed(get_db(), app.config['FEEDENTRYLIMIT'], page_title=bahn),
51                               mimetype='application/atom+xml')
52
53
54 @app.route("/berichte/bahnen/<bahnen>")
55 def bahnen(bahnen):
56     """Handles URLs like
57     http://127.0.0.1:5000/berichte/bahnen/5+280+251
58     http://www.winterrodeln.org/feed/berichte/bahnen/5+280+251
59     """
60     page_ids = bahnen.split('+')
61     try:
62         page_ids = [int(page_id) for page_id in page_ids]
63     except ValueError:
64         abort(400) # bad request
65     return app.response_class(create_feed(get_db(), app.config['FEEDENTRYLIMIT'], page_ids=page_ids),
66                               mimetype='application/atom+xml')
67
68
69 @app.route("/berichte/region/<region>")
70 def region(region):
71     """Handles URLs like
72     http://www.winterrodeln.org/feed/berichte/region/osttirol
73     """
74     return app.response_class(create_feed(get_db(), app.config['FEEDENTRYLIMIT'], region_name=region),
75                               mimetype='application/atom+xml')