【问题标题】:flask url_for TypeError烧瓶 url_for TypeError
【发布时间】:2012-10-14 05:10:50
【问题描述】:

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

【问题讨论】:

    标签: python flask url-for


    【解决方案1】:

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

    【讨论】:

    • 我的错,你是对的。但是现在又出现了一个错误。 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)
    • 您的问题是它希望登录功能具有提供的用户名。请改用 url_for('login', username='cobicobi')。
    • 啊,我想我现在明白了。你是对的。 url_for 至少需要在端点中定义参数。如果我没有在端点中定义参数,url_for 将与参数一起使用或不使用。但是如果我在其中定义了一个参数,我还必须在url_for 调用中提供该参数。
    猜你喜欢
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2016-01-12
    • 2012-05-06
    • 1970-01-01
    • 2018-07-13
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多