Flask微型框架入门笔记
2016-04-15 16:26
344 查看
例程:
from flask import Flaskapp = Flask(__name__) # 新建一个Flask可运行实体(名字参数如果是单独应用可以使用__name__变量,如果是module则用模块名)
app.debug = True # 可以通过此参数设置Flash的DEBUG模式参数
@app.route("/") # 在运行实体上绑定URL路由
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run() # 运行Flash实体,如果要让网络上的人也可以访问,运行app.run(host=’0.0.0.0’)
特点:
1:请求集中于一个本地线程Thread-Locals,方法调用无需传参,即可实现存取功能2:安全方面的问题要谨慎考虑
3:出于安全考虑要严禁在Production环境设置DEBUG为True
安装:
Flash依赖两个库,分别是Werkzeug(一个WSGI工具集)和Jinja2(一个模板引擎)。代码段:
传递URL参数@app.route(’/user/<username>’, methods=[’GET’]) # 不带参数转换器,默认为字符串
def profile(username): pass
@app.route(’/post/<int:post_id>’) # 带上参数转换器int,表示参数post_id是一个整型参数
def post(post_id): pass
默认参数转换器有int, float and path
注:可以通过url_for方法获取URL路径,如url_for('post', post_id=12),打印出来便是/post?post_id=12
获取静态资源
url_for(’static’, filename=’style.css’) #默认存放路径为app_path/static
模板引擎
return render_template(’hello.html’, name=name) # 方式与django类似,查询地址在app_path/templates
重定向
return redirect(url_for(’login’))
自定义404错误
@app.errorhandler(404)
def page_not_found(error):
return render_template(’page_not_found.html’), 404
记录日志
app.logger.warning(’A warning occurred (%d apples)’, 42)
相关文章推荐
- 【Java】判断字符串是否含字母
- 内核模块参数例子
- TensorFlow非Root权限源码编译安装
- 【Vue】-(1) 安装
- oracle触发器
- 在线编程--链表中倒数第k个结点
- python中多进程+协程的使用以及为什么要用它
- JVM运行时数据区浅析
- bzoj1717(后缀数组)
- 我正在学习图形编程,请大家多帮助,谢谢!
- HTML中常见的各种位置距离(clientTop clientLeft clientWidth ClientHeight offsetleft offsettop offsetwidth offset
- PHP生成条形码
- 转windows服务安装启动报错误1053:服务没有及时响应启动或控制请求
- SQLSERVER数据库表各种同步技术
- 关于GDI+
- 怎么用navicat自动备份mysql数据库
- 二叉树的镜像
- Discuz! 全局变量 $_G 详解
- 剑指offer 面试题17: 合并两个排序的链表 题解
- android TextView设置自定义字体