第2章 程序的基本结构
# encoding=utf-8
from flask import Flask, request, redirect, make_response
from flask_script import Manager
app = Flask(__name__)
# 添加命令行解析功能
manager = Manager(app)
@app.route('/')
def index():
# request object
user_agent = request.headers.get('User-Agent')
return '<h1>hello world!</h1>\r\n<p>Your browser is {}</p>'.format(user_agent)
# return response, status code
# return '<h1>bad request</h1>',400
# redirect
# return redirect('http://www.baidu.com')
# make response
# response = make_response('<h1>This document carries a cookie!</h1>')
# response.set_cookie('answer', '42')
# return response
@app.route('/user/<name>')
def user(name):
return '<h1>hello, {}</h2>'.format(name)
@app.route('/user/<id>')
def get_user(id):
user = load_user(id)
if not user:
abort(404)
return '<h1>hello, {}</h1>'.format(user.name)
if __name__ == '__main__':
# app.run(debug=True)
manager.run()
2.6 flask扩展
学到了扩展,Flask-Script别说使用,安装先喝了一壶
python2下 flask-script的情况
先看看书中做法:
安装方式
(venv) $ pip install flask-script
导入方式:
示例 2-3 hello.py:使用 Flask-Script
from flask.ext.script import Manager
环境:python 2.7.6,flask 1.0.2,所以应该不是版本的冲突吧?
报错:ImportError: No module named ext.script
更换导入方式:from flask_script import Manager
依然报错ImportError
deactivate 退出虚拟环境再source venv/bin/activate进入,然并卵
看到一贴:
no module named flask.ext.moment
在虚拟环境(取名:venv)下继续安装:
pip install Flask-Script(显示:Requirement already satisfied)
pip install Flask-Moment
依然报错:ImportError: No module named ext.script
更换导入方式:from flask_script import Manager
于是成功了吧?:
usage: hello.py [-?] {shell,runserver} ...
positional arguments:
{shell,runserver}
shell Runs a Python shell inside Flask application context.
runserver Runs the Flask development server i.e. app.run()
optional arguments:
-?, --help show this help message and exit
python3下 flask-script的情况
后来使用python3的venv安装了虚拟环境(取名:py3)在py3环境下,导入报错,以上方法均不起作用,可见虚拟环境(py3)不被支持。。。
用python2的virtualenv安装虚拟环境(取名:py),在py环境下,运行python hello.py报错,运行python3 hello.py成功,显示:usage: hello.py [-?] {shell,runserver} …
不在虚拟环境py/py3下,运行python/python2/python3 hello.py均成功,所以说是虚拟环境的锅么。。。。。。
python3的安装,然并卵
默默去安装了3.6。。。Ubuntu怎样安装Python3.6,半路get到新技能apt-fast)
因为安装好了py3.6,于是在新建文件夹使拥venv开启虚拟环境