-
-
Save pilgrim2go/24434ad1d5949231be9bd5df90908864 to your computer and use it in GitHub Desktop.
An httpd-like thing in a PL/Python function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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