Skip to content

Instantly share code, notes, and snippets.

@pilgrim2go
Forked from joshwilliams/run_server.pl.py
Created October 27, 2016 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pilgrim2go/24434ad1d5949231be9bd5df90908864 to your computer and use it in GitHub Desktop.
Save pilgrim2go/24434ad1d5949231be9bd5df90908864 to your computer and use it in GitHub Desktop.
An httpd-like thing in a PL/Python function
CREATE OR REPLACE FUNCTION run_server() RETURNS text
LANGUAGE plpythonu STRICT
AS $$
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class PGHandler(BaseHTTPRequestHandler):
def do_GET(self):
plpy.notice("Path: %s" % self.path)
if self.path.count('/') == 2 and self.path.split('/')[1] != "" and self.path.split('/')[2] != "":
nsp = plpy.quote_ident(self.path.split('/')[1])
tbl = plpy.quote_ident(self.path.split('/')[2])
try:
with plpy.subtransaction():
results = plpy.execute("SELECT * FROM %s.%s;" % (nsp,tbl))
except plpy.SPIError, e:
self.send_error(404, 'Table not found')
return
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(
"<html><head><title>AwfulServer %d</title></head><body><a href='/'>Back</a><table>"
% len(results)
)
self.wfile.write(
"<thead><tr>%s</tr></thead>"
% "".join(["<th>%s</th>" % col for col in results[0]])
)
self.wfile.write("\n".join( ["<tr>%s</tr>" % "".join(
["<td>%s</td>" % str(results[row][col]) for col in results[row]]
) for row in range(len(results))] ))
self.wfile.write("</table></body></html>")
return
return
server = HTTPServer(('', 8000), PGHandler)
plpy.notice('Started server')
server.serve_forever()
return ('Done')
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment