项目结构:
/home/henry/dev/flask_henry
hello.py hello.pyc README.md templates venv_flask_henry
hello.py代码:
from flask import Flask
from flask_script import Manager
app = Flask(__name__)
manager = Manager(app)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)
if __name__ == '__main__':
manager.run()
报错:
(venv_flask_henry) henry@henry-virtual-machine:~/dev/flask_henry$ python hello.py runserver --host 0.0.0.0
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
[2017-11-26 14:11:30,844] ERROR in app: Exception on /user/HeLi [GET]
Traceback (most recent call last):
File "/home/henry/dev/flask_henry/venv_flask_henry/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/henry/dev/flask_henry/venv_flask_henry/local/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/henry/dev/flask_henry/venv_flask_henry/local/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/henry/dev/flask_henry/venv_flask_henry/local/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/henry/dev/flask_henry/venv_flask_henry/local/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "hello.py", line 14, in user
return render_template('user.html', name=name)
NameError: global name 'render_template' is not defined
127.0.0.1 - - [26/Nov/2017 14:11:30] "GET /user/HeLi HTTP/1.1" 500 -
注意到这一行:
NameError: global name ‘render_template’ is not defined
原因是:
hello.py中没有导入render_template
补上
from flask import render_template
即可。