我收到一条错误消息。这表明我误导了exec
,因为在' get'中有一些嵌套函数。那我怎么能避免这个问题呢?我的例程在交互式控制台中工作正常,所以我不知道我的代码中的子函数是什么:https://stackoverflow.com/questions/4484872/why-doesnt-exec-work-in-a-function-with-a-subfunction
ERROR 2018-02-16 20:57:49,507 wsgi.py:263]
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/Users/brian/googleapps/c4ica9o/main.py", line 2, in <module>
from views import MainPageParty, CreateParty, DeleteParty, EditParty, Host, Play, Start, \
SyntaxError: unqualified exec is not allowed in function 'get' it contains a nested function with free variables (views.py, line 132)
INFO 2018-02-16 20:57:49,514 module.py:812] default: "GET /host/BBB HTTP/1.1" 500 -
Python代码:
class Host(BaseHandler):
def get(self, ID):
key = ndb.Key(Pages,ID,Parties,ID)
party = key.get()
tables=party.tables
rounds=party.rounds
round_key = 'round'+str(rounds-1)
table_parent_key = ndb.Key(Pages,ID,Parties,ID,Rounds,round_key).get()
keys0 = ['p1','p2','p3','p4','s1','s2']
keys = ['p1','p2','p3','p4','s1','s2','swap']
dict = {}
for r in range(rounds):
round_key = 'round'+str(r)
names = []
values = []
for t in range(tables):
T=str(t)
T_key_name = 'table'+T
table_parent_key = ndb.Key(Pages,ID,Parties,ID,Rounds,round_key,Tables,T_key_name)
temp = table_parent_key.get()
if r == 0:
for k in keys0:
exec("name='r0t%d%s'" % (t,k))
names.append(name)
for k in keys0:
exec("value=temp.%s" % (k))
values.append(value)
dict.update({names[i]:values[i] for i in range(len(keys0))})
else:
for k in keys:
exec("name='r%dt%d%s'" % (r,t,k))
names.append(name)
for k in keys:
exec("value=temp.%s" % (k))
values.append(value)
dict.update({names[i]:values[i] for i in range(len(keys))})
template_values = {'ID':ID, 'dict': dict}
template = JINJA_ENVIRONMENT.get_template('host.html')
self.response.out.write(template.render( template_values))
import webapp2
from views import MainPageParty, CreateParty, DeleteParty, EditParty, Host, Play, Start, \
MainPage, CreatePage, DeletePage, EditPage, Unexpected, File, Wifi
app = webapp2.WSGIApplication([
('/', MainPage),
('/host/([\w]+)', Host),
],
debug=True)
答案 0 :(得分:1)
嵌套函数是为在
中实现字典理解而创建的隐式函数dict.update({names[i]:values[i] for i in range(len(keys))})
停止使用exec
。你用它做的事情毫无意义,与Python 3不兼容; jbch发布了你应该做的事情。
此外,停止混合标签和空格。这也是Python 3不兼容的,当显示标签宽度不是8个空格时,它看起来很混乱。