Sharedwww / ss / ss.pyOpen in CoCalc
#! /usr/bin/env sage-python

#*****************************************************************************
#       Copyright (C) 2006 William Stein <[email protected]>
#
#  Distributed under the terms of the GNU General Public License (GPL)
#
#    This code is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    General Public License for more details.
#
#  The full text of the GPL is available at:
#
#                  http://www.gnu.org/licenses/
#
#
# CREDITS:
#
# * Inspired by Python cookbook code:
#      (put url here....)
#
# * Some design was joint work with Henry Cohn (of Microsoft Research)
#   and Alex Clemesha
#
# CHANGES:
#    2006-04-18: initial version in progress
#
#*****************************************************************************

"""

"""

import BaseHTTPServer 
from StringIO import StringIO 
import os, sys
import shutil

import sage.all as sage

output = []
input = []

class MyHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_GET(self): 
	global output, input
        f = self.send_head() 
	f.write("<html><head><title>SAGE Server</title></head>\n")
	f.write('<body><H1>SAGE Server</H1>\n')
	f.write('</body></html>')
	cmd = self.path[1:].replace('%20',' ')
	try:
	    out = sage.sage0.eval(cmd)
	except (RuntimeError, TypeError), msg:
	    out = msg
	input.append(cmd)
	output.append(out)
	for i in range(len(output)):
	    f.write('<table bgcolor=black cellpadding=3><tr bgcolor=white><td width=20%%>In:</td><td><pre>%s</pre></td></tr></table>'%input[i])
	    f.write('<table bgcolor=purple cellpadding=3><tr bgcolor=white><td width=20%%>Out:</td><td><pre>%s</pre></td></tr></table>'%output[i])
	    f.write('\n<hr>\n')
	f.seek(0)
	shutil.copyfileobj(f, self.wfile) 
	f.close() 
        return f 
 
    def do_HEAD(self): 
        f = self.send_head() 
        if f: 
            f.close() 
 
    def send_head(self): 
        path = self.path 
        self.send_response(200)
	self.send_header("Content-type", 'text/html') 
        self.end_headers() 
        return StringIO() 
 
def main(HandlerClass = MyHTTPRequestHandler, 
         ServerClass = BaseHTTPServer.HTTPServer): 
    BaseHTTPServer.test(HandlerClass, ServerClass) 
 
if __name__ == '__main__':
    print "Starting SS: Sage Server"
    print "Press ctrl-C to exit."
    try:
        main()
    except KeyboardInterrupt:
        print "Shutting down server."
        sys.exit(0)