问题
Using Webpy. I have the following code in my app.py:
app = web.application(urls, globals())
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'count': 0, 'username': 'CRC'})
render = web.template.render('templates/', base="base", globals={'context': session, 'username': 'CRC'})
class Index(object):
def GET(self):
if not session:
session.count = 0
else:
session.count = 1
return render.hello_form()
def POST(self):
form = web.input(name="Nobody", greet="Hello")
greeting = "%s, %s" % (form.greet, form.name)
return render.index(greeting = greeting)
And then the following in my index html file:
$def with (greeting)
<p>
Hi <b>$context.username</b>
</p>
$if greeting:
I just wanted to say <em style="color: green; font-size: 2em;">$greeting</em>.
$else:
I just wanted to say <em style="color: green; font-size: 2em;">Default</em>.
<p>
<a href="/hello">Link Back To Form</a>
I'm seeing this once I submit the form: at /hello 'ThreadedDict' object has no attribute 'username'
Python /Library/Python/2.7/site-packages/web/session.py in getattr, line 64 Web POST /hello
Any thoughts on why I am seeing this? It obviously doesn't like what I am doing with username, but it's not clear to me why.
回答1:
As the error says, the context
variable (which is actually mapped to session
), has no attribute username
. Instead, you've defined username
as a global var itself.
Try accessing username
directly in your template as $username
, or make the assignment session['username'] = 'CRC'
in app.py, so that $context.username
is valid when you access it in the template file.
来源:https://stackoverflow.com/questions/10906963/webpy-sessions-with-templates