1.认识flask框架
Flask是一个轻量级的Web应用框架, 是使用Python语言来编写的。它基于 WerkzeugWSGI工具箱和 Jinja2模板引擎。
2.第一个应用
根据之前学习上的经验,第一个编写的应用便是Hello World。
程序代码:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
把它保存为 hello.py(或是类似的),然后用 Python 解释器来运行即可。运行之后的结果是:
* Running on http://127.0.0.1:5000/
当我们访问这个网址,便能看到Hello World!的字样了。
3.其他
通过搜索接触了一些其他方面的知识,比如
传递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’))
记录日志
app.logger.warning(’A warning occurred (%d apples)’, 42)