Skip to content
Snippets Groups Projects
layer_times_postgres.py 1.48 KiB
Newer Older
#!/usr/bin/env python3
import os
import sys
import cgi
import json
import psycopg2
from psycopg2 import sql

pw_filename = "__POSTGRES_PASSWORD_FILE__"
connect_str = "host=__POSTGRES_HOST__ " \
              "port=__POSTGRES_PORT__ " \
              "dbname=__POSTGRES_DBNAME__ " \
              "user=__POSTGRES_USER__"
if not os.path.isfile(pw_filename) or '__' in connect_str:
    print("""Status: 500 Backend Misconfigured\n
Content-type: text/plain
Access-Control-Allow-Origin: *

Backend has not been configured properly and doesn't know how to communicate with the database.
Please contact site administrator.
""")
    sys.exit(1)

with open(pw_filename, 'r') as pw_file:
    password = pw_file.read().strip()
    connect_str += " password={}".format(password)


form = cgi.FieldStorage()
table_name = form['layer'].value

try:
    conn = psycopg2.connect(connect_str)
    with conn:
        with conn.cursor() as cur:
            cur.execute(sql.SQL("SELECT start_time FROM {} ORDER BY start_time").format(sql.Identifier(table_name)))
            times = cur.fetchall()
except psycopg2.errors.DataBaseError:
    print("""Status: 500 Database Error
Content-type: text/plain
Access-Control-Allow-Origin: *

Error requesting time information from database.
""")
    sys.exit(1)

# postgres returned a list of tuples
times = [time_tuple[0] for time_tuple in times]

print("Content-Type: application/json")
print("Access-Control-Allow-Origin: *")
print()  # blank line, end of headers
print(json.dumps(times))