以下讲解假设你对 python 有基本了解,熟悉 wsgi,以及了解某种 python web framework。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "HELLO WROLD"
if __name__ == '__main__':
app.run(debug=True)
route() 装饰器支持变量规则,用 <variable_name> 表示,还可以制订一个转换器,例如:
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@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('/user/<path:location>')
def show_path(location):
return location
有三种转换器:
int accepts integers
float like int but for floating point values
path like the default but also accepts slashes
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == "POST":
return 'post'
else:
return 'get'
在 package 或则 module 同目录下创建 static 目录
url_for('static', filename='style.css')
默认 Flask 配置 JinJia2 作为模板引擎,因为他们是一家的,Flask 会在 templates 目录下查找模板文件,如果 application 是一个 module,那么这个 templates 目录与 application 同级目录,如果他是一个 package:
/application.py /templates
/hello.html
/application
/__init__.py
/templates
/hello.html
渲染模板使用 render_template()
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html',name=name)
JinJia2 模板的语法和 Mako 以及 django 的语法都差不多,可以稍作了解
<!doctype html>
<title>Hello from Flask</title>
{ % if name % }
<h1>Hello { { name } }!</h1>
{ % else % }
<h1>Hello World!</h1>
{ % endif % }
