-
Notifications
You must be signed in to change notification settings - Fork 0
Flask Learning Report csd
YagoToasa edited this page Oct 19, 2019
·
1 revision
- Edit Configuration ⟹ FLASK_DEBUG
-
route()`:将函数绑定到URL上
@app.route('/') def index(): return 'Index'
-
<converter:variable_name>
:在URL中添加变量@app.route('/user/<username>') def show_user_profile(username): # show the user profile for that user return "User %s" % username
-
Converter type
Type Description string 任何不包含 /
的文本int 正整数 float 正浮点数 path 类似string,可以包含 /
uuid UUID字符串
-
-
route('/about/')
- 使用不带
/
的URL访问该地址,Flask会自动重定向 - 可将其看作是一个文件夹
- 使用不带
-
route('/about')
- 使用带
/
的URL访问该地址时,会得到一个NOT FOUND
错误 - 可将其看作是一个文件
- 使用带
-
url_for()
- 参数1:函数名
- 关键字参数:任意数目,关键字对应URL中的变量
- 未知变量将添加到URL中作为查询参数
- 优点:
- 便于修改
- 便于处理特殊字符的转义及Unicode数据
- 绝对路径,避免相对路径的副作用
-
HTTP
- 默认:路由只回应
GET
请求 -
route('/', methods=['GET', 'POST'])
:处理不同的HTTP方法
- 默认:路由只回应
- 一般是CSS和JavaScript文件,通常存放在
/static
中; - 相应的URL:
url_for('static', filename='<file-name>')
render_template()
:Flask会在templates
文件夹中寻找指定模版
-
Module:
/application.py /templates /index.html
-
Package:
/application /__init__.py /templates /index.html
-
redirect()
-
abort()
-
errorhandler()
装饰器可以自定义出错页面@app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404 # 404:页面不存在;Default-200:一切正常
-
- 转换规则
返回值 | 响应 |
---|---|
响应对象 | -------- |
字符串 | 字符串+ 省缺参数 |
字典 | jsonify |
元组 | (response,status)/(response,headers)/(response, status,headers) |
-
Make_response()
包裹返回表达式,获取响应对象,可以对响应对象进行修改后再返回
-
允许在不同请求间存储信息;
-
相当于用密钥签名加密的cookie;
-
使用session前,必须设置一个密钥,可以使用
os.urandom()
生成密钥。
- 记录请求结束时的消息,并仅允许下一个请求访问。
- 一般会结合Templates来使用
- 浏览器及网络服务器对cookie的限制,可能会导致消息闪现失败。
-
app.logger.debug('debug-message') app.logger.warning('warning-message') app.logger.error('error-message')