import os
from flask import Flask, render_template, request, abort, redirect, url_for, make_response
import requests
import iso8601
import updater

# Config
DEBUG = True
OPEN311_SERVER = 'localhost:5000'
OPEN311_API_KEY = ''
PASSWORD_PROTECTED = False

app = Flask(__name__)

@app.before_request
def password_protect():
    if app.config['PASSWORD_PROTECTED']:
        auth = request.authorization
        if not auth or auth.password != app.config['PASSWORD']:
            # Tell the browser to do basic auth
            return make_response(
                'Could not verify your access level for that URL.\n'
                'You have to login with proper credentials', 401,
                {'WWW-Authenticate': 'Basic realm="Login Required"'})


@app.route("/")
def index():
    return "Chicago Nightly 311";


@app.route("/requests")
def redirect_request():
    if 'request_id' in request.args:
        return redirect(url_for('show_request', request_id=request.args['request_id']))
    else:
        abort(404)


@app.route("/requests/<request_id>")
def show_request(request_id):
    # TODO: Should probably use Three or something nice for this...
    url = '%s/requests/%s.json' % (app.config['OPEN311_SERVER'], request_id)
    params = {}
    if app.config['OPEN311_API_KEY']:
        params['api_key'] = app.config['OPEN311_API_KEY']
    r = requests.get(url, params=params)
    sr = r.json
    
    if sr:
        sr[0]['requested_datetime'] = iso8601.parse_date(sr[0]['requested_datetime'])
        for activity in sr[0]['activities']:
            activity['datetime'] = iso8601.parse_date(activity['datetime'])
        
        sr[0]['activities'].reverse()
        
        body = render_template('service_request.html', sr=sr[0])
        return (body, 200, None)
    
    else:
        return ("No such service request", 404, None)


@app.route("/subscribe/<request_id>", methods=["POST"])
def subscribe(request_id):
    email = request.form.get('update_email')
    # TODO: validate email
    if email:
        contact = 'email:%s' % email
        updater.subscribe(request_id, contact)
    return redirect(url_for('show_request', request_id=request_id))



if __name__ == "__main__":
    app.config.from_object(__name__)
    if 'DEBUG' in os.environ:
        app.debug = os.environ['DEBUG'] == 'True' and True or False
    if 'OPEN311_SERVER' in os.environ:
        app.config['OPEN311_SERVER'] = os.environ['OPEN311_SERVER']
    if 'OPEN311_API_KEY' in os.environ:
        app.config['OPEN311_API_KEY'] = os.environ['OPEN311_API_KEY']
    
    app.config['PASSWORD_PROTECTED'] = 'PASSWORD_PROTECTED' in os.environ and (os.environ['PASSWORD_PROTECTED'] == 'True') or False
    app.config['PASSWORD'] = 'PASSWORD' in os.environ and os.environ['PASSWORD'] or ''
    
    port = int(os.environ.get('PORT', 5100))
    app.run(host='0.0.0.0', port=port)
@@ -2234,42 +2234,8 @@
 __)%0A
-    if 'DEBUG' in os.environ:%0A    
     
@@ -2260,53 +2260,63 @@
 iron
-%5B
+.get(
 'DEBUG'
-%5D == 'True' and True or False%0A    if 
+, str(app.debug)) == 'True'%0A    app.config%5B
 'OPE
@@ -2327,19 +2327,19 @@
 _SERVER'
- in
+%5D =
  os.envi
@@ -2345,61 +2345,31 @@
 iron
-:%0A        app.config%5B'OPEN311_SERVER'%5D = os.environ%5B'
+.get('OPEN311_SERVER', 
 OPEN
@@ -2382,18 +2382,25 @@
 RVER
-'%5D
+)
 %0A    
-if 
+app.config%5B
 'OPE
@@ -2412,19 +2412,19 @@
 API_KEY'
- in
+%5D =
  os.envi
@@ -2430,29 +2430,13 @@
 iron
-:%0A        app.config%5B
+.get(
 'OPE
@@ -2452,24 +2452,10 @@
 KEY'
-%5D = os.environ%5B'
+, 
 OPEN
@@ -2465,23 +2465,17 @@
 _API_KEY
-'%5D%0A    
+)
 %0A    app
@@ -2502,24 +2502,39 @@
 OTECTED'%5D = 
+os.environ.get(
 'PASSWORD_PR
@@ -2545,40 +2545,14 @@
 TED'
- in os.environ and (os.environ%5B'
+, str(
 PASS
@@ -2565,18 +2565,18 @@
 ROTECTED
-'%5D
+))
  == 'Tru
@@ -2581,18 +2581,8 @@
 rue'
-) or False
 %0A   
@@ -2611,48 +2611,23 @@
 %5D = 
-'PASSWORD' in os.environ and os.environ%5B
+os.environ.get(
 'PAS
@@ -2636,15 +2636,13 @@
 ORD'
-%5D or
+,
  ''
+)
 %0A   
@@ -2688,16 +2688,16 @@
  5100))%0A
-
     app.
@@ -2726,8 +2726,13 @@
 rt=port)
+%0A    

Use os.environ.get instead of lots of 'if in' statements for config