Is the following behaviour a problem intrinsic to python (One cannot change the value of a variable inside a loop if an exception is raised) or is it a problem with cherrypy (One cannot change the value of a variable inside a loop if an HTTPRedirect exception is raised)? I am trying to change the value of 'outp' from 'ORIGINAL' to 'NEWVALUE'.
I am running the following code snippet as a method within a class called "Root(object)" (print statement are highlighted for easy reading):
@cherrypy.expose
def tester(self, cancel=False, submit=False, clear=False, **data):
outp = "ORIGINAL"
if cherrypy.request.method == 'POST':
print outp ############ FIRST PRINT STATEMENT ##########
if True:
outp = "NEWVALUE"
print outp + '1' ############ SECOND PRINT STATEMENT #########
raise cherrypy.HTTPRedirect('/tester')
print outp + '2' ############ THIRD PRINT STATEMENT ##########
tmpl = loader.load('tester.html')
stream = tmpl.generate(outp=outp)
return stream.render('html', doctype='html')
I receive the following output:
ORIGINAL
NEWVALUE1
127.0.0.1 - - [10/Oct/2012:15:45:33] "POST /tester HTTP/1.1" 303 102
"http://localhost:8080/tester" "Mozilla/5.0 (X11; Linux x86_64; rv:10.0.7)
Gecko/20120829 Firefox/10.0.7"
ORIGINAL2
the value of outp only changes inside the if statement. If I comment out the exception raise "raise cherrypy.HTTPRedirect('/tester')":
@cherrypy.expose
def tester(self, cancel=False, submit=False, clear=False, **data):
outp = "ORIGINAL"
if cherrypy.request.method == 'POST':
print outp ############ FIRST PRINT STATEMENT ##########
if True:
outp = "NEWVALUE"
print outp + '1' ############ SECOND PRINT STATEMENT #########
#raise cherrypy.HTTPRedirect('/tester')
print outp + '2' ############ THIRD PRINT STATEMENT ##########
tmpl = loader.load('tester.html')
stream = tmpl.generate(outp=outp)
return stream.render('html', doctype='html')
I receive the following output:
ORIGINAL
NEWVALUE1
NEWVALUE2
I'm not necessarily looking for an in depth answer, just an idea of whether this is Python caused behaviour or Cherrypy caused behaviour. I could not mimic the behaviour by turning the code snippet into its own Python script so indications are that it's a Cherrypy issue.
Python, mostly. The HTTPRedirect, like any Python exception, suspends execution of the function. HTTPRedirect is essentially telling the client to make another HTTP request, which will run the function a second time without continuing from where it left off. Exceptions aren't loops: any variables local to that function will be new each time you run it.