不确定如何解决此瓶错误(Python)

时间:2015-05-31 23:21:27

标签: python import bottle

以下是我的导入:

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其他名称来消除错误。

1 个答案:

答案 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