6 Replies - 681 Views - Last Post: 24 December 2012 - 06:38 AM Rate Topic: -----

#1 liherb  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 25-November 12

Why can't I rename this variable?

Posted 24 December 2012 - 03:37 AM

Hi there. The following code is from a textbook that I'm learning.
'''
spreadsheet3.py is adapted to present the user with a logon screen first, before serving the spreadsheet.

it uses the default implementation of the Logon class, so the only user that will be authenticated will
be the user 'user' with the password 'secret'.

The few lines of code that had to be added are marked with the sting CHANGED
'''

import cherrypy

import os.path

current_dir = os.path.dirname(os.path.abspath(__file__))

# CHANGED, we need to import the logon module
import logon

class Root(object):
	
	spreadsheet = '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" href="/jquerytheme.css" type="text/css" media="screen, projection" />
<script type="text/javascript" src="/jquery.js" ></script>
<script type="text/javascript" src="/jquery-ui.js" ></script>
<script type="text/javascript" src="/static/js/jeditable.js" ></script>
<script type="text/javascript" src="/spreadsheet.js" ></script>
</head>
<body id="spreadsheet_example">
<div id="example"></div>
<p id="logging">
</p>
<script type="text/javascript">
$("#example").sheet({cols:8,rows:10});
</script>
</body>
</html>
	'''

	# CHANGED, we mount an instance of the Logon class
	logon = logon.Logon(path='/logon')
	
	@cherrypy.expose
	def index(self):
		# CHANGED, before serving the sheet, we authenticate the user. No returnpage argument is needed
		# as the defautl one is / 
		username=logon.checkauth('/logon')
		return Root.spreadsheet
	
if __name__ == "__main__":
	
	cherrypy.quickstart(Root(),config={
		# CHANGED, enable sessions
		'/': 
		{ 'tools.sessions.on': True },
		'/static':
		{ 'tools.staticdir.on':True,
		  'tools.staticdir.dir':os.path.join(current_dir,"static")
		},
		'/jquery.js':
		{ 'tools.staticfile.on':True,
		'tools.staticfile.filename':os.path.join(current_dir,"static","jquery","jquery-1.4.2.js")
		},
		'/jquery-ui.js':
		{ 'tools.staticfile.on':True,
		'tools.staticfile.filename':os.path.join(current_dir,"static","jquery","jquery-ui-1.8.1.custom.min.js")
		},
		'/jquerytheme.css':
		{ 'tools.staticfile.on':True,
		'tools.staticfile.filename':os.path.join(current_dir,"static","jquery","css","redmond","jquery-ui-1.8.1.custom.css")
		},
		'/spreadsheet.js':
		{ 'tools.staticfile.on':True,
		  'tools.staticfile.filename':os.path.join(current_dir,"spreadsheet.js")
		}
	})



The logon.py module is like this:
import cherrypy
import urllib.parse

import logging

def checkauth(logonurl="/", returntopage=False):
	returnpage=''
	if returntopage:
		returnpage='?returnpage='+cherrypy.request.script_name+cherrypy.request.path_info
		#returnpage='?returnpage='+cherrypy.request.base+cherrypy.request.script_name+cherrypy.request.path_info
		#returnpage='?returnpage='+cherrypy.request.path_info
	
	auth = cherrypy.session.get('authenticated',None)
	if auth == None : raise cherrypy.HTTPRedirect(logonurl+returnpage)
	return auth

class Logon:
	base_page = '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="/jquery.js" ></script>
<script type="text/javascript" src="/jquery-ui.js" ></script>
<style type="text/css" title="currentStyle">
	@import "/jquerytheme.css";
	@import "/static/css/logon.css";
</style>
</head>
<body id="logonscreen">
<div id="content">
%s
</div>
<script type="text/javascript">$("button").button({icons: {primary: 'ui-icon-power'}})</script>
</body>
</html>
'''

	# change the GET once in production: otherwise passwords may end up in the access log!
	
	# use <button> NOT <input> for submit and reet otherwise icons won't show!
	logon_screen = base_page % '''
<form class="login" action="%s/logon" method="GET">
<fieldset>
<label for="username">Username</label><input id="username" type="text" name="username" />
<script type="text/javascript">$("#username").focus()</script>
<label for="password">Password</label><input id="password" type="password" name="password" />
<input type="hidden" name="returnpage" value="%s" />
<button type="submit" class="login-button" value="Log in">Log in</button>
</fieldset>
</form>
'''

	not_authenticated = base_page % '''<h1>Login or password not correct</h1>'''

	def __init__(self,path="/logon",authenticated="/",not_authenticated="/"):
		self.path=path
		self.authenticated=authenticated
		self.not_authenticated=not_authenticated
		
	# change this to a proper check in a production environment
	@staticmethod
	def checkpass(username,password):
		if username=='user' and password=='secret': return True
		return False

	@cherrypy.expose
	def index(self,returnpage=''):
		if returnpage is None : returnpage = '' 
		return Logon.logon_screen % (self.path,urllib.parse.quote(returnpage))
	index._cp_config = {'tools.expires.on':True,'tools.expires.secs':0,'tools.expires.force':True}
	
	@cherrypy.expose
	def logon(self,username,password,returnpage=''):
		returnpage = urllib.parse.unquote(returnpage)
		#logging.error("####"+returnpage+"####")
		if Logon.checkpass(username,password):
			cherrypy.session['authenticated']=username
			if returnpage != '':
				raise cherrypy.InternalRedirect(returnpage)
			else:
				raise cherrypy.InternalRedirect(self.authenticated)
		raise cherrypy.InternalRedirect(self.not_authenticated)
	
	@cherrypy.expose
	def logoff(self,logoffurl=None):
		cherrypy.session.delete()
		cherrypy.lib.sessions.expire()
		#cherrypy.session['authenticated']=None
		if logoffurl is None :
			raise cherrypy.InternalRedirect(self.not_authenticated)
		raise cherrypy.InternalRedirect(logoffurl)
	


