Python Server Pages: Part 1
by Kirby W. Angell


Listing One

<HTML>
<HEAD>
<TITLE>Hello World</TITLE>
</HEAD>
<BODY>
$[include banner.psp]$
<H1>Hello World</H1>
<BR>
$[
Response.write( "Hello, %s, from Python Server 
                                Pages." % (Request.server["REMOTE_ADDR"]))
]$
<BR>
If your IP address was in the greeting above, you have 
                              installed Python Server Pages correctly.
</BODY>
</HTML>

Listing Two

__write__(  "<HTML>" )
__write__(  "<HEAD>" )
__write__(  "<TITLE>Hello World</TITLE>" )
__write__(  "</HEAD>" )
__write__(  "<BODY>" )
 ... statements included from banner.psp deleted ...
__write__(  "<H1>Hello World</H1>" )
__write__(  "<BR>" )

Response.write( "Hello, %s, 
             from Python Server Pages." % (Request.server["REMOTE_ADDR"]))
__write__(  "<BR>" )

__write__(  "If your IP address was in the greeting above, you have 
                                installed Python Server Pages correctly." )
__write__(  "</BODY>" )
__write__(  "</HTML>" )
__write__(  "" )


Listing Three

class cgEngine:
    # These constants are used to keep track of the state of the parser.
    stNormal = 0
    stFoundScriptPrefix1 = 1
    stScriptOpen = 2
    stFoundScriptPostfix1 = 3

    def parseLine( self, inBuf ):
        """Parses a text string into a list of tokens. Each token is either 
        a block of text or a python expression. Classes Text and Expression 
        are used to hold the text blocks and Python expressions. """
        tokens = []
        output = Text()
        expression = Expression()
        nPos = 0
                        
        while nPos < len(inBuf):
            char = inBuf[nPos]
            if char == '$':
                if self.state == cgEngine.stNormal:
                    self.state = cgEngine.stFoundScriptPrefix1
                elif self.state == cgEngine.stFoundScriptPostfix1:
                    self.state = cgEngine.stNormal
                    tokens.append( expression )
                    expression = Expression()
                elif self.state == cgEngine.stFoundScriptPrefix1:
                    output.append( "$" )
                elif self.state == cgEngine.stScriptOpen:
                    expression.append( char )
                else:
                    output.append( char )
            elif char == '[':
                if self.state == cgEngine.stFoundScriptPrefix1:
                    self.state = cgEngine.stScriptOpen
                   expression = Expression()
                    if output.empty() == 0:
                        tokens.append(output)
                        output = Text()
                elif self.state == cgEngine.stScriptOpen:
                    expression.append( char )
                else:
                    output.append( char )
            elif char == ']':
                if self.state == cgEngine.stScriptOpen:
                    self.state = cgEngine.stFoundScriptPostfix1
                elif self.state == cgEngine.stFoundScriptPostfix1:
                    expression.append( "]" )
                else:
                    output.append(char)
            else:
                if self.state == cgEngine.stScriptOpen and char != '\n':
                    expression.append( char )
                elif self.state == cgEngine.stFoundScriptPrefix1:
                    self.state = cgEngine.stNormal
                    output.append("$")
                    output.append(char)
                elif self.state == cgEngine.stFoundScriptPostfix1:
                    self.state = cgEngine.stScriptOpen
                    expression.append("]")
                    expression.append(char)
                elif char != '\n':
                    output.append(char)
            nPos = nPos + 1
        # if there is some output left
        if output.empty() == 0:
            tokens.append( output )
        # if there is an expression
        if expression.empty() == 0:
            tokens.append( expression )
        # if there are no tokens, this must be a blank line
        if len(tokens) == 0 and self.state != cgEngine.stScriptOpen:
            tokens.append( Text() )
        return tokens
    # convertToPython
    # Processes the input file, converting all script expressions into
    # python code and other text into print statements
    def __convertToPython( self, inFile, outFile, tabIndent = 0 ):
        inBuf = "spam"
        self.state = cgEngine.stNormal
        while len(inBuf):
            inBuf = inFile.readline()
            tokens = self.parseLine( inBuf )
            # find out if this is only a script line, or contains some output
            printLine = 0
            for token in tokens:
                if token.__class__ == Text:
                    printLine = 1
                    break
            # Write out this line of output
            outBuff = Text()
            if printLine == 0 and len(tokens):
                s = string.strip( str(tokens[0]) )
                if len(s) and s[len(s)-1] == ":" and s[0] != "#":
                    tabIndent = tabIndent + 1
                elif "end block" == string.lower(s):
                    tabIndent = tabIndent - 1
                    if tabIndent < 0: 
                        tabIndent = 0
                    tokens[0] = Expression("#" + self.indent(tabIndent) + s)
                elif string.lower(s)[:8] == "include ":
                    stmt,name = string.split( s, " ", 1 )
                    path,inFileName = os.path.split( inFile.name )
                    if len(path) == 0:
                        newInFile = open( name, "r" )
                    else:
                        newInFile = open( path + os.sep + name, "r" )
                    self.__convertToPython( newInFile, outFile, tabIndent )
                    newInFile.close()
                    tokens[0] = Expression("#" + self.indent(tabIndent) + s)
            for token in tokens:
                if token.__class__ == Text:
                    outBuff.append( ' + "' + escapeQuotes(str(token)) + '"' )
                    printLine = 1
                if token.__class__ == Expression:
                    if printLine:
                        outBuff.append( ' + str(' + str(token) + ')' )
                    else:
                       outBuff.append( str(token) )
            if printLine:
                # Write out the statement, trimming off the leading + sign.
                outFile.write( self.indent( tabIndent ) + "__write__( " 
                                              + str(outBuff)[2:] + " )\n" )
            else:
                outFile.write( str( outBuff ) + "\n" )
class Expression:
   "Contains a single python expression fragment parsed from a template file."
    def __init__(self, expr = ""):
        self.data = expr
    def append(self, s):
        self.data = self.data + s
    def empty(self):
        return len(self.data) == 0
    def __repr__(self):
        return self.data
class Text:
    "Contains a single text fragment parsed from a template file."
    def __init__(self):
        self.data = ""
    def append(self, s):
        self.data = self.data + s
    def empty(self):
        return len(self.data) == 0
    def __repr__(self):
        return self.data


Listing Four

<HTML>
<HEAD>
<TITLE>PSP Snoop</TITLE>
</HEAD>
<BODY>
<H1>PSP Snoop</H1>
<BR>
<PRE>
<H2>Request Headers:</H2>
<table>
$[
for varName in Request.server.keys():
]$
    <tr>
        <td>$[varName]$</td>
        <td>$[Request.server[varName]]$</td>
    </tr>
$[  
end block ]$
</table>
</BODY>
</HTML>


Listing Five

__write__(  "<HTML>" )
__write__(  "<HEAD>" )
__write__(  "<TITLE>PSP Snoop</TITLE>" )
__write__(  "</HEAD>" )
__write__(  "<BODY>" )
__write__(  "<H1>PSP Snoop</H1>" )
__write__(  "<BR>" )
__write__(  "<PRE>" )
__write__(  "<H2>Request Headers:</H2>" )
__write__(  "<table>" )
for varName in Request.server.keys():
    __write__(  "   <tr>" )
    __write__(  "       <td>" + str(varName) + "</td>" )
    __write__(  "       <td>" + str(Request.server[varName]) + "</td>" )
    __write__(  "" )
    __write__(  "   </tr>" )
#end block
__write__(  "</table>" )
__write__(  "</BODY>" )
__write__(  "</HTML>" )
__write__(  "" )





1


