import os

if os.environ.get('FLASK_ENV') == 'production':
    from dotenv import load_dotenv, find_dotenv
    load_dotenv(find_dotenv(), override=True)

from flask import Flask, jsonify
from flask_cors import CORS

######################### FLASK APP
app = Flask(__name__)
CORS(app)

print("Value of WEB_CONCURRENCY is %s" % os.environ['WEB_CONCURRENCY'])
if int(os.environ['WEB_CONCURRENCY']) > 1:
    # sleep for a random interval to avoid all workers hitting
    # the database multiple times on bootup
    from random import randint
    from time import sleep
    interval = randint(4,20)
    print("Sleep for %d seconds to avoid too many concurrent db hits" % interval)
    sleep(interval)
import db


######################### ACTIONS
@app.route("/pbc")
def index():
    """
    Return organizational entities like Landesliste Hessen and the hessian election districts
    as well as the candidates in them
    """
    groupings = []
    candidates_by_district = db.get_candidates_grouped_by_district()
    for group in candidates_by_district:
        print(group)
        groupings.append(group)
    return jsonify({'candidates_grouped_by_district': groupings})


@app.route("/pbc/districts")
def districts():
    """
    Return organizational entities like Landesliste Hessen and the hessian election districts
    """
    districts = db.get_districts()
    for district in districts:
        districts.append({'id': district['_id', 'name': district['name']]})
    return jsonify({'districts': districts})


@app.route("/pbc/districts/<slug>")
def show_district(slug=None):
    """
    Return one organizational entity like Landesliste Hessen or a hessian election district
    as well as the candidates in them
    """
    groupings = []
    candidates = db.get_candidates_by_district(slug)
    for group in candidates_in_district:
        print(group)
        groupings.append(group)
    return jsonify({'district': groupings})


@app.route("/pbc/parties/<slug>")
def show_party(slug=None):
    """
    Return organizational entities like Landesliste Hessen and the hessian election districts
    as well as the candidates in them
    """
    membersOnLists = []
    candidates_by_party = db.get_candidates_by_party(slug)
    for group in candidates_by_party:
        print(group)
        groupings.append(group)
    return jsonify({'candidates_by_district': groupings})


def get_full_name(name):
    if not name:
        return None
    full_name = ''
    if name['titles']:
        full_name = full_name + name['titles']
    if name['forename']:
        full_name = full_name + ' ' + name['forename']
    if name['surname']:
        full_name = full_name + ' ' + name['surname']
    if name['affix']:
        full_name = full_name + ' ' + name['affix']
    return full_name


@app.route("/pbc/users/<slug>")
def show_candidate(slug=None):
    """
    """
    if slug is None:
        return "Candidate not provided"

    candidate = db.get_candidate(slug)
    if candidate is None:
        return "Candidate not found"

    full_name = get_full_name(candidate['name'])

    twitter_user = db.getUser(candidate['twitter_handle'])
    if twitter_user is None:
       return "Twitter user for candidate lost in the dark forest - make a donation to us to find this user."

    followers = {"numFollowers": twitter_user["twitter"]["followers_count"]}
    follower_stats = db.getFollowerStats(candidate['twitter_handle'])
    followers.update(follower_stats)

    json_output = {
        "content": "MEMBER", 
        "member": {
            "name": full_name,
            "party": candidate["election"]["party"],
            "twitter_handle": candidate['twitter_handle'],
            "facts" : candidate["facts"],
            "links" : candidate["links"],
            "photos" : candidate["photos"]
        },
        "twitter": {
            "profile_url": twitter_user["twitter"]["profile_image_url_https"],
        },
        "wordCluster": twitter_user.get("word_frequencies") or {'topics': []},
        "followers": followers,
        "retweets": {
              "numRetweets": 12,
              "numHumans": 11,
              "numBots": 1
        },
        "retweeters": {
              "numRetweeters": 22,
              "numHumans": 9,
              "numBots": 13
        },
        "election": candidate['election'],
        "botness": twitter_user["botness"] if "botness" in twitter_user else {}
    }

    return jsonify(json_output)


if __name__ == "__main__":
    port = os.environ.get('PORT') or 6755
    app.run(host="0.0.0.0", port=port)

@@ -7,16 +7,20 @@
  os%0A%0Aif 
+not 
 os.envir
@@ -325,33 +325,37 @@
 %25s%22 %25 os.environ
-%5B
+.get(
 'WEB_CONCURRENCY
@@ -355,17 +355,17 @@
 URRENCY'
-%5D
+)
 )%0Aif int
@@ -375,17 +375,21 @@
 .environ
-%5B
+.get(
 'WEB_CON
@@ -397,17 +397,17 @@
 URRENCY'
-%5D
+)
 ) %3E 1:%0A 
@@ -1353,26 +1353,10 @@
 s = 
-db.get_districts()
+%5B%5D
 %0A   
@@ -1372,16 +1372,23 @@
 rict in 
+db.get_
 district
@@ -1388,16 +1388,18 @@
 istricts
+()
 :%0A      
@@ -1424,16 +1424,20 @@
 (%7B'id': 
+int(
 district
@@ -1439,19 +1439,22 @@
 trict%5B'_
-id'
+key'%5D)
 , 'name'
@@ -1471,17 +1471,16 @@
 %5B'name'%5D
-%5D
 %7D)%0A    r

Serialize district id as int