# Copyright (c) Daniel Sheffield 2022
# All rights reserved.
from bottle import route, run, template, response
import psycopg
from psycopg import Cursor
import os
user = os.getenv('USER')
password = os.getenv('PASSWORD')
host = 'host=localhost'
conn: Cursor = psycopg.connect(f"{host} dbname=pgdb user={user} {password}")
statement = """SELECT
  table_to_xml_and_xmlschema('pg_random_view_default_if_null'::regclass,
  false, false, ''::text);"""
heading = """<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="https://shandan.one/xml/pg_view_style.xsl"?>
"""

@route('/pyapi/random')
def index():
    try:
        with conn.cursor() as cur:
            xml = cur.execute(statement).fetchone()[0]
    finally:
        conn.commit()
    response.content_type = 'application/xhtml+xml; charset=utf-8'
    return f"{heading}{xml}"

run(host='192.168.0.20', port=11888)
