[Tutor] Stopping program execution
Magnus Lycka
magnus@thinkware.se
Thu Jan 30 19:43:09 2003
At 16:07 2003-01-30 -0800, Sean Abrahams wrote:
>I have a web script that checks to see if the user has a session
>cookie. If not, I want to display a page saying 'no session found,
>please login. yadda yadda yadda', and not execute the rest of the
>script. Thing is, I check for the session cookie through a separate
>module.
>
>import session
>id = session.checkSession()
># for example
>
>If there is a session, the id is returned, otherwise the error message
>is printed.
>
>Right now, I have the error message printing fine, but it continues to
>execute the rest of the script, which is not the behavior I'm looking
>for.
If session.checkSession() returns without providing a
return value, it will be the same as "return None"
This means that the calling script could for instance do
id = session.checkSession()
if id is None:
# There is no ongoing session for this client. Abort!
raise SystemExit
>def sessionCheck(session):
> try:
> id = session["id"]
>
> return id
> except KeyError, e:
> print "content-type: text/html"
> print
> print "No session found."
>
> # Stop script
You can do:
raise SystemExit
here instead.
In general, I think you should put all your code in functions.
Indent your main code four spaces, and make it look like this:
def main():
[The code that is now always run, except imports and
possibly some globals needed by other functions.]
if __name__ == '__main__':
main()
This style is more pythonic, and it will make it easier to
structure the code further. It will also enable you to
simply do "return" in main() instead of "raise SystemExit".
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se