4

尝试在 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 的稳定版和开发版,但错误仍然存​​在。任何帮助都感激不尽!谢谢,如果我的英语不是很好,我很抱歉。

4

1 回答 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>
>>> 
于 2012-10-14T05:15:52.033 回答