Flask url_for TypeError

I have an error while trying to use the url_for method in Flask. I am not sure what the reason for this is, because I only run Flask quickly. I am 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 looks 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 have tried both the stable and the Flask development version, and the error is still happening. Any help would be much appreciated! Thank you and sorry if my English is not very good.

+4
source share
1 answer

docs says url_for accepts 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 get 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> >>> 
+4
source

Source: https://habr.com/ru/post/1439609/


All Articles