flask url_for TypeError

4
当我尝试在Flask中使用url_for方法时,出现了错误。我不确定原因是什么,因为我只是按照Flask的快速入门进行操作。我是一名Java程序员,有一点Python经验,想学习Flask。
以下是错误追踪信息:
Traceback (most recent call last):
  File "hello.py", line 36, in <module>
    print url_for(login)
  File "/home/cobi/Dev/env/flask/latest/flask/helpers.py", line 259, in url_for
    if endpoint[:1] == '.':
TypeError: 'function' object has no attribute '__getitem__

我的代码如下:

from flask import Flask, url_for
app = Flask(__name__)
app.debug = True

@app.route('/login/<username>')
def login(): pass

with app.test_request_context():
  print url_for(login)

我尝试过Flask的稳定版和开发版,但错误仍然存在。非常感谢任何帮助!如果我的英语不是很好,请原谅。

1个回答

5
文档中提到url_for需要传入字符串而不是函数。因为您创建的路由需要提供用户名,所以您还需要提供用户名。请按照以下方式操作:
with app.test_request_context():
    print url_for('login', username='testuser')

您收到此错误是因为字符串具有__getitem__方法,但函数没有。
>>> def myfunc():
...     pass
... 
>>> myfunc.__getitem__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__getitem__'
>>> 'myfunc'.__getitem__
<method-wrapper '__getitem__' of str object at 0x10049fde0>
>>> 

我的错,你是对的。但现在出现了另一个错误。 print url_for('login') File "/home/cobi/Dev/env/flask/latest/flask/helpers.py", line 296, in url_for return appctx.app.handle_url_build_error(error, endpoint, values) File "/home/cobi/Dev/env/flask/latest/flask/helpers.py", line 289, in url_for force_external=external) File "/home/cobi/Dev/env/flask/latest/venv/local/lib/python2.7/site-packages/Werkzeug-0.8.3-py2.7.egg/werkzeug/routing.py", line 1607, in build raise BuildError(endpoint, values, method) werkzeug.routing.BuildError: ('login', {}, None) - cobicobi
您的问题在于它期望登录函数提供了用户名。请改用url_for('login', username='cobicobi')。 - Nathan Villaescusa
啊,我现在明白了。你说得对。url_for 至少需要在端点中定义一个参数。如果我在端点中不定义参数,则 url_for 将可以使用带参数或不带参数的方式工作。但是,如果我在其中定义了一个参数,那么在 url_for 调用中也必须提供该参数。 - cobicobi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接