However, when I changed the variable name in the main module from
logon = logon.Logon(path='/logon')
into
logonnew = logon.Logon(path='/logon')
, the code breaks down saying:"NameError: global name 'logonnew' is not defined"

Why can't I change a variable name? I checked and checked just didn't find any reason. :cry2:/>

Is This A Good Question/Topic? 0
  • +

Replies To: Why can't I rename this variable?

#2 sepp2k  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2018
  • View blog
  • Posts: 3,046
  • Joined: 21-June 11

Re: Why can't I rename this variable?

Posted 24 December 2012 - 04:44 AM

Did you really just change that line and nothing else? Can you post the whole error message including the trace back?

This post has been edited by sepp2k: 24 December 2012 - 04:45 AM

Was This Post Helpful? 0
  • +
  • -

#3 liherb  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 25-November 12

Re: Why can't I rename this variable?

Posted 24 December 2012 - 05:20 AM

Thank you so much for your response.
I'm quite sure I only changed the variable name. Now I got this following message from localhost:8080

Quote

404 Not Found

The path '/logon' was not found.

Traceback (most recent call last):
File "C:\Python32\lib\site-packages\cherrypy\_cprequest.py", line 646, in respond
response.body = self.handler()
File "C:\Python32\lib\site-packages\cherrypy\lib\encoding.py", line 188, in __call__
self.body = self.oldhandler(*args, **kwargs)
File "C:\Python32\lib\site-packages\cherrypy\_cperror.py", line 387, in __call__
raise self
cherrypy._cperror.NotFound: (404, "The path '/logon' was not found.")


The reason for me trying to change that variable name is I wanted to figure out how cherrypy handle the object tree. I wanted to try my own custom "mount point" rather than the one provided by the textbook, and it broke down right there.
I really appreciate any hint about where I could be wrong. Thanks.
Was This Post Helpful? 0
  • +
  • -

#4 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5643
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: Why can't I rename this variable?

Posted 24 December 2012 - 05:58 AM

Your code uses the word "login" a lot. In many breakable ways. You use it as a class name, a variable name, a function name, and a module name. Kudos for covering all bases. It's a wonder it ever worked, though.

Look at your error: NameError: global name 'logonnew' is not defined

This is not an error you'd get when you assign a variable. Rather, this is the error you'll get when you try to access that variable out of scope. You probably didn't get burned by this before because when you thought you were accessing a variable, you were accessing one of the many other options for the name.
Was This Post Helpful? 2
  • +
  • -

#5 liherb  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 25-November 12

Re: Why can't I rename this variable?

Posted 24 December 2012 - 06:09 AM

View Postbaavgai, on 24 December 2012 - 05:58 AM, said:

Your code uses the word "login" a lot. In many breakable ways. You use it as a class name, a variable name, a function name, and a module name. Kudos for covering all bases. It's a wonder it ever worked, though.

Look at your error: NameError: global name 'logonnew' is not defined

This is not an error you'd get when you assign a variable. Rather, this is the error you'll get when you try to access that variable out of scope. You probably didn't get burned by this before because when you thought you were accessing a variable, you were accessing one of the many other options for the name.


Hi baavgai, thank you for your reply. I really don't think scope is the problem here. I defined that variable (logonnew) globally and I am using it locally within index() function. What's wrong about it?

I think your advice about confusion of 'login' and 'logon' is quite informative. thanks.
Was This Post Helpful? 0
  • +
  • -

#6 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5643
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: Why can't I rename this variable?

Posted 24 December 2012 - 06:24 AM

View Postliherb, on 24 December 2012 - 08:09 AM, said:

I really don't think scope is the problem here. I defined that variable (logonnew) globally and I am using it locally within index() function.


No, you're not using that variable in either index function. Current code would be helpful. Also, see comments below.


View Postliherb, on 24 December 2012 - 08:09 AM, said:

I think your advice about confusion of 'login' and 'logon' is quite informative. thanks.


When did I say "login"?!?

To be clear, here is the confusion:
# in module spreadsheet3.py

# module name
import logon

# variable name.  Also, module context, and confusing class name same 
logon = logon.Logon(path='/logon')

# method of instance variable logon or function in module?  unknown
username=logon.checkauth('/logon')

# in module logon.py

# now name use for function
def logon(self,username,password,returnpage=''):

# calling a static method in class with similar name
if Logon.checkpass(username,password):


Was This Post Helpful? 0
  • +
  • -

#7 liherb  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 25-November 12

Re: Why can't I rename this variable?

Posted 24 December 2012 - 06:38 AM

I got it to work!!!
I think it might be my browser's cache problem. When I restart my computer it just work as normal. Thank you guys!
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1