烧瓶 url_for 类型错误

cob*_*obi 4 python url-for flask

尝试在 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__
Run Code Online (Sandbox Code Playgroud)

我的代码是这样的:

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)
Run Code Online (Sandbox Code Playgroud)

我已经尝试了 Flask 的稳定版和开发版,但错误仍然存​​在。任何帮助都感激不尽!谢谢你,如果我的英语不是很好,很抱歉。

Nat*_*usa 5

文件说,url_for需要一个字符串,而不是一个函数。您还需要提供一个用户名,因为您创建的路由需要一个。

改为这样做:

with app.test_request_context():
    print url_for('login', username='testuser')
Run Code Online (Sandbox Code Playgroud)

您收到此错误是因为字符串有__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>
>>> 
Run Code Online (Sandbox Code Playgroud)