web-dev-qa-db-ja.com

なぜこのNameErrorが発生するのですか:名前 'url_for'が定義されていません。

flaskチュートリアルの指示に従ってURLを作成しようとしています

http://flask.pocoo.org/docs/0.11/quickstart/

しかし、私はこのNameErrorを取得し続けています

名前「url_for」は定義されていません

これはコードです:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def Index() : pass

@app.route ('/ login')
def loGin() : pass

@app.route('/user/<username>')
def profile( username) : pass


with app.test_request_context() :
    print url_for('Index')
    print url_for('loGin')
    print url_for('loGin', next='/')
    print url_for('profile', username = 'Jon DD')

これは合計エラーメッセージです。

eloiim:minimalapp iivri.andre$ export FLASK_APP=Greet.py
eloiim:minimalapp iivri.andre$ flask run 
Traceback (most recent call last):
  File "/usr/local/bin/flask", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 478, in main
    cli.main(args=args, prog_name=name)
  File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 345, in main
    return AppGroup.main(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/click/core.py", line 696, in main
    rv = self.invoke(ctx)
  File "/usr/local/lib/python2.7/site-packages/click/core.py", line 1060, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/usr/local/lib/python2.7/site-packages/click/core.py", line 889, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/local/lib/python2.7/site-packages/click/core.py", line 534, in invoke
    return callback(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/click/decorators.py", line 64, in new_func
    return ctx.invoke(f, obj, *args[1:], **kwargs)
  File "/usr/local/lib/python2.7/site-packages/click/core.py", line 534, in invoke
    return callback(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 388, in run_command
    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
  File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 124, in __init__
    self._load_unlocked()
  File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 148, in _load_unlocked
    self._app = rv = self.loader()
  File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 209, in load_app
    rv = locate_app(self.app_import_path)
  File "/usr/local/lib/python2.7/site-packages/flask/cli.py", line 89, in locate_app
    __import__(module)
  File "/Users/iivri.andre/Documents/minimalapp/Greet.py", line 16, in <module>
    print url_for('Index')
NameError: name 'url_for' is not defined

問題が何であるかわかりません。

11
siur

それをインポート行に追加します。

from flask import Flask, url_for
18
abigperson