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

Unsure how to resolve this Bottle error (Python)

这是我的导入:

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 另一个名称来消除错误。

您必须将 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