472,364 Members | 2,166 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,364 software developers and data experts.

except clause appears to be being skipped?

I can't figure out this problem Im having, I just can't understand why
it is ignoring the call I put in. First the code (This is a cherrypy
website):

import sys, cherrypy, html

class Root:
@cherrypy.expose
def index(self, pageid = "Index"):
selection = html.Page()
return selection.makeit(dex = pageid)
cherrypy.config.update({'server.socket_port': 2572, 'log.screen':
False})
cherrypy.quickstart(Root())
If you're not familiar with cherrypy, whats going on here is its
pulling a variable from the url and just passing that to my page class
that I created. The url would look like http://nonyaz.com/index?pageid=foo
and pageid would thus be foo.

and here is the class code stored in the html.py file that's causing
me all this grief:

class Page:
#Generic webpage assembler
def __init__(self):
#Open the header txt file for later use
self.headertxt = open("pages/header.html","r")
#self.footertxt = open("pages/footer.html","r")
def makeit(self,dex=""):
pagetitle, htmlbody = self.pager(dex)
return self.headerinsert(pagetitle) + htmlbody
def pager(self,dex):
#Input page filename, Output pagetitle and the HTML output
#Find out if the file requested actually exists
try:
j = dex + ".html"
textfile = open("pages/" + j, "r")
#If not 404' it
except:
self.err404(dex)

#The first line in the .html files is the title, this reads that one
line
pagetitle = textfile.readline()

#Put the remaining lines of HTML into a var
htmlbody = textfile.read()

#Return the results
return pagetitle,htmlbody

def headerinsert(self,pagetitle):
#Processes the header.html file for use. Input a page title,
outputs
#the compleated header with pagetitle inserted
headerp1 = ""
for i in range(5):
headerp1 += self.headertxt.readline()
headerp2 = self.headertxt.readline(7)
headerp3 = self.headertxt.readline()
headerp4 = self.headertxt.read()
return headerp1 + headerp2 + str.strip(pagetitle) + headerp3 +
headerp4
def err404(self,whatitis="N/A"):
#Page not found error page
return """<body bgcolor="#666666">
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<center>Sorry the page <em>""" + str(whatitis) + """</emdoes not
exist.<br />
<img src="/files/images/404.png" alt="Page cannot be found."></center>
</body>"""

This code does work when there is a valid page, aka when the try
statement executes with out exception. The the exception is raised
for when there is no file, that's where the problems come in, I want
it just to call the err404 function and return my 404 page, but it
seems to act like its not there and keeps on going, giving me this
error:

Traceback (most recent call last):
File "/home2/awasilenko/lib/python2.4/cherrypy/_cprequest.py", line
342, in respond
cherrypy.response.body = self.handler()
File "/home2/awasilenko/lib/python2.4/cherrypy/_cpdispatch.py", line
15, in __call__
return self.callable(*self.args, **self.kwargs)
File "/home2/awasilenko/webapps/cp/site.py", line 7, in index
return selection.makeit(dex = pageid)
File "/home2/awasilenko/webapps/cp/html.py", line 10, in makeit
pagetitle, htmlbody = self.pager(dex)
File "/home2/awasilenko/webapps/cp/html.py", line 25, in pager
pagetitle = textfile.readline()
UnboundLocalError: local variable 'textfile' referenced before
assignment

I know the except is being executed because I put a break in there for
testing purposes and it did break, but as for why its not pulling up
the 404 function and returning the error page, I have no idea.

Mar 24 '07 #1
2 1287
On Mar 24, 12:51 pm, AWasile...@gmail.com wrote:
[snip]
def pager(self,dex):
#Input page filename, Output pagetitle and the HTML output
#Find out if the file requested actually exists
try:
j = dex + ".html"
textfile = open("pages/" + j, "r")
#If not 404' it
except:
self.err404(dex)

#The first line in the .html files is the title, this reads that one
line
pagetitle = textfile.readline()
[snip]
File "/home2/awasilenko/webapps/cp/html.py", line 25, in pager
pagetitle = textfile.readline()
UnboundLocalError: local variable 'textfile' referenced before
assignment

I know the except is being executed because I put a break in there for
testing purposes and it did break, but as for why its not pulling up
the 404 function and returning the error page, I have no idea.
It *is* "pulling up the 404 function", which *is* returning your error
page. However all your except clause does is "self.err404(dex)" -- you
ignore the return value, and fall out of the except clause with
textfile undefined, with the expected consequences.

I'm not at all familiar with cherrypy, but you probably need to do
either:
errpage = self.err404(dex)
dosomethingwith(errpage, dex)
return
or simply:
return "404 page title", self.err404(dex)
[Actually it would be better style if the err404 method returned a
tuple of (pagetitle, pagebody), then your except clause contains
only:
return self.err404(dex)

The main point being to return instead of falling through the bottom
of the except clause. BTW, you should not use a bare except. Be a
little more specific, like except IOError:

Looking at the cherrypy docs would seem indicated. AFAIK there was a
v1 and a v2 with different naming conventions and there's now a v3 --
do ensure that you mention which version you are using if you need to
come back with more questions.

HTH,
John

Mar 24 '07 #2
On Mar 23, 10:29 pm, "John Machin" <sjmac...@lexicon.netwrote:
It *is* "pulling up the 404 function", which *is* returning your error
page. However all your except clause does is "self.err404(dex)" -- you
ignore the return value, and fall out of the except clause with
textfile undefined, with the expected consequences.
Humm I dident think had to put return when I called the 404 becuase
the def has a return on the end of that, but now that I think about it
more it makes sence.
>
I'm not at all familiar with cherrypy, but you probably need to do
either:
errpage = self.err404(dex)
dosomethingwith(errpage, dex)
return
or simply:
return "404 page title", self.err404(dex)
[Actually it would be better style if the err404 method returned a
tuple of (pagetitle, pagebody), then your except clause contains
only:
return self.err404(dex)
Both of you're suggestions worked, Change it to return the tuple.

>
The main point being to return instead of falling through the bottom
of the except clause. BTW, you should not use a bare except. Be a
little more specific, like except IOError:
Suggestion implemented, I figured you could be more specific with
exceptions but I must have glazed over that in my book when I read
about it.

Looking at the cherrypy docs would seem indicated.
Since I'm a noobie python'r (or programmer for that matter) most if
not all of my mistkaes are with python and the syntax, there is not
much to screw up with Cherrypy itself, but I'm sure I will find a way
to screw it up later :)
AFAIK there was a
v1 and a v2 with different naming conventions and there's now a v3 --
do ensure that you mention which version you are using if you need to
come back with more questions.

HTH,
John
Naming conventions eh? I guess I'm following conventions so far, I
havent ran into that problem yet (Knock Knock)

Thanks for you're help John, people like you make these newsgroups are
an invaluable resource :)

Mar 24 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: KefX | last post by:
This may have been discussed before, but I'm kind of confused as to why Python doesn't support having both an except ~and~ a finally clause, like this: try: raise RuntimeException except:...
7
by: Robert Brewer | last post by:
Alex Martelli wrote in another thread: > One sign that somebody has moved from "Python newbie" to "good Python > programmer" is exactly the moment they realize why it's wrong to code: > > ...
20
by: John Salerno | last post by:
I'm starting out with this: try: if int(text) 0: return True else: self.error_message() return False except ValueError: self.error_message()
5
by: Nebur | last post by:
I'm using the contract.py library, running Python 2.4.4. Now I'm confronted with the following exception backtrace: (...) File "/usr/lib/python2.4/site-packages/contract.py", line 1265, in...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.