繁体   English   中英

flask url_for TypeError

[英]flask url_for TypeError

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

文档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>
>>> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM