flask url_for TypeError
Question: I have an error when trying to use the url_for method in Flask. I'm not sure
what the cause of it because I only follow the Flask quick start. I'm a Java
guy with a bit of Python experience and want to learn Flask.

Here's the trace:

    
    
    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__
    

My code is like this:

    
    
    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)
    

I'm have tried both the stable and development version of Flask and the error
still occurs. Any help will be much appreciated! Thank you and sorry if my
English is not very good.


Answer: The [docs](http://flask.pocoo.org/docs/api/#flask.url_for) say that `url_for`
takes a string, not a function. You also need to provide a username since the
route you created requires one.

Do this instead:

    
    
    with app.test_request_context():
        print url_for('login', username='testuser')
    

You are receiving this error because strings have a `__getitem__` method but
functions do not.

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

