1. 变量
- __name__
__name__ 文件作为模块导入则为模块名称,作为执行文件则为__main__
2. Flask应用发布
Windows
- Cmd
C:\path\to\app> set FLASK_APP=app.py
C:\path\to\app> flask run
# 或者
C:\path\to\app> python -m flask run
- PowerShell
PS C:\path\to\app> $env:FLASK_APP = "hello.py"
PS C:\path\to\app> flask run
# 或者
PS C:\path\to\app> python -m flask run
注意:默认web应用ip为127.0.0.1,只有本机可以访问,若需要让所有ip都可访问:
flask run --host=0.0.0.0
告诉操作系统监听所有公开的ip
3. Flask Route路由
使用route()装饰器将函数绑定至URL
@app.route('/')
def hello_world():
return 'hello world (%s)!' % __name__
使用url_for()查找资源绑定的url
URL参数
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
# 指定参数类型int
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return 'Subpath %s' % subpath
参数类型:string,int,float,path,uuid
URL的唯一性
先看以下两个路由方式,“/projects/”以“/”结尾,“/about”则没有以“/”结尾。两种url格式在访问时有何不同?
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
经过测试,结果如下:
URL | 访问状态 |
---|---|
http://127.0.0.1:5000/projects/ | 正常 |
http://127.0.0.1:5000/projects | 重定向至http://127.0.0.1:5000/projects/ |
http://127.0.0.1:5000/about | 正常 |
http://127.0.0.1:5000/about/ | 404 不能访问 |
典型的URL地址是以“/”结尾的,类似访问一个文件夹,这有助于保持这些资源的URL唯一,有助于搜索引擎避免两次索引相同的页面。
4. Flask Quick Start
request
session
g
Message Flashing 与 get_flashed_messages
模板继承
MarkUp Html安全转义
request请求
从request请求中获取form参数:
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if valid_login(request.form['username'],
request.form['password']):
return log_the_user_in(request.form['username'])
else:
error = 'Invalid username/password'
# the code below is executed if the request method
# was GET or the credentials were invalid
return render_template('login.html', error=error)
从request中获取url参数:
# xxxxx?key=value
searchword = request.args.get('key', '')
File Upload
- Html 设置数据格式
enctype="multipart/form-data"
- 获取文件
通过request.files字典获取文件信息,得到的是标准的Python File数据;filename属性可获得上传时的文件名称,但是这可能是伪造的,直接使用filename保存文件不安全,可通过secure_filename获取文件名称:
from flask import request
from werkzeug.utils import secure_filename
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/' + secure_filename(f.filename))
Cookies
# 获取cookie
username = request.cookies.get('username')
# 设置cookie
resp = make_response(render_template(...))
resp.set_cookie('username', 'the username')
Redirect 重定向
from flask import abort, redirect, url_for
@app.route('/')
def index():
return redirect(url_for('login'))
Error 错误处理
@app.route('/login')
def login():
abort(401) # 指定错误类型,拒绝访问; 200 一切正常
this_is_never_executed()
# 定制错误处理
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html')
Responses 响应
使用make_response生成Response对象
@app.errorhandler(404)
def not_found(error):
resp = make_response(render_template('error.html'), 404)
resp.headers['X-Something'] = 'A value'
return resp
Session
session是在cookie上实现的,并经过加密;secret_key用于加密session,必须设置;
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
# 在使用session前,需设置secret_key
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@app.route('/')
def index():
# 判断session中是否存在key = ‘username'
if 'username' in session:
# 从session中获取key = 'username' 的 value
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# 设置session的值
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
# remove the username from the session if it's there
# 移除session中key = 'username' 的值
session.pop('username', None)
return redirect(url_for('index'))
Log 日志
Flask预先配置了日志实现
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')