以下是我的导入:
from bottle import request, route, run, template, static_file, redirect
from urllib2 import urlopen, URLError, Request
from pymongo import MongoClient
from config.development import config
import json
这是违规行(我认为可能导致问题的另一行):
game_id = request.forms.get('game_id')
request = Request(config['singlegame_url'].replace('$GAMEID', game_id))
我得到的错误是:
UnboundLocalError("local variable 'request' referenced before assignment",)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/usr/local/lib/python2.7/site-packages/bottle.py", line 1732, in wrapper
rv = callback(*a, **ka)
File "app.py", line 23, in add
game_id = request.forms.get('game_id')
UnboundLocalError: local variable 'request' referenced before assignment
我的第一个想法是两个request
模块导致问题,但我无法通过搞乱导入和导入as
其他名称来消除错误。
答案 0 :(得分:2)
您必须将request
变量重命名为其他内容。
Python类在实际执行代码之前,由于request
而将变量名request = ...
保留为局部变量。
解释器然后执行您的行game_id = request.forms.get('game_id')
,其中request
是新保留的局部变量,未定义。
以下是同一问题的一个很好的例子:
>>> x = 1
>>> def f():
... print(x) # You'd think this prints 1, but `x` is the local variable now
... x = 3
>>> f()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
f()
File "<pyshell#4>", line 2, in f
print(x)
UnboundLocalError: local variable 'x' referenced before assignment