flask url_for TypeError

时间:2012-10-14 05:10:50

标签: python flask url-for

尝试在Flask中使用url_for方法时出错。我不确定它的原因是什么,因为我只关注Flask的快速启动。我是一个有点Python经验的Java人,想学习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 个答案:

答案 0 :(得分:4)

docsurl_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>
>>>