Flask微型框架入门札记
例程:
from flask import Flask
app = 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)