配置conda虚拟环境
conda create -n flasky python==3.6
activate flasky
pip install -r requirements.txt
requirements.txt
alembic==0.9.3
bleach==2.0.0
blinker==1.4
click==6.7
dominate==2.3.1
Flask==0.12.2
Flask-Bootstrap==3.3.7.1
Flask-HTTPAuth==3.2.3
Flask-Login==0.4.0
Flask-Mail==0.9.1
Flask-Migrate==2.0.4
Flask-Moment==0.5.1
Flask-PageDown==0.2.2
Flask-SQLAlchemy==2.2
Flask-WTF==0.14.2
html5lib==0.999999999
itsdangerous==0.24
Jinja2==2.9.6
Mako==1.0.7
Markdown==2.6.8
MarkupSafe==1.1.1
python-dateutil==2.6.1
python-dotenv==0.6.5
python-editor==1.0.3
six==1.10.0
SQLAlchemy==1.1.11
visitor==0.1.3
webencodings==0.5.1
Werkzeug==0.12.2
WTForms==2.1
第一个flask实例
创建web服务器实例
所有flask程序都必须创建一个程序实例,Web服务器使用WSGI协议把所有来自于客户端的请求都转发给这个对象处理。
from flask import Flask
app=Flask(__name__)
配置路由
# 静态路由
@app.route('/')
def hello():
return '<h1>hello!</h1>'
# 动态路由
@app.route('/user/<name>')
def user(name):
return '<h1>hello!%s</h1>' % name
开启服务
if __name__=='__main__':
app.run(debug=True)
服务器默认打开在localhost:5000
进入浏览器输入http://localhost:5000,请求交给hello方法处理
输入http://localhost:5000/user/alex,请求交给user方法处理
请求-响应循环
程序和请求上下文
在flask中有程序上下文、请求上下文两类
实例:获取User-Agent
# 上下文
from flask import request
@app.route('/useragent')
def useragent():
ret=request.headers.get('User-Agent')
return '<h1>%s</h1>' % ret
请求调度
URL映射,是URL和视图函数之间的对应关系
from hello import app
print(app.url_map)
输出:
Map([<Rule '/useragent' (GET, HEAD, OPTIONS) -> useragent>,
<Rule '/' (GET, HEAD, OPTIONS) -> hello>,
<Rule '/static/<filename>' (GET, HEAD, OPTIONS) -> static>,
<Rule '/user/<name>' (GET, HEAD, OPTIONS) -> user>])
其中,/static/<filename>是Flask添加的特殊路由,用于访问静态文件
响应
携带cookie
from flask import make_response
@app.route('/makecookie')
def makecookie():
res=make_response('<h1>cookies</h1>')
res.set_cookie('status','200')
return res
重定向
from flask import redirect
@app.route('/redi')
def redi():
return redirect('http://www.baidu.com')
flask扩展
flask-script命令行扩展
from flask_script import Manager
from hello import app
manager=Manager(app)
if __name__=='__main__':
manager.run()
加上扩展之后,直接运行会提示:
usage: hello2.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
执行python hello2.py runserver --help,提示:
usage: hello2.py runserver [-?] [-h HOST] [-p PORT] [--threaded]
[--processes PROCESSES] [--passthrough-errors] [-d]
[-D] [-r] [-R] [--ssl-crt SSL_CRT]
[--ssl-key SSL_KEY]
Runs the Flask development server i.e. app.run()
optional arguments:
-?, --help show this help message and exit
-h HOST, --host HOST
-p PORT, --port PORT
--threaded
--processes PROCESSES
--passthrough-errors
-d, --debug enable the Werkzeug debugger (DO NOT use in production
code)
-D, --no-debug disable the Werkzeug debugger
-r, --reload monitor Python files for changes (not 100% safe for
production use)
-R, --no-reload do not monitor Python files for changes
--ssl-crt SSL_CRT Path to ssl certificate
--ssl-key SSL_KEY Path to ssl key
Process finished with exit code 0
允许web服务器被本网段所有主机访问
python hello2.py runserver --host 0.0.0.0