def connect_to_db(app):
    # reads the database name from a YAML file
    DB_NAME = get_secret_key('DB_NAME')

    DB_URI = f"postgresql:///{DB_NAME}"
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
    db.app = app
    db.init_app(app)
Ejemplo n.º 2
0
def get_hospitals():
    """Get list of hospitals in SF where ambulances transport patients."""

    DATA_DIR = get_secret_key('DATA_DIR')
    sf_hospitals_fp = DATA_DIR + "sf_hospitals.txt"

    hospitals = []

    with open(sf_hospitals_fp, 'r') as f:
        for hospital in f.readlines():
            hospital_data = hospital.split("|")
            hospital_name = hospital_data[0].strip()
            hospital_address = hospital_data[1].strip()
            lct = get_coords_from_address(hospital_address)
            hospitals.append(
                (hospital_name, hospital_address, lct.longitude, lct.latitude))

    return hospitals
Ejemplo n.º 3
0
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
from jinja2 import StrictUndefined

from code.db_model import connect_to_db
from code.key_utils import get_secret_key

app = Flask(__name__)

from code.flaskr import views

# reads the app key from a YAML file
APP_KEY = get_secret_key('APP_KEY')
app.secret_key = APP_KEY

# Raises an error in the case of an undefined variable in Jinja2.
app.jinja_env.undefined = StrictUndefined

if __name__ == "__main__":
    # We have to set debug=True here, since it has to be True at the
    # point that we invoke the DebugToolbarExtension
    app.debug = False

    # make sure templates, etc. are not cached in debug mode
    app.jinja_env.auto_reload = app.debug

    connect_to_db(app)

    # Use the DebugToolbar
    DebugToolbarExtension(app)
Ejemplo n.º 4
0
def get_medical_calls(filename='Med_Calls_with_Tracts.pkl'):
    """Read the pickled dataframe of SF medical calls."""

    DATA_DIR = get_secret_key('DATA_DIR')

    return pd.read_pickle(DATA_DIR + filename)
                         GMapOptions
from sqlalchemy.sql import functions as func

from code.key_utils import get_secret_key
from code.flaskr import app
from code.db_model import db, \
                          connect_to_db, \
                          MedicalCall, \
                          TractGeometry
from code.mappings import AMBULANCE_UNITS, \
                          PRIORITY_CODES, \
                          GROUPING_FREQ
from code.tract_tools import get_tract_geom


GMAP_API_KEY = get_secret_key('GMAP_API_KEY')

class StatsPlotter:
    """Plotting class for tract statistics.

    Optional filtering can be done based starting date and end date. Dates are
    strings formatted as %Y-%m-%d, e.g. '2019-02-13'."""
    def __init__(self,
                 tract_id=None,
                 min_date=None,
                 max_date=None):
        connect_to_db(app)

        if not min_date:
            min_date = db.session.query(
                func.min(MedicalCall.received_dttm)
Ejemplo n.º 6
0
    @contextmanager
    def session_scope():
        """Provide a transactional scope around creating a postgis extension
        when the database is being created."""
        session = Session(bind=db.engine.connect())

        try:
            yield session
            session.commit()
        except:
            session.rollback()
            raise
        finally:
            session.close()

    DB_NAME = get_secret_key('DB_NAME')
    DB_URI = f"postgresql:///{DB_NAME}"

    if not database_exists(DB_URI):
        create_database(DB_URI)
        with session_scope() as session:
            session.execute("CREATE SCHEMA postgis;")
            session.execute(
                "ALTER DATABASE medical_calls_db SET search_path=public, postgis, contrib;"
            )
            session.execute("CREATE EXTENSION postgis SCHEMA postgis;")

    # Create the tables in the database.
    db.create_all()

    with session_scope() as session:
import pandas as pd
import geopandas as gpd
from shapely.geometry import Polygon
from geoalchemy2.shape import to_shape

from code.key_utils import get_secret_key


DATA_DIR = get_secret_key('DATA_DIR')


def get_updated_tract_data(tracts_filename):
    """Make Tracts() object, with the boundaries as `shapely` polygons."""

    tracts = Tracts(tracts_filename=tracts_filename)
    tracts.get_boundaries()

    return tracts


def get_tract_geom(tract):
    """Extract the geometry of a specific tract from the database."""
    # hacky way to avoid circular imports--not pretty...
    # TODO: Fix it?!
    from code.flaskr import app
    from code.db_model import db, \
                              connect_to_db, \
                              TractGeometry

    connect_to_db(app)
Ejemplo n.º 8
0
                          AMBULANCE_UNITS, \
                          FEATURE_COLS
from code.location_tools import get_new_incident_coords, \
                                get_new_incident_tract, \
                                get_locations_as_shape
from code.utils import set_time_features, \
                       load_model, \
                       set_new_incident_priority_code, \
                       set_new_incident_unit_type, \
                       predict_eta, \
                       find_dist_to_closest_hospital, \
                       find_dist_to_closest_fire_station, \
                       get_fig_components
from code.key_utils import get_secret_key

CODE_DIR = get_secret_key('CODE_DIR')
FLASK_DIR = f"{CODE_DIR}/flaskr/"


@app.route('/')
def index():
    """Homepage."""

    return render_template("homepage.html")


@app.route('/about')
def about():
    """About page."""

    return render_template("about.html")