473,396 Members | 1,933 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 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 1382
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